Manual do PHP

Stig Sæther Bakken
Alexander Aulbach
Egon Schmid
Jim Winstead
Lars Torben Wilson
Rasmus Lerdorf
Andrei Zmievski
Jouni Ahto

Editado por

Stig Sæther Bakken
Egon Schmid
Renato Arruda
André L F S Bacci
Anderson Fortaleza
João Prado Maia
Claudio Pereira
Lucas Rocha
Alessander Pery Lopes Thomaz
Taniel Franklin
Thomas Gonzalez Miranda
Ernani Joppert Pontes Martins
Fernando Correa da Conceição

29-01-2003

Copyright

Este manual tem © Copyright 1997 - 2003 para o PHP Documentation Group. Os membros deste grupo são listados na primeira página deste manual.

Este manual pode ser redistribuído sob os termos da Licença Pública Geral (GNU) conforme publicada pela Free Software Foundation; a versão 2 da Licença ou (a seu critério) qualquer versão posterior.

A seção 'Extendendo PHP 4.0' deste manual tem copyright © 2000 para Zend Technologies, Ltd. Este material pode ser distribuido somente sob os termos e condições descritas na Open Publication License v1.0 ou posterior (a versão mais recente está disponível em http://www.opencontent.org/openpub/).


Índice
Prefácio
I. Começando
1. Introdução
2. A simple tutorial
3. Instalação
4. Configuração
5. Security
II. Referência da Linguagem
6. Sintaxe básica
7. Tipos
8. Variáveis
9. Constantes
10. Expressões
11. Operadores
12. Estruturas de Controle
13. Funções
14. Classes e Objetos
15. Referências
III. Características
16. HTTP authentication with PHP
17. Cookies
18. Gerenciar o upload de arquivos
19. Using remote files
20. Connection handling
21. Persistent Database Connections
22. Safe Mode
23. Utilizando o PHP na linha de comando
IV. Referência das Funções
I. Apache
II. Funções para manipulação de arrays
III. Aspell functions [deprecated]
IV. BCMath Funções Matemáticas de Precisão Arbitrária
V. Funções de compactação com Bzip2
VI. Calendar functions
VII. CCVS API Functions
VIII. COM support functions for Windows
IX. Classes e Objetos
X. ClibPDF functions
XI. Crack functions
XII. CURL, Client URL Library Functions
XIII. Cybercash payment functions
XIV. Crédit Mutuel CyberMUT functions
XV. Cyrus IMAP administration functions
XVI. Character type functions
XVII. Database (dbm-style) abstraction layer functions
XVIII. Funções data e hora
XIX. dBase functions
XX. DBM Functions [deprecated]
XXI. dbx functions
XXII. DB++ Functions
XXIII. Direct IO functions
XXIV. Diretórios
XXV. DOM XML functions
XXVI. .NET functions
XXVII. Error Handling and Logging Functions
XXVIII. FrontBase Functions
XXIX. filePro functions
XXX. Filesystem (Sistema de arquivos)
XXXI. Forms Data Format functions
XXXII. FriBiDi functions
XXXIII. FTP functions
XXXIV. Function Handling functions
XXXV. Gettext
XXXVI. GMP functions
XXXVII. HTTP functions
XXXVIII. Hyperwave functions
XXXIX. Hyperwave API functions
XL. iconv functions
XLI. Image functions
XLII. IMAP, POP3 and NNTP functions
XLIII. Informix functions
XLIV. InterBase functions
XLV. Ingres II functions
XLVI. IRC Gateway Functions
XLVII. PHP / Java Integration
XLVIII. LDAP functions
XLIX. Funções de E-Mail
L. mailparse functions
LI. Matemática e Trigonometria
LII. Multi-Byte String Functions
LIII. MCAL functions
LIV. Mcrypt Encryption Functions
LV. MCVE Payment Functions
LVI. Mhash - Funções de hash
LVII. Mimetype Functions
LVIII. Funções Microsoft SQL Server
LIX. Ming functions for Flash
LX. Funções de Miscelânea
LXI. mnoGoSearch Functions
LXII. mSQL functions
LXIII. MySQL
LXIV. Mohawk Software session handler functions
LXV. muscat functions
LXVI. Network Functions
LXVII. Ncurses terminal screen control functions
LXVIII. Lotus Notes functions
LXIX. Unified ODBC functions
LXX. Object Aggregation/Composition Functions
LXXI. Oracle 8 functions
LXXII. OpenSSL functions
LXXIII. Oracle functions
LXXIV. Ovrimos SQL functions
LXXV. Output Control Functions
LXXVI. Sobrecarga de propriedades e métodos de objetos
LXXVII. PDF functions
LXXVIII. Verisign Payflow Pro functions
LXXIX. PHP Options&Information
LXXX. POSIX functions
LXXXI. Funções para PostgreSQL
LXXXII. Process Control Functions
LXXXIII. Program Execution functions
LXXXIV. Printer functions
LXXXV. Pspell Functions
LXXXVI. GNU Readline
LXXXVII. GNU Recode functions
LXXXVIII. Regular Expression Functions (Perl-Compatible)
LXXXIX. qtdom functions
XC. Regular Expression Functions (POSIX Extended)
XCI. Semaphore, Shared Memory and IPC Functions
XCII. SESAM database functions
XCIII. Manejo de sessões
XCIV. Shared Memory Functions
XCV. Shockwave Flash functions
XCVI. SNMP functions
XCVII. Socket functions
XCVIII. Stream functions
XCIX. String functions
C. Funções Sybase
CI. Tokenizer functions
CII. Funções URL
CIII. Variable Functions
CIV. vpopmail functions
CV. W32api functions
CVI. WDDX Functions
CVII. XML parser functions
CVIII. XML-RPC functions
CIX. XSLT functions
CX. YAZ functions
CXI. YP/NIS Functions
CXII. Zip File Functions (Read Only Access)
CXIII. Funções de Compressão Zlib
V. Extending PHP 4.0
24. Overview
25. Extension Possibilities
26. Source Layout
27. PHP's Automatic Build System
28. Creating Extensions
29. Using Extensions
30. Troubleshooting
31. Source Discussion
32. Accepting Arguments
33. Creating Variables
34. Duplicating Variable Contents: The Copy Constructor
35. Returning Values
36. Printing Information
37. Startup and Shutdown Functions
38. Calling User Functions
39. Initialization File Support
40. Where to Go from Here
41. Reference: Some Configuration Macros
42. API Macros
43. Streams API for PHP Extension Authors
Overview
Streams Basics
Streams as Resources
Streams Common API Reference
Streams Dir API Reference
Streams File API Reference
Streams Socket API Reference
Streams Structures
Streams Constants
VI. FAQ: Perguntas Mais Freqüentes
44. General Information
45. Mailing lists
46. Obtaining PHP
47. Database issues
48. Installation
49. Build Problems
50. Using PHP
51. PHP and HTML
52. PHP and COM
53. PHP and other languages
54. Migrating from PHP 2 to PHP 3
55. Migrating from PHP 3 to PHP 4
56. Miscellaneous Questions
VII. Apêndices
A. A História do PHP e projetos relacionados
B. Migrating from PHP 3 to PHP 4
C. Migrating from PHP/FI 2 to PHP 3
D. O debugador do PHP
E. Extending PHP
F. Lista de funções sinônimas (aliases)
G. Palavras reservadas do PHP
H. List of Resource Types
I. List of Supported Protocols/Wrappers
J. List of Parser Tokens
K. Sobre o manual
L. Identificadores faltando (compilação do manual)

Prefácio

PHP, que significa "PHP: Hypertext Preprocessor", é uma linguagem de programação de ampla utilização, interpretada, que é especialmente interessante para desenvolvimento para a Web e pode ser mesclada dentro do código HTML. A sintaxe da linguagem lembra C, Java e Perl, e é fácil de aprender. O objetivo principal da linguagem é permitir a desenvolvedores escrever páginas que serão geradas dinamicamente rapidamente, mas você pode fazer muito mais do que isso com PHP.

Esse manual consiste primariamente de uma referência de funções, mas ele também contém uma referência da linguagem, explicações sobre as mais importantes características do PHP, e outras informações suplementares .

Você pode fazer o download desse manual em vários formatos em http://www.php.net/docs.php. Os arquivos para downloads são atualizados automaticamente assim que o conteúdo for modificado. Para mais informações sobre como esse manual é desenvolvido pode ser encontrado em 'Sobre o manual' do apêndice.

Veja também a história do PHP.

I. Começando


Capítulo 1. Introdução

O que é PHP?

PHP (um acrônimo recursivo para "PHP: Hypertext Preprocessor") é uma linguagem de script Open Source de uso geral, muito utilizada e especialmente guarnecida para o desenvolvimento de aplicações Web embútivel dentro do HTML.

Uma resposta simples, mas o que isso significa?

Exemplo 1-1. Um exemplo introdutório

<html>
    <head>
        <title>Exemplo</title>
    </head>
    <body>

        <?php
        echo "Olá, Eu sou um script PHP!";
        ?>

    </body>
</html>

Note como isso é diferente de scripts CGI escritos em outras linguagens como Perl ou C --- ao invés de escrever um programa com um monte de comandos para imprimir HTML, você escreve um arquivo HTML com algum código inserido para fazer alguma coisa (nesse caso, imprimir um pouco de texto). O código PHP é delimitado por tags iniciais e finais que lhe permitem pular pra dentro e pra fora do "modo PHP".

O que distingui o PHP de algo como Javascript no lado do cliente é que o código é executado no servidor. Se você tivesse um script similar ao acima em seu servidor, o cliente receberia os resultados da execução desse script, sem nenhum modo de determinar como é o código fonte. Você pode inclusive configurar seu servidor para processar todos os seus arquivos HTML como PHP, e então não haverá nenhum modo dos usuários descobrirem que se você usa essa linguagem ou não.

A melhor coisa em usar PHP está no fato de ele ser extremamente simples para um iniciante, mas oferece muitos recursos para o programador profissional. Não se preocupe em ler as longas listas de funções do PHP. Você pode pular essa parte (por enquanto) e começar a escrever scripts em poucas horas.

Apesar do desenvolvimento do PHP ser focado nos scripts do lado do servidor, você pode fazer muito mais com ele. Veja isso e leia mais na seção O que o PHP pode fazer?.


O que o PHP pode fazer?

Qualquer coisa. O PHP é focado para ser uma linguagem de script do lado do servidor, portanto, você pode fazer qualquer coisa que outro programa CGI pode fazer, como: coletar dados de formulários, gerar páginas com conteúdo dinâmico ou enviar e receber cookies. Mas o PHP pode fazer muito mais.

Esses são os maiores campos onde os scripts PHP podem se utilizados:

  • Script no lado do servidor (server-side). Este é o mais tradicional e principal campo de atuação do PHP. Você precisa de três coisas para seu trabalho. O interpretador do PHP (como CGI ou módulo), um servidor web e um browser. Basta rodar o servidor web conectado a um PHP instalado. Você pode acessar os resultados de seu programa PHP com um browser, visualizando a página PHP através do servidor web. Veja as instruções de instalação para maiores informações.

  • Script de linha de comando. Você pode fazer um script PHP funcionar sem um servidor web ou browser. A única coisa necessária é o interpretador. Esse tipo de uso é ideal para script executados usando o cron ou o Agendador de Tarefas (no Windows). Esses scripts podem ser usados também para rotinas de processamento de texto. Veja a seção Utilizando o PHP em linha de comando para maiores informações.

  • Escrevendo aplicações GUI no lado do cliente (client-side). O PHP não é (provavelmente) a melhor linguagem para produção de aplicações com interfaces em janelas, mas o PHP faz isso muito bem, e se você deseja usar alguns recursos avançados do PHP em aplicações no lado do cliente poderá utilizar o PHP-GTK para escrever esses programas. E programas escritos desta forma ainda serão independentes de plataforma. O PHP-GTK é uma extensão do PHP, não disponível na distribuição oficial. Se você está interessado no PHP-GTK, visite seu website

O PHP pode ser utilizado na maioria dos sistemas operacionais, incluindo Linux, várias variantes Unix (incluindo HP-UX, Solaris e OpenBSD), Microsoft Windows, Mac OS X, RISC OS, e provavelmente outros. O PHP também é suportado pela maioria dos servidores web atuais, incluindo Apache, Microsoft Internet Information Server, Personal Web Server, Netscape and iPlanet Servers, Oreilly Website Pro Server, Caudium, Xitami, OmniHTTPd, e muitos outros. O PHP pode ser configurado como módulo para a maioria dos servidores, e para os outros como um CGI comum.

Com o PHP, portanto, você tem a liberdade para escolher o sistema operacional e o servidor web. Do mesmo modo, você pode escolher entre utilizar programação estrutural ou programação orientada a objeto, ou ainda uma mistura deles. Mesmo não desenvolvendo nenhum recurso padrão de OOP (Object Oriented Programming, Programação Orientada a Objetos) na versão atual do PHP, muitas bibliotecas de código e grandes aplicações (incluindo a biblioteca PEAR) foram escritos somente utilizando OOP.

Com PHP você não está limitado a gerar somente HTML. As habilidades do PHP incluem geração de imagens, arquivos PDF e animações Flash (utilizando libswf ou Ming) criados dinamicamente, on the fly. Você pode facilmente criar qualquer padrão texto, como XHTML e outros arquivos XML. O PHP pode gerar esses padrões e os salvar no sistema de arquivos, em vez de imprimi-los, formando um cache dinâmico de suas informações no lado do servidor.

Talvez a mais forte e mais significativa característica do PHP é seu suporte a uma ampla variedade de banco de dados. Escrever uma página que consulte um banco de dados é incrivelmente simples. Os seguintes bancos de dados são atualmente suportados:

Adabas D Ingres Oracle (OCI7 and OCI8)
dBase InterBase Ovrimos
Empress FrontBase PostgreSQL
FilePro (read-only) mSQL Solid
Hyperwave Direct MS-SQL Sybase
IBM DB2 MySQL Velocis
Informix ODBC Unix dbm

Também foi providenciado uma abstração de banco de dados DBX permitindo a você utilizar qualquer banco de dados transparentemente com sua extensão. Adicionalmente, o PHP suporta ODBC (Open Database Connection, ou Padrão Aberto de Conexão com Bancos de Dados), permitindo que você utilize qualquer outro banco de dados que suporte esse padrão mundial.

O PHP também tem suporte para comunicação com outros serviços utilizando protocolos como LDAP, IMAP, SNMP, NNTP, POP3, HTTP, COM (em Windows) e incontáveis outros. Você pode abrir sockets de rede e interagir diretamente com qualquer protocolo. O PHP também suporta o intercâmbio de dados complexos WDDX, utilizado em virtualmente todas as linguagens de programação para web. Falando de comunicação, o PHP implementa a instanciação de objetos Java e os utiliza transparentemente como objetos PHP. Você ainda pode usar sua extensão CORBA para acessar objetos remotos.

O PHP é extremamente útil em recursos de processamento de texto, do POSIX Estendido ou expressões regulares Perl até como interpretador para documentos XML. Para acessar e processar documentos XML, são suportados os padrões SAX e DOM. Você ainda pode usar nossa extensão XSLT para transformar documentos XML.

Utilizando o PHP no campo do e-commerce, você poderá usar as funções específicas para Cybescash, CyberMUT, Verysign Payflow Pro e CCVS, práticos sistemas de pagamento online.

Por último mas longe de terminar, temos também outras extensões interessantes: funções para o search engine mnoGoSearch, funções para Gateway IRC, vários utilitários de compressão (gzip, bz2), calendário e conversões de datas, tradução...

Como você pode ver, esta página não é suficiente para descrever todos os recursos e benefícios que o PHP pode oferecer. Leia nas seções sobre a Instalação do PHP, e veja a referência das funções para detalhes das extensões mencionadas aqui.


Capítulo 2. A simple tutorial

Here we would like to show the very basics of PHP in a short simple tutorial. This text only deals with dynamic webpage creation with PHP, though PHP is not only capable of creating webpages. See the section titled What can PHP do for more information.

PHP-enabled web pages are treated just like regular HTML pages and you can create and edit them the same way you normally create regular HTML pages.


What do I need?

In this tutorial we assume that your server has support for PHP activated and that all files ending in .php are handled by PHP. On most servers this is the default extension for PHP files, but ask your server administrator to be sure. If your server supports PHP then you don't need to do anything. Just create your .php files and put them in your web directory and the server will magically parse them for you. There is no need to compile anything nor do you need to install any extra tools. Think of these PHP-enabled files as simple HTML files with a whole new family of magical tags that let you do all sorts of things.

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 likely want to install a database as well, such as MySQL. You can install these individually or a simpler way is to locate a pre-configured package that automatically installs all of these with just a few mouse clicks. It's easy to setup a web server with PHP support on any operating system, including Linux and Windows. In linux, you may find rpmfind helpful for locating RPMs.


Your first PHP-enabled page

Create a file named hello.php and put it in your web servers root directory (DOCUMENT_ROOT) with the following content:

Exemplo 2-1. Our first PHP script: hello.php

<html>
 <head>
  <title>PHP Test</title>
 </head>
 <body>
 <?php echo "<p>Hello World</p>"; ?>
 </body>
</html>

Use your browser to access the file with your web access URL, ending with the "/hello.php" file reference. When developing locally this url will be something like http://localhost/hello.php or http://127.0.0.1/hello.php but this depends on the web servers configuration. Although this is outside the scope of this tutorial, see also the DocumentRoot and ServerName directives in your web servers configuration file. (on Apache this is httpd.conf). If everything is setup correctly, this file will be parsed by PHP and the following output will make it to your browser:

<html>
 <head>
  <title>PHP Test</title>
 </head>
 <body>
 <p>Hello World</p>
 </body>
</html>

Note that this is not like a CGI script. The file does not need to be executable or special in any way. Think of it as a normal HTML file which happens to have a set of special tags available to you that do a lot of interesting things.

This program is extremely simple and you really didn't need to use PHP to create a page like this. All it does is 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 text, chances are that the server you are on does not have PHP enabled. Ask your administrator to enable it for you using the Installation chapter of the manual. If you're developing locally, also read the installation chapter to make sure everything is configured properly. If problems continue to persist, don't hesitate to use one of the many PHP support options.

The point of the example is to show the special PHP tag format. In this example we used <?php to indicate the start of a PHP tag. Then we put the PHP statement and left PHP mode by adding the closing tag, ?>. You may jump in and out of PHP mode in an HTML file like this all you want. For more details, read the manual section on basic PHP syntax.

A Note on Text Editors: There are many text editors and Integrated Development Environments (IDEs) that you can use to create, edit and manage PHP files. A partial list of these tools is maintained at PHP Editor's List. If you wish to recommend an editor, please visit the above page and ask the page maintainer to add the editor to the list. Having an editor with syntax highlighting can be helpful.

A Note on Word Processors: Word processors such as StarOffice Writer, Microsoft Word and Abiword are not good choices for editing PHP files. If you wish to use one for this test script, you must ensure that you save the file as PLAIN TEXT or PHP will not be able to read and execute the script.

A Note on Windows Notepad: If you are writing your PHP scripts using Windows Notepad, you will need to ensure that your files are saved with the .php extension. (Notepad adds a .txt extension to files automatically unless you take one of the following steps to prevent it.) When you save the file and are prompted to provide a name for the file, place the filename in quotes (i.e. "hello.php"). Alternately, you can click on the 'Text Documents' drop-down menu in the save dialog box and change the setting to "All Files". You can then enter your filename without quotes.

Now that you've successfully created a simple PHP script that works, it's time to create the most famous PHP script! Make a call to the phpinfo() function and you'll see a lot of useful information about your system and setup such as available Predefined Variables, loaded PHP modules, and configuration settings. Take some time and review this important information.


Something Useful

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 agent string that the browser sends as part of its HTTP request. This information is stored in a variable. Variables always start with a dollar-sign in PHP. The variable we are interested in right now is $_SERVER["HTTP_USER_AGENT"].

PHP Autoglobals Note: $_SERVER is a special reserved PHP variable that contains all web server information. It's known as an Autoglobal (or Superglobal). See the related manual page on Autoglobals for more information. These special variables were introduced in PHP 4.1.0. Before this time, we used the older $HTTP_*_VARS arrays instead, such as $HTTP_SERVER_VARS. Although deprecated, these older variables still exist. (See also the note on old code.)

To display this variable, we can simply do:

Exemplo 2-2. Printing a variable (Array element)

<?php echo $_SERVER["HTTP_USER_AGENT"]; ?>

A sample output of this script may be:
Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)

There are many types of variables available in PHP. In the above example we printed an Array element. Arrays can be very useful.

$_SERVER is just one variable that's automatically made available to you by PHP. A list can be seen in the Reserved Variables section of the manual or you can get a complete list of them by creating a file that looks like this:

Exemplo 2-3. Show all predefined variables with phpinfo()

<?php phpinfo(); ?>

If you load up this file in your browser you will see a page full of information about PHP along with a list of all the variables available to you.

You can put multiple PHP statements inside a PHP tag and create little blocks of code that do more than just a single echo. For example, if we wanted to check for Internet Explorer we could do something like this:

Exemplo 2-4. Example using control structures and functions

<?php
if (strstr($_SERVER["HTTP_USER_AGENT"], "MSIE")) {
	echo "You are using Internet Explorer<br />";
}
?>

A sample output of this script may be:
You are using Internet Explorer<br />

Here we introduce a couple of new concepts. We have an if statement. If you are familiar with the basic syntax 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 up any introductory PHP book and read the first couple of chapters, or read the Language Reference part of the manual. You can find a list of PHP books at http://www.php.net/books.php.

The second concept we introduced was the strstr() function call. strstr() is a function built into PHP which searches a string for another string. In this case we are looking for "MSIE" inside $_SERVER["HTTP_USER_AGENT"]. If the string is found, the function returns TRUE and if it isn't, it returns FALSE. If it returns TRUE, the if statement evaluates to TRUE and the code within its {braces} is executed. Otherwise, it's not. Feel free to create similar examples, with if, else, and other functions such as strtoupper() and strlen(). Each related manual page contains examples too.

We can take this a step further and show how you can jump in and out of PHP mode even in the middle of a PHP block:

Exemplo 2-5. Mixing both HTML and PHP modes

<?php
if (strstr($_SERVER["HTTP_USER_AGENT"], "MSIE")) {
?>
<h3>strstr must have returned true</h3>
<center><b>You are using Internet Explorer</b></center>
<?php
} else {
?>
<h3>strstr must have returned false</h3>
<center><b>You are not using Internet Explorer</b></center>
<?php
}
?>

A sample output of this script may be:
<h3>strstr must have returned true</h3>
<center><b>You are using Internet Explorer</b></center>

Instead of using a PHP echo statement to output something, we jumped out of PHP mode and just sent straight HTML. The important and powerful point to note here is that the logical flow of the script remains intact. Only one of the HTML blocks will end up getting sent to the viewer depending on if strstr() returned TRUE or FALSE In other words, if the string MSIE was found or not.


Dealing with Forms

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:

Exemplo 2-6. A simple HTML form

<form action="action.php" method="POST">
 Your name: <input type="text" name="name" />
 Your age: <input type="text" name="age" />
 <input type="submit">
</form>

There is nothing special about this form. It is a straight HTML form with no special tags of any kind. When the user fills in this form and hits the submit button, the action.php page is called. In this file you would have something like this:

Exemplo 2-7. Printing data from our form

Hi <?php echo $_POST["name"]; ?>.
You are <?php echo $_POST["age"]; ?> years old.

A sample output of this script may be:
Hi Joe.
You are 22 years old.

It should be obvious what this does. There is nothing more to it. The $_POST["name"] and $_POST["age"] 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 POST data. Notice how the method of our form is POST. If we used the method GET then our form information would live in the $_GET autoglobal instead. You may also use the $_REQUEST autoglobal if you don't care the source of your request data. It contains a mix of GET, POST, COOKIE and FILE data. See also the import_request_variables() function.


Using old code with new versions of PHP

Now that PHP has grown to be a popular scripting language, there are more resources out there that have listings of code you can reuse in your own scripts. For the most part the developers of the PHP language have tried to be backwards compatible, so a script written for an older version should run (ideally) without changes in a newer version of PHP, in practice some changes will usually be needed.

Two of the most important recent changes that affect old code are:

  • The deprecation of the old $HTTP_*_VARS arrays (which need to be indicated as global when used inside a function or method). The following autoglobal arrays were introduced in PHP 4.1.0. They are: $_GET, $_POST, $_COOKIE, $_SERVER, $_ENV, $_REQUEST, and $_SESSION. The older $HTTP_*_VARS arrays, such as $HTTP_POST_VARS, still exist and have since PHP 3.

  • External variables are no longer registered in the global scope by default. In other words, as of PHP 4.2.0 the PHP directive register_globals is off by default in php.ini. The preferred method of accessing these values is via the autoglobal arrays mentioned above. Older scripts, books, and tutorials may rely on this directive being on. If on, for example, one could use $id from the URL http://www.example.com/foo.php?id=42. Whether on or off, $_GET['id'] is available.

For more details on these changes, see the section on predefined variables and links therein.


What's next?

With what you know now you should be able to understand most of the manual and also the various example scripts available in the example archives. You can also find other examples on the php.net websites in the links section: http://www.php.net/links.php.


Capítulo 3. Instalação


General Installation Considerations

Before installing first, you need to know what do you want to use PHP for. There are three main fields you can use PHP, as described in the What can PHP do? section:

  • Server-side scripting

  • Command line scripting

  • Client-side GUI applications

For the first and most common form, you need three things: PHP itself, a web server and a web browser. You probably already have a web browser, and depending on your operating system setup, you may also have a web server (eg. Apache on Linux or IIS on Windows). You may also rent webspace at a company. This way, you don't need to set up anything on your own, only write your PHP scripts, upload it to the server you rent, and see the results in your browser.

While setting up the server and PHP on your own, you have two choices for the method of connecting PHP to the server. For many servers PHP has a direct module interface (also called SAPI). These servers include Apache, Microsoft Internet Information Server, Netscape and iPlanet servers. Many other servers have support for ISAPI, the Microsoft module interface (OmniHTTPd for example). If PHP has no module support for your web server, you can always use it as a CGI processor. This means you set up your server to use the command line executable of PHP (php.exe on Windows) to process all PHP file requests on the server.

If you are also interested to use PHP for command line scripting (eg. write scripts autogenerating some images for you offline, or processing text files depending on some arguments you pass to them), you always need the command line executable. For more information, read the section about writing command line PHP applications. In this case, you need no server and no browser.

With PHP you can also write client side GUI applications using the PHP-GTK extension. This is a completely different approach than writing web pages, as you do not output any HTML, but manage windows and objects within them. For more information about PHP-GTK, please visit the site dedicated to this extension. PHP-GTK is not included in the official PHP distribution.

From now on, this section deals with setting up PHP for web servers on Unix and Windows with server module interfaces and CGI executables.

Downloading PHP, the source code, and binary distributions for Windows can be found at http://www.php.net/. We recommend you to choose a mirror nearest to you for downloading the distributions.


Unix/HP-UX installs

This section contains notes and hints specific to installing PHP on HP-UX systems.

Exemplo 3-1. Installation Instructions for HP-UX 10

From: paul_mckay@clearwater-it.co.uk
04-Jan-2001 09:49
(These tips are for PHP 4.0.4 and Apache v1.3.9) 

So you want to install PHP and Apache on a HP-UX 10.20 box? 

1. You need gzip, download a binary distribution from
http://hpux.connect.org.uk/ftp/hpux/Gnu/gzip-1.2.4a/gzip-1.2.4a-sd-10.20.depot.Z
uncompress the file and install using swinstall 

2. You need gcc, download a binary distribution from 
http://gatekeep.cs.utah.edu/ftp/hpux/Gnu/gcc-2.95.2/gcc-2.95.2-sd-10.20.depot.gz 
gunzip this file and install gcc using swinstall. 

3. You need the GNU binutils, you can download a binary distribution from 
http://hpux.connect.org.uk/ftp/hpux/Gnu/binutils-2.9.1/binutils-2.9.1-sd-10.20.depot.gz 
gunzip and install using swinstall. 

4. You now need bison, you can download a binary distribution from 
http://hpux.connect.org.uk/ftp/hpux/Gnu/bison-1.28/bison-1.28-sd-10.20.depot.gz 
install as above. 

5. You now need flex, you need to download the source from one of the
http://www.gnu.org mirrors. It is in the <filename>non-gnu</filename> directory of the ftp site. 
Download the file, gunzip, then tar -xvf it. Go into the newly created flex
directory and do a ./configure, then a make, and then a make install 

If you have errors here, it's probably because gcc etc. are not in your
PATH so add them to your PATH. 

Right, now into the hard stuff. 

6. Download the PHP and apache sources. 

7. gunzip and tar -xvf them. 

We need to hack a couple of files so that they can compile ok. 

8. Firstly the configure file needs to be hacked because it seems to lose
track of the fact that you are a hpux machine, there will be a
better way of doing this but a cheap and cheerful hack is to put 
    lt_target=hpux10.20 
on line 47286 of the configure script. 

9. Next, the Apache GuessOS file needs to be hacked. Under
apache_1.3.9/src/helpers change line 89 from 
    "echo "hp${HPUXMACH}-hpux${HPUXVER}"; exit 0" 
to: 
    "echo "hp${HPUXMACH}-hp-hpux${HPUXVER}"; exit 0" 
    
10. You cannot install PHP as a shared object under HP-UX so you must compile
it as a static, just follow the instructions at the Apache page. 

11. PHP and apache should have compiled OK, but Apache won't start. you need
to create a new user for Apache, eg www, or apache. You then change lines 252
and 253 of the conf/httpd.conf in Apache so that instead of 
    User nobody 
    Group nogroup 
you have something like 
    User www 
    Group sys 

This is because you can't run Apache as nobody under hp-ux. 
Apache and PHP should then work. 

Hope this helps somebody,
Paul Mckay.

Unix/Linux installs

This section contains notes and hints specific to installing PHP on Linux distributions.


Using Packages

Many Linux distributions have some sort of package installation system, such as RPM. This can assist in setting up a standard configuration, but if you need to have a different set of features (such as a secure server, or a different database driver), you may need to build PHP and/or your webserver. If you are unfamiliar with building and compiling your own software, it is worth checking to see whether somebody has already built a packaged version of PHP with the features you need.


Unix/Mac OS X installs

This section contains notes and hints specific to installing PHP on Mac OS X Server.


Using Packages

There are a few pre-packaged and pre-compiled versions of PHP for Mac OS X. This can help in setting up a standard configuration, but if you need to have a different set of features (such as a secure server, or a different database driver), you may need to build PHP and/or your web server yourself. If you are unfamiliar with building and compiling your own software, it's worth checking whether somebody has already built a packaged version of PHP with the features you need.


Compiling for OS X server

There are two slightly different versions of Mac OS X, client and server. The following is for OS X Server.

Exemplo 3-2. Mac OS X server install

1. Get the latest distributions of Apache and PHP
2. Untar them, and run the configure program on Apache like so.
    ./configure --exec-prefix=/usr \ 
    --localstatedir=/var \ 
    --mandir=/usr/share/man \ 
    --libexecdir=/System/Library/Apache/Modules \ 
    --iconsdir=/System/Library/Apache/Icons \ 
    --includedir=/System/Library/Frameworks/Apache.framework/Versions/1.3/Headers \ 
    --enable-shared=max \ 
    --enable-module=most \ 
    --target=apache 

4. You may also want to add this line: 
    setenv OPTIM=-O2 
    If you want the compiler to do some optimization. 
    
5. Next, go to the PHP 4 source directory and configure it. 
    ./configure --prefix=/usr \ 
    --sysconfdir=/etc \ 
    --localstatedir=/var \ 
    --mandir=/usr/share/man \ 
    --with-xml \ 
    --with-apache=/src/apache_1.3.12 

    If you have any other additions (MySQL, GD, etc.), be sure to add
    them here. For the --with-apache string, put in the path to your 
    apache source directory, for example "/src/apache_1.3.12". 
6. make
7. make install    
    This will add a directory to your Apache source directory under
    src/modules/php4.
    
8. Now, reconfigure Apache to build in PHP 4.
    ./configure --exec-prefix=/usr \ 
    --localstatedir=/var \ 
    --mandir=/usr/share/man \ 
    --libexecdir=/System/Library/Apache/Modules \ 
    --iconsdir=/System/Library/Apache/Icons \ 
    --includedir=/System/Library/Frameworks/Apache.framework/Versions/1.3/Headers \ 
    --enable-shared=max \ 
    --enable-module=most \ 
    --target=apache \ 
    --activate-module=src/modules/php4/libphp4.a 

    You may get a message telling you that libmodphp4.a is out of date.
    If so, go to the src/modules/php4 directory inside your apache
    source directory and run this command: 

    ranlib libmodphp4.a 

    Then go back to the root of the apache source directory and run the
    above configure command again. That'll bring the link table up to
    date. 

9. make

10. make install

11. copy and rename the php.ini-dist file to your "bin" directory from your
    PHP 4 source directory:
    cp php.ini-dist /usr/local/bin/php.ini 

    or (if your don't have a local directory) 

    cp php.ini-dist /usr/bin/php.ini

Compiling for MacOS X client

Those tips are graciously provided by Marc Liyanage.

The PHP module for the Apache web server included in Mac OS X. This version includes support for the MySQL and PostgreSQL databases.

NOTE: Be careful when you do this, you could screw up your Apache web server!

Do this to install:

  • 1. Open a terminal window

  • 2. Type "wget http://www.diax.ch/users/liyanage/software/macosx/libphp4.so.gz", wait for download to finish

  • 3. Type "gunzip libphp4.so.gz"

  • 4. Type "sudo apxs -i -a -n php4 libphp4.so"

Now type "sudo open -a TextEdit /etc/httpd/httpd.conf" TextEdit will open with the web server configuration file. Locate these two lines towards the end of the file: (Use the Find command)
#AddType application/x-httpd-php .php 
   #AddType application/x-httpd-php-source .phps
Remove the two hash marks (#), then save the file and quit TextEdit.

Finally, type "sudo apachectl graceful" to restart the web server.

PHP should now be up and running. You can test it by dropping a file into your "Sites" folder which is called "test.php". Into that file, write this line: "<?php phpinfo() ?>".

Now open up 127.0.0.1/~your_username/test.php in your web browser. You should see a status table with information about the PHP module.


Unix/OpenBSD installs

This section contains notes and hints specific to installing PHP on OpenBSD 3.2.


Using Binary Packages

Using binary packages to install PHP on OpenBSD is the recommended and simplest method. The core package has been separated from the various modules, and each can be installed and removed independently from the others. The files you need can be found on your OpenBSD CD or on the FTP site.

The main package you need to install is php4-core-4.2.3.tgz, which contains the basic engine (plus gettext and iconv). Next, take a look at the module packages, such as php4-mysql-4.2.3.tgz or php4-imap-4.2.3.tgz. You need to use the phpxs command to activate and deactivate these modules in your php.ini file.

Exemplo 3-3. OpenBSD Package Install Example

# pkg_add php4-core-4.2.3.tgz
# /usr/local/sbin/phpxs -s
# cp /usr/local/share/doc/php4/php.ini-recommended /var/www/conf/php.ini
  (add in mysql)
# pkg_add php4-mysql-4.2.3.tgz
# /usr/local/sbin/phpxs -a mysql
  (add in imap)
# pkg_add php4-imap-4.2.3.tgz
# /usr/local/sbin/phpxs -a imap
  (remove mysql as a test)
# pkg_delete php4-mysql-4.2.3
# /usr/local/sbin/phpxs -r mysql
  (install the PEAR libraries)
# pkg_add php4-pear-4.2.3.tgz

Read the packages(7) manual page for more information about binary packages on OpenBSD.


Using Ports

You can also compile up PHP from source using the ports tree. However, this is only recommended for users familiar with OpenBSD. The PHP4 port is split into three sub-directories: core, extensions and pear. The extensions directory generates sub-packages for all of the supported PHP modules. If you find you do not want to create some of these modules, use the no_* FLAVOR. For example, to skip building the imap module, set the FLAVOR to no_imap.


Older Releases

Older releases of OpenBSD used the FLAVORS system to compile up a statically linked PHP. Since it is hard to generate binary packages using this method, it is now deprecated. You can still use the old stable ports trees if you wish, but they are unsupported by the OpenBSD team. If you have any comments about this, the current maintainer for the port is Anil Madhavapeddy.


Unix/Solaris installs

This section contains notes and hints specific to installing PHP on Solaris systems.


Required software

Solaris installs often lack C compilers and their related tools. The required software is as follows:

  • gcc (recommended, other C compilers may work)

  • make

  • flex

  • bison

  • m4

  • autoconf

  • automake

  • perl

  • gzip

  • tar

  • GNU sed

In addition, you will need to install (and possibly compile) any additional software specific to your configuration, such as Oracle or MySQL.


Using Packages

You can simplify the Solaris install process by using pkgadd to install most of your needed components.


Installation on UNIX systems

This section will guide you through the general configuration and installation of PHP on Unix systems. Be sure to investigate any sections specific to your platform or web server before you begin the process.

Prerequisite knowledge and software:

  • Basic UNIX skills (being able to operate "make" and a C compiler, if compiling)

  • An ANSI C compiler (if compiling)

  • flex (for compiling)

  • bison (for compiling)

  • A web server

  • Any module specific components (such as gd, pdf libs, etc.)

There are several ways to install PHP for the Unix platform, either with a compile and configure process, or through various pre-packaged methods. This documentation is mainly focused around the process of compiling and configuring PHP.

The initial PHP setup and configuration process is controlled by the use of the commandline options of the configure script. This page outlines the usage of the most common options, but there are many others to play with. Check out the Complete list of configure options for an exhaustive rundown. There are several ways to install PHP:


Apache Module Quick Reference

PHP can be compiled in a number of different ways, but one of the most popular is as an Apache module. The following is a quick installation overview.

Exemplo 3-4. Quick Installation Instructions for PHP 4 (Apache Module Version)

1.  gunzip apache_1.3.x.tar.gz
2.  tar xvf apache_1.3.x.tar
3.  gunzip php-x.x.x.tar.gz
4.  tar xvf php-x.x.x.tar
5.  cd apache_1.3.x
6.  ./configure --prefix=/www
7.  cd ../php-x.x.x
8.  ./configure --with-mysql --with-apache=../apache_1.3.x --enable-track-vars
9.  make
10. make install
11. cd ../apache_1.3.x
12. ./configure --activate-module=src/modules/php4/libphp4.a
13. make
14. make install
15. cd ../php-x.x.x
16. cp php.ini-dist /usr/local/lib/php.ini
17. Edit your httpd.conf or srm.conf file and add: 
      AddType application/x-httpd-php .php

18. Use your normal procedure for restarting the Apache server. (You must
    stop and restart the server, not just cause the server to reload by
    use a HUP or USR1 signal.)

Building

When PHP is configured, you are ready to build the CGI executable. The command make should take care of this. If it fails and you can't figure out why, see the Problems section.


Installation on Windows systems

This section applies to Windows 95/98/Me and Windows NT/2000/XP. Do not expect PHP to work on 16 bit platforms such as Windows 3.1. Sometimes we refer to the supported Windows platforms as Win32.

There are two main ways to install PHP for Windows: either manually or by using the InstallShield installer.

If you have Microsoft Visual Studio, you can also build PHP from the original source code.

Once you have PHP installed on your Windows system, you may also want to load various extensions for added functionality.


Windows InstallShield

The Windows PHP installer available from the downloads page at http://www.php.net/downloads.php, this installs the CGI versionof PHP and, for IIS, PWS, and Xitami, configures the web server as well.

Nota: Also note, that while the InstallShield installer is an easy way to make PHP work, it is restricted in many aspects, as automatic setup of extensions for example is not supported. The whole set of supported extensions is only available by downloading the zip binary distribution.

Install your selected HTTP server on your system and make sure that it works.

Run the executable installer and follow the instructions provided by the installation wizard. Two types of installation are supported - standard, which provides sensible defaults for all the settings it can, and advanced, which asks questions as it goes along.

The installation wizard gathers enough information to set up the php.ini file and configure the web server to use PHP. For IIS and also PWS on NT Workstation, a list of all the nodes on the server with script map settings is displayed, and you can choose those nodes to which you wish to add the PHP script mappings.

Once the installation has completed the installer will inform you if you need to restart your system, restart the server, or just start using PHP.

Atenção

Be aware, that this setup of PHP is not secure. If you would like to have a secure PHP setup, you'd better go on the manual way, and set every option carefully. This automatically working setup gives you an instantly working PHP installation, but it is not meant to be used on online servers.


Manual Installation Steps

This install guide will help you manually install and configure PHP on your Windows webserver. You need to download the zip binary distribution from the downloads page at http://www.php.net/downloads.php. The original version of this guide was compiled by Bob Silva, and can be found at http://www.umesd.k12.or.us/php/win32install.html.

This guide provides manual installation support for:

  • Personal Web Server 3 and 4 or newer

  • Internet Information Server 3 and 4 or newer

  • Apache 1.3.x

  • OmniHTTPd 2.0b1 and up

  • Oreilly Website Pro

  • Xitami

  • Netscape Enterprise Server, iPlanet

PHP 4 for Windows comes in two flavours - a CGI executable (php.exe), and several SAPI modules (for example: php4isapi.dll). The latter form is new to PHP 4, and provides significantly improved performance and some new functionality. There is also a CLI version which is further described in the commandline chapter.

Atenção

The SAPI modules have been significantly improved in the 4.1 release, however, you may find that you encounter possible server errors or other server modules such as ASP failing, in older systems.

If you choose one of the SAPI modules and use Windows 95, be sure to download the DCOM update from the Microsoft DCOM pages. For the ISAPI module, an ISAPI 4.0 compliant Web server is required (tested on IIS 4.0, PWS 4.0 and IIS 5.0). IIS 3.0 is NOT supported. You should download and install the Windows NT 4.0 Option Pack with IIS 4.0 if you want native PHP support.

The following steps should be performed on all installations before the server specific instructions.

  • Extract the distribution file to a directory of your choice. c:\php\ is a good start. You probably do not want to use a path in which spaces are included (for example: c:\program files\php is not a good idea). Some web servers will crash if you do.

  • You need to ensure that the DLLs which PHP uses can be found. The precise DLLs involved depend on which web server you use and whether you want to run PHP as a CGI or as a server module. php4ts.dll is always used. If you are using a server module (e.g. ISAPI or Apache) then you will need the relevant DLL from the sapi folder. If you are using any PHP extension DLLs then you will need those as well. To make sure that the DLLs can be found, you can either copy them to the system directory (e.g. winnt/system32 or windows/system) or you can make sure that they live in the same directory as the main PHP executable or DLL your web server will use (e.g. php.exe, php4apache.dll).

    The PHP binary, the SAPI modules, and some extensions rely on external DLLs for execution. Make sure that these DLLs in the distribution exist in a directory that is in the Windows PATH. For example, if you enable php_oci8.dll in php.ini then you'll want to make sure the Oracle home directory can be seen in PATH so PHP can find oci.dll.

    The best bet to do it is to copy the files below into your system directory, which is typically:

    c:\windows\system for Windows 9x/ME
    c:\winnt\system32 for Windows NT/2000
    c:\windows\system32 for Windows XP

    The files to copy are:

    php4ts.dll, if it already exists there, overwrite it
    The files in your distribution's 'dlls' directory. If you have them already installed on your system, overwrite them only if something doesn't work correctly (Before overwriting them, it is a good idea to make a backup of them, or move them to another folder - just in case something goes wrong).

    Download the latest version of the Microsoft Data Access Components (MDAC) for your platform, especially if you use Microsoft Windows 9x/NT4. MDAC is available at http://www.microsoft.com/data/.

  • Copy your chosen ini file (see below) to your '%WINDOWS%' directory on Windows 9x/Me or to your '%SYSTEMROOT%' directory under Windows NT/2000/XP and rename it to php.ini. Your '%WINDOWS%' or '%SYSTEMROOT%' directory is typically:

    c:\windows for Windows 9x/ME/XP
    c:\winnt or c:\winnt40 for NT/2000 servers

    There are two ini files distributed in the zip file, php.ini-dist and php.ini-optimized. We advise you to use php.ini-optimized, because we optimized the default settings in this file for performance, and security. The best is to study all the ini settings and set every element manually yourself. If you would like to achieve the best security, then this is the way for you, although PHP works fine with these default ini files.

  • Edit your new php.ini file:

    • You will need to change the 'extension_dir' setting to point to your php-install-dir, or where you have placed your php_*.dll files. Please do not forget the last backslash. ex: c:\php\extensions\

    • If you are using OmniHTTPd, do not follow the next step. Set the 'doc_root' to point to your webservers document_root. For example: c:\apache\htdocs or c:\webroot

    • Choose which extensions you would like to load when PHP starts. See the section about Windows extensions, about how to set up one, and what is already built in. Note that on a new installation it is advisable to first get PHP working and tested without any extensions before enabling them in php.ini.

    • On PWS and IIS, you can set the browscap.ini to point to: c:\windows\system\inetsrv\browscap.ini on Windows 9x/Me, c:\winnt\system32\inetsrv\browscap.ini on NT/2000, and c:\windows\system32\inetsrv\browscap.ini on XP.

    • Note that the mibs directory supplied with the Windows distribution contains support files for SNMP. This directory should be moved to DRIVE:\usr\mibs (DRIVE being the drive where PHP is installed.)

    • If you're using NTFS on Windows NT, 2000 or XP, make sure that the user running the webserver has read permissions to your php.ini (e.g. make it readable by Everyone).

  • For PWS give execution permission to the webroot:

    • Start PWS Web Manager

    • Edit Properties of the "Home"-Directory

    • Select the "execute"-Checkbox


Building from source

Before getting started, it is worthwhile answering the question: "Why is building on Windows so hard?" Two reasons come to mind:

  1. Windows does not (yet) enjoy a large community of developers who are willing to freely share their source. As a direct result, the necessary investment in infrastructure required to support such development hasn't been made. By and large, what is available has been made possible by the porting of necessary utilities from Unix. Don't be surprised if some of this heritage shows through from time to time.

  2. Pretty much all of the instructions that follow are of the "set and forget" variety. So sit back and try follow the instructions below as faithfully as you can.


Requisitos

To compile and build PHP you need a Microsoft Development Environment. Microsoft Visuaul C++ 6.0 is recommended. To extract the downloaded files you need a extraction utilitiy (e.g.: Winzip). If you don't already have an unzip utility, you can get a free version from InfoZip.

Before you get started, you have to download...

Finally, you are going to need the source to PHP 4 itself. You can get the latest development version using anonymous CVS, a snapshot or the most recent released source tarball.


Putting it all together

After downloading the required packages you have to extract them in a proper place.

  • Create a working directory where all files end up after extracting, e.g: c:\work.

  • Create the directory win32build under your working directory (c:\work) and unzip win32build.zip into it.

  • Create the directory bindlib_w32 under your working directory (c:\work) and unzip bindlib_w32.zip into it.

  • Extract the downloaded PHP source code into your working directory (c:\work).

Following this steps your directory structure looks like this:

+--c:\work
|  |
|  +--bindlib_w32
|  |  |
|  |  +--arpa
|  |  |
|  |  +--conf
|  |  |
|  |  +--...
|  |
|  +--php-4.x.x
|  |  |
|  |  +--build
|  |  |
|  |  +--...
|  |  |
|  |  +--win32
|  |  |
|  |  +--...
|  |
|  +--win32build
|  |  |
|  |  +--bin
|  |  |
|  |  +--include
|  |  |
|  |  +--lib

Create the directories c:\usr\local\lib. Copy bison.simple from c:\work\win32build\bin to c:\usr\local\lib.

Nota: Cygwin users may omit the last step. A properly installed Cygwin environment provides the mandatory files bison.simple and bison.exe.


Configure MVC ++

The next step is to configure MVC ++ to prepare for compiling. Launch Microsoft Visual C++, and from the menu select Tools => Options. In the dialog, select the directories tab. Sequentially change the dropdown to Executables, Includes, and Library files. Your entries should look like this:

  • Executable files: c:\work\win32build\bin, Cygwin users: cygwin\bin

  • Include files: c:\work\win32build\include

  • Library files: c:\work\win32build\lib


Build resolv.lib

You must build the resolv.lib library. Decide whether you want to have debug symbols available (bindlib - Win32 Debug) or not (bindlib - Win32 Release). Build the appropriate configuration:

  • For GUI users, launch VC++, and then select File => Open Workspace, navigate to c:\work\bindlib_w32and select bindlib.dsw. Then select Build=>Set Active Configuration and select the desired configuration. Finally select Build=>Rebuild All.

  • For command line users, make sure that you either have the C++ environment variables registered, or have run vcvars.bat, and then execute one of the following commands:

    • msdev bindlib.dsp /MAKE "bindlib - Win32 Debug"

    • msdev bindlib.dsp /MAKE "bindlib - Win32 Release"

At this point, you should have a usable resolv.lib in either your c:\work\bindlib_w32\Debug or Release subdirectories. Copy this file into your c:\work\win32build\lib directory over the file by the same name found in there.


Compiling

The best way to get started is to build the CGI version.

  • For GUI users, launch VC++, and then select File => Open Workspace and select c:\work\php-4.x.x\win32\php4ts.dsw . Then select Build=>Set Active Configuration and select the desired configuration, either php4ts - Win32 Debug_TS or php4ts - Win32 Release_TS. Finally select Build=>Rebuild All.

  • For command line users, make sure that you either have the C++ environment variables registered, or have run vcvars.bat, and then execute one of the following commands from the c:\work\php-4.x.x\win32 directory:

    • msdev php4ts.dsp /MAKE "php4ts - Win32 Debug_TS"

    • msdev php4ts.dsp /MAKE "php4ts - Win32 Release_TS"

    • At this point, you should have a usable php.exe in either your c:\work\php-4.x.x.\Debug_TS or Release_TS subdirectories.

It is possible to do minor customization to the build process by editing the main/config.win32.h.in file. For example you can change the builtin extensions, the location of php.ini and

Next you may want to build the CLI version which is designed to use PHP from the command line. The steps are the same as for building the CGI version, except you have to select the php4ts_cli - Win32 Debug_TS or php4ts_cli - Win32 Release_TS project file. After a succcessfull compiling run you will find the php.exe in either the directory Release_TS\cli\ or Debug_TS\cli\.

Nota: If you want to use PEAR and the comfortable command line installer, the CLI-SAPI is mandatory. For more information about PEAR and the installer read the documantation at the PEAR website.

In order to build the SAPI module (php4isapi.dll for integrating PHP with Microsoft IIS, set your active configuration to php4isapi-whatever-config and build the desired dll.


Installation of Windows extensions

After installing PHP and a webserver on Windows, you will probably want to install some extensions for added functionality. The following table describes some of the extensions available. You can choose which extensions you would like to load when PHP starts by uncommenting the: 'extension=php_*.dll' lines in php.ini. You can also load a module dynamically in your script using dl().

The DLLs for PHP extensions are prefixed with 'php_' in PHP 4 (and 'php3_' in PHP 3). This prevents confusion between PHP extensions and their supporting libraries.

Nota: In PHP 4.0.6 BCMath, Calendar, COM, FTP, MySQL, ODBC, PCRE, Session, WDDX and XML support is built in. You don't need to load any additional extensions in order to use these functions. See your distributions README.txt or install.txt for a list of built in modules.

Nota: Some of these extensions need extra DLLs to work. Couple of them can be found in the distribution package, in the 'dlls' folder but some, for example Oracle (php_oci8.dll) require DLLs which are not bundled with the distribution package.

Copy the bundled DLLs from 'DLLs' folder to your Windows PATH, safe places are:

c:\windows\system for Windows 9x/Me
c:\winnt\system32 for Windows NT/2000
c:\windows\system32 for Windows XP

If you have them already installed on your system, overwrite them only if something doesn't work correctly (Before overwriting them, it is a good idea to make a backup of them, or move them to another folder - just in case something goes wrong).

Tabela 3-1. PHP Extensions

Extension Description Notes
php_bz2.dll bzip2 compression functions None
php_calendar.dll Calendar conversion functions Built in since PHP 4.0.3
php_cpdf.dll ClibPDF functions None
php_crack.dll Crack functions None
php3_crypt.dll Crypt functions unknown
php_ctype.dll ctype family functions None
php_curl.dll CURL, Client URL library functions Requires: libeay32.dll, ssleay32.dll (bundled)
php_cybercash.dll Cybercash payment functions None
php_db.dll DBM functions Deprecated. Use DBA instead (php_dba.dll)
php_dba.dll DBA: DataBase (dbm-style) Abstraction layer functions None
php_dbase.dll dBase functions None
php3_dbm.dll Berkeley DB2 library unknown
php_domxml.dll DOM XML functions Requires: libxml2.dll (bundled)
php_dotnet.dll .NET functions None
php_exif.dll Read EXIF headers from JPEG None
php_fbsql.dll FrontBase functions None
php_fdf.dll FDF: Forms Data Format functions. Requires: fdftk.dll (bundled)
php_filepro.dll filePro functions Read-only access
php_ftp.dll FTP functions Built-in since PHP 4.0.3
php_gd.dll GD library image functions None
php_gd2.dll GD2 library image functions None
php_gettext.dll Gettext functions Requires: gnu_gettext.dll (bundled)
php_hyperwave.dll HyperWave functions None
php_iconv.dll ICONV characterset conversion Requires: iconv-1.3.dll (bundled)
php_ifx.dll Informix functions Requires: Informix libraries
php_iisfunc.dll IIS management functions None
php_imap.dll IMAP POP3 and NNTP functions PHP 3: php3_imap4r1.dll
php_ingres.dll Ingres II functions Requires: Ingres II libraries
php_interbase.dll InterBase functions Requires: gds32.dll (bundled)
php_java.dll Java extension Requires: jvm.dll (bundled)
php_ldap.dll LDAP functions Requires: libsasl.dll (bundled)
php_mhash.dll Mhash Functions None
php_ming.dll Ming functions for Flash None
php_msql.dll mSQL functions Requires: msql.dll (bundled)
php3_msql1.dll mSQL 1 client unknown
php3_msql2.dll mSQL 2 client unknown
php_mssql.dll MSSQL functions Requires: ntwdblib.dll (bundled)
php3_mysql.dll MySQL functions Built-in in PHP 4
php3_nsmail.dll Netscape mail functions unknown
php3_oci73.dll Oracle functions unknown
php_oci8.dll Oracle 8 functions Requires: Oracle 8 client libraries
php_openssl.dll OpenSSL functions Requires: libeay32.dll (bundled)
php_oracle.dll Oracle functions Requires: Oracle 7 client libraries
php_pdf.dll PDF functions None
php_pgsql.dll PostgreSQL functions None
php_printer.dll Printer functions None
php_xslt.dll XSLT functions Requires: sablot.dll (bundled)
php_snmp.dll SNMP get and walk functions NT only!
php_sybase_ct.dll Sybase functions Requires: Sybase client libraries
php_yaz.dll YAZ functions None
php_zlib.dll ZLib compression functions None


Servers-CGI/Commandline

The default is to build PHP as a CGI program. This creates a commandline interpreter, which can be used for CGI processing, or for non-web-related PHP scripting. If you are running a web server PHP has module support for, you should generally go for that solution for performance reasons. However, the CGI version enables Apache users to run different PHP-enabled pages under different user-ids. Please make sure you read through the Security chapter if you are going to run PHP as a CGI.

As of PHP 4.3.0, some important additions have happened to PHP. A new SAPI named CLI also exists and it has the same name as the CGI binary. What is installed at {PREFIX}/bin/php depends on your configure line and this is described in detail in the manual section named Using PHP from the command line. For further details please read that section of the manual.


Testing

If you have built PHP as a CGI program, you may test your build by typing make test. It is always a good idea to test your build. This way you may catch a problem with PHP on your platform early instead of having to struggle with it later.


Benchmarking

If you have built PHP 3 as a CGI program, you may benchmark your build by typing make bench. Note that if Safe Mode is on by default, the benchmark may not be able to finish if it takes longer then the 30 seconds allowed. This is because the set_time_limit() can not be used in safe mode. Use the max_execution_time configuration setting to control this time for your own scripts. make bench ignores the configuration file.

Nota: make bench is only available for PHP 3.


Using Variables

Some server supplied enviroment variables are not defined in the current CGI/1.1 specification. Only the following variables are defined there; everything else should be treated as 'vendor extensions': AUTH_TYPE, CONTENT_LENGTH, CONTENT_TYPE, GATEWAY_INTERFACE, PATH_INFO, PATH_TRANSLATED, QUERY_STRING, REMOTE_ADDR, REMOTE_HOST, REMOTE_IDENT, REMOTE_USER, REQUEST_METHOD, SCRIPT_NAME, SERVER_NAME, SERVER_PORT, SERVER_PROTOCOL and SERVER_SOFTWARE


Servidores-Apache

Esta seção contém notas e dicas específicas para instalações do PHP em Apache, tanto para versões Unix quanto para Windows.


Detalhes ao instalar o PHP com Apache no Unix

Você pode selecionar argumentos para adicionar ao configure na linha 10 abaixo através da Lista completa de opções do configure . Os números de versões foram omitidos aqui, para assegurar que as instruções não estejam incorretas. Você deverá trocar o 'xxx' aqui com os valores corretos dos seus arquivos.

Exemplo 3-5. Instruções de Instalação (Apache Versão de Módulo Compartilhado) para PHP 4

1.  gunzip apache_xxx.tar.gz
2.  tar -xvf apache_xxx.tar
3.  gunzip php-xxx.tar.gz
4.  tar -xvf php-xxx.tar
5.  cd apache_xxx
6.  ./configure --prefix=/www --enable-module=so
7.  make
8.  make install
9.  cd ../php-xxx
10. ./configure --with-mysql --with-apxs=/www/bin/apxs
11. make
12. make install

  Se você decidir mudar as opções de seu configure depois da instalação
  você precisará somente repetir os últimos tres passos. Você somente precisará
  reiniciar o apache para o novo módulo funcionar. Não será necessário recompilar
  o Apache.

13. cp php.ini-dist /usr/local/lib/php.ini

  Você pode editar o seu arquivo .ini para configurar as opções do PHP.  Se
  você preferir que este arquivo fique em outro lugar, use a opção
  --with-config-file-path=/caminho no passo 10.

14. Edite o seu arquivo httpd.conf ou srm.conf e verifique que estas linas estejam presentes
    e não estejam comentadas:
  
   AddType application/x-httpd-php .php

   LoadModule php4_module        libexec/libphp4.so
 
  Você pode escolher qualquer extensão aqui. .php é simplesmente uma sugestão
  que nós damos. Você também pode incluir .html, e .php3 pode ser adicionado para 
  compatibilidade com versões antigas.
 
  O caminho no lado direito do comando LoadModule deve apontar para para o caminho
  do módulo PHP do seu sistema. O comando acima está correto para os passos
  mostrados acima.

15. Use seu procedimento normal para iniciar o servidor Apache. (Você deve
    parar e reiniciar o servidor, não somente fazer um reinício enviando
    um sinal HUP ou USR1.)

Dependendo da sua instalação do Apache e das variações Unix, existem inúmeras maneiras possíveis de parar e reiniciar o servidor. Abaixo estão algumas linhas típicas usadas para reiniciar e o servidor, para instalações de versões de apache/unix. Você deve trocar /caminho/para/ pelo caminho destas aplicações nos seus sistemas.

1. Inúmeras variações de sistemas Linux:
/etc/rc.d/init.d/httpd restart

2. Usando os scripts apachectl:
/caminho/para/apachectl stop
/caminho/para/apachectl start

3. httpdctl and httpsdctl (Usando OpenSSL), igual ao apachectl:
/caminho/para/httpsdctl stop
/caminho/para/httpsdctl start

4. Usando mod_ssl, ou outro servidor SSL, você pode querer iniciar ou
reiniciar manualmente:
/caminho/para/apachectl stop
/caminho/para/apachectl startssl

As localizações dos binários apachectl e http(s)dctl geralmente variam. Se o seu sistema tem os comandos locate ou whereis ou which, estem podem lhe ajudar a encontrar os programas de controle do servidor.

Exemplos diferentes de compilação do PHP para apache estão a seguir:

./configure --with-apxs --with-pgsql

Isto irá criar uma biblioteca compartilhada libphp4.so que é carregada com o Apache usando uma linha LoadModule no arquivo httpd.conf do Apache. O suporte ao PostgreSQL está embutido dentro da biblioteca compartilhada libphp4.so.

./configure --with-apxs --with-pgsql=shared

Isto irá criar uma biblioteca compartilhada libphp4.so para o Apache, mas isto também criará uma biblioteca compartilhada pgsql.so que é carregada com o PHP tanto ao usar a diretiva de extensão no arquivo php.ini ou então carregando ela explícitamente no script usando a função dl().

./configure --with-apache=/caminho/para/apache_source --with-pgsql

Isto irá criar uma biblioteca libmodphp4.a, o arquivo mod_php4.c e vários arquivos dependentes e copiará eles para o diretório src/modules/php4 na árvore de diretório do código fonte do Apache. Então você compilará o Apache usando a opção --activate-module=src/modules/php4/libphp4.a e o sistema de compilação do Apache irá criar o arquivo libphp4.a e fará um link estático dentro do binário httpd. O suporte ao PostgreSQL estará incluído diretamente neste binário httpd, então o resultado final aqui será um único arquivo binário httpd que incluirá tudo do Apache e tudo do PHP.

./configure --with-apache=/caminho/para/apache_source --with-pgsql=shared

Mesmo que o anterior, exceto em vez de incluir o suporte ao PostgreSQL diretamente no binário httpd você terá uma biblioteca compartilhada pgsql.so que você poderá carregar com o PHP tanto do arquivo php.ini ou diretamente usando a função dl().

Quanto estiver decidindo compilar o PHP com maneiras diferentes, você deverá considerar as vantages e disvantagens de cada método. Complilando como uma biblioteca compartilhada significará que você poderá compilar o apache separadamente, e não terá que recompilar tudo quando quiser adicionar ou mudar o seu PHP. compilando o PHP dentro do apache (método estático) significará que o PHP irá carregar e rodar rapidamente. Para maiores informações, veja a página web do Apache que fala sobre Suporte a Objetos Dinâmicos Compartilhados.

Nota: O arquivo httpd.conf padrão do Apache atualmente já contém uma seção que se parece com isso:

User nobody
Group "#-1"

A menos que você mude isto para "Group nogroup" ou algo assim ("Group daemon" é também muito comum) o PHP não estará apto a abrir arquivos.

Nota: Tenha certeza de especificar a versão instalada do apxs quando usar a opção --with-apxs=/caminho/para/apxs. Você NÂO deverá usar a versão do apxs que está nos fontes do apache e sim a que está atualmente instalada no seu sistema.


Instalando o PHP em Windows com Apache 1.3.x

Existem duas maneiras de configurar o PHP para funcionar com o Apache 1.3.x em Windows. Uma é usando o binário CGI (php.exe), a outra é usando a bliblioteca compartilhada (DLL) como módulo para o Apache (SAPI). Nos dois casos você precisará parar o Servidor Apache, e editar seu arquivo srm.conf ou httpd.conf para configurar o Apache para funcionar com o PHP.

Vale deixar claro aqui que agora o módulo SAPI tornou-se muito mais estável no windows, nós recomendamos o seu uso em vez do binário CGI, por ele ser mais transparente e seguro.

Embora possa ter algumas variações de configurar o PHP com Apache, elas são fáceis suficientemente para ser feitas por um usuário sem experiência. Por favor consulte os Documentos do Apache para maiores diretivas de configuração.

Se você descompactou o pacote do PHP para c:\php\ como descrito na seção Passos de Instalação Manual, você precisará inserir estas linhas no seu arquivo de configuração do Apache para configurar o binário CGI:

  • ScriptAlias /php/ "c:/php/"

  • AddType application/x-httpd-php .php .phtml

  • Action application/x-httpd-php "/php/php.exe"

Note que a segunda linha na lista acima pode ser encontrada em versões atuais do arquivo httpd.conf, mas elas estão comentadas. Lembre-se também de trocar o caminho c:/php/ pelo caminho atual do PHP instalado em seu sistema.

Atenção

Usando a configuração do binário CGI, o seu servidor está aberto a vários tipos possívels de ataque. Por favor leia nossa seção Segurança em CGI para aprender como defender-se de ataques.

Se você preferir usar o PHP como um módulo no Apache, esteja certo de mover o arquivo php4ts.dll para o diretório windows/system (em Windows 9x/Me) ou winnt/system32 (para Windows NT/2000/XP), sobrescrevendo qualquer arquivo antigo. Então você deverá adiciomar as duas linhas a seguir em seu arquivo de configuração do Apache:

  • LoadModule php4_module c:/php/sapi/php4apache.dll

  • AddType application/x-httpd-php .php .phtml

Após mudar o arquivo de configuração, lembre-se de reiniciar o servidor, por exemplo, NET STOP APACHE seguido por NET START APACHE, se você roda o Apache como um Serviço Windows, ou use os atalhos comuns no menu iniciar.

Nota: Você irá descobrir que após usar o windows installer para Apache que você deverá definir a diretriz AddModule para mod_php4.c no arquivo de configuração (httpd.conf). Isto pode ser feito adicionando AddModule mod_php4.c para a lista AddModule, perto do começo do arquivo de configuração. Isto é especialmente importante se a diretriz ClearModuleList estiver definida. Falhas ao configurar isto pode resultar em não definir o PHP como um módulo para Apache.

Existem duas maneiras para você poder usar a função de destaque de códigos fonte, contudo dependerá da maneira de sua instalação para esta função funcionar corretamente. Se você configurou o Apache para usar o PHP como um módulo SAPI, então adicionando a seguinte linha ao seu arquivo de configuração você poderá usar esta função: AddType application/x-httpd-php-source .phps

Se você escolher configurar o Apache para usar o PHP como um binário CGI, você precisará usar a função show_source(). Para fazer isto simplesmente crie um arquivo de script PHP e adicione este código: <?php show_source ("php_original_script.php"); ?>. Troque php_original_script.php pelo nome do arquivo que você quer que seja mostrado o código fonte.

Nota: No Apache em Windows todas as barras invertidas em uma definição de caminho como descrito aqui "c:\diretorio\arquivo.ext", devem ser convertidas para barras normais, como descrito aqui "c:/diretorio/arquivo.ext".


Servers-Apache 2.0

This section contains notes and hints specific to Apache 2.0 installs of PHP, both for Unix and Windows versions.

Atenção

Do not use Apache 2.0 and PHP in a production environment neither on Unix nor on Windows.

You are highly encouraged to take a look at the Apache Documentation to get a basic understanding of the Apache 2.0 Server.


PHP and Apache 2.0 compatibility notes

The following versions of PHP are known to work with the most recent version of Apache 2.0:

These versions of PHP are compatible to Apache 2.0.40 and later.

Nota: Apache 2.0 SAPI-support started with PHP 4.2.0. PHP 4.2.3 its known to work in conjunction with Apache 2.0.39. Don't try to use this version of PHP with any other version of Apache. We do not recommend to use PHP 4.2.3 along with Apache 2.0.39.

All mentioned versions of PHP will work still with Apache 1.3.x.


PHP and Apache 2 on Linux

Download the most recent version of Apache 2.0 and a fitting PHP version from the above mentioned places. This quick guide covers only the basics to get started with Apache 2.0 and PHP. For more information read the Apache Documentation. The version numbers have been omitted here, to ensure the instructions are not incorrect. You will need to replace the 'NN' here with the correct values from your files.

Exemplo 3-6. Installation Instructions (Apache 2 Shared Module Version)

1.  gzip -d httpd-2_0_NN.tar.gz
2.  tar xvf httpd-2_0_NN.tar
3.  gunzip php-NN.tar.gz
4.  tar -xvf php-NN.tar
5.  cd httpd-2_0_NN
6.  ./configure --enable-so
7.  make
8.  make install

    Now you have Apache 2.0.NN available under /usr/local/apache2,
    configured with loadable module support and the standard MPM prefork.
    To test the installation use your normal procedure for starting
    the Apache server, e.g.:
    /usr/local/apache2/bin/apachectl start
    and stop the server to go on with the configuration for PHP:
    /usr/local/apache2/bin/apachectl stop.

9.  cd ../php4-NN
10. ./configure --with-apxs2=/usr/local/apache2/bin/apxs
11. make
12. make install
13. cp php.ini-dist /usr/local/lib/php.ini

    Edit your php.ini file to set PHP options. If
    you prefer this file in another location, use
    --with-config-file-path=/path in step 10.

14. Edit your httpd.conf file and check that these lines are
    present:
  
   LoadModule php4_module modules/libphp4.so
   AddType application/x-httpd-php .php

  You can choose any extension you wish here. .php is simply the one
  we suggest.
 
  The path on the right hand side of the LoadModule statement must point
  to the path of the PHP module on your system. The above statement is
  correct for the steps shown above.

15. Use your normal procedure for starting the Apache server, e.g.:
   /usr/local/apache2/bin/apachectl start

Following the steps above you will have a running Apache 2.0 with support for PHP as SAPI module. Of course there are many more configuration options available for both, Apache and PHP. For more information use ./configure --help in the corresponding source tree. In case you wish to build a multithreaded version of Apache 2.0 you must overwrite the standard MPM-Module prefork either with worker or perchild. To do so append to your configure line in step 6 above either the option --with-mpm=worker or --with-mpm=perchild. Take care about the consequences and understand what you are doing. For more information read the Apache documentation about the MPM-Modules.

Nota: To build a multithreaded version of Apache your system must support threads. This also implies to build PHP with experimental Zend Thread Safety (ZTS). Therefore not all extensions might be available. The recommended setup is to build Apache with the standard prefork MPM-Module.


PHP and Apache 2.0 on Windows

Consider to read the Windows specific notes for Apache 2.0.

Atenção

Apache 2.0 is designed to run on Windows NT 4.0, Windows 2000 or Windows XP. At this time, support for Windows 9x is incomplete. Apache 2.0 is not expected to work on those platforms at this time.

Download the most recent version of Apache 2.0 and a fitting PHP version from the above mentioned places. Follow the Manual Installation Steps and come back to go on with the integration of PHP and Apache.

There are two ways to set up PHP to work with Apache 2.0 on Windows. One is to use the CGI binary the other is to use the Apache module DLL. In either case you need to stop the Apache server, and edit your httpd.conf to configure Apache to work with PHP.

You need to insert these three lines to your Apache httpd.conf configuration file to set up the CGI binary:

Exemplo 3-7. PHP and Apache 2.0 as CGI

ScriptAlias /php/ "c:/php/"
AddType application/x-httpd-php .php
Action application/x-httpd-php "/php/php.exe"

If you would like to use PHP as a module in Apache 2.0, be sure to move php4ts.dll to winnt/system32 (for Windows NT/2000) or windows/system32 (for Windows XP), overwriting any older file. You need to insert these two lines to your Apache httpd.conf configuration file to set up the PHP-Module for Apache 2.0:

Exemplo 3-8. PHP and Apache 2.0 as Module

LoadModule php4_module c:/php/sapi/php4apache2.dll
AddType application/x-httpd-php .php

Nota: Remember to substitute the c:/php/ for your actual path to PHP in the above examples.

Atenção

Don't mix up your installation with dll files from different PHP versions . You have the only choice to use the dll's and extensions that ship with your downloaded PHP version.


Servers-Caudium

PHP 4 can be built as a Pike module for the Caudium webserver. Note that this is not supported with PHP 3. Follow the simple instructions below to install PHP 4 for Caudium.

Exemplo 3-9. Caudium Installation Instructions

1.  Make sure you have Caudium installed prior to attempting to
    install PHP 4. For PHP 4 to work correctly, you will need Pike
    7.0.268 or newer. For the sake of this example we assume that
    Caudium is installed in /opt/caudium/server/.
2.  Change directory to php-x.y.z (where x.y.z is the version number).
3.  ./configure --with-caudium=/opt/caudium/server
4.  make
5.  make install
6.  Restart Caudium if it's currently running.
7.  Log into the graphical configuration interface and go to the
    virtual server where you want to add PHP 4 support.
8.  Click Add Module and locate and then add the PHP 4 Script Support module.
9.  If the documentation says that the 'PHP 4 interpreter isn't
    available', make sure that you restarted the server. If you did
    check /opt/caudium/logs/debug/default.1 for any errors related to
    <filename>PHP4.so</filename>. Also make sure that 
    <filename>caudium/server/lib/[pike-version]/PHP4.so</filename>
    is present.
10. Configure the PHP Script Support module if needed.

You can of course compile your Caudium module with support for the various extensions available in PHP 4. See the complete list of configure options for an exhaustive rundown.

Nota: When compiling PHP 4 with MySQL support you must make sure that the normal MySQL client code is used. Otherwise there might be conflicts if your Pike already has MySQL support. You do this by specifying a MySQL install directory the --with-mysql option.


Servers-fhttpd

To build PHP as an fhttpd module, answer "yes" to "Build as an fhttpd module?" (the --with-fhttpd=DIR option to configure) and specify the fhttpd source base directory. The default directory is /usr/local/src/fhttpd. If you are running fhttpd, building PHP as a module will give better performance, more control and remote execution capability.


Servers-IIS/PWS

This section contains notes and hints specific to IIS (Microsoft Internet Information Server). Installing PHP for PWS/IIS 3, PWS 4 or newer and IIS 4 or newer versions.

Important for CGI users: Read the faq on cgi.force_redirect for important details. This directive needs to be set to 0.


Windows and PWS/IIS 3

The recommended method for configuring these servers is to use the REG file included with the distribution (pws-php4cgi.reg). You may want to edit this file and make sure the extensions and PHP install directories match your configuration. Or you can follow the steps below to do it manually.

Atenção

These steps involve working directly with the Windows registry. One error here can leave your system in an unstable state. We highly recommend that you back up your registry first. The PHP Development team will not be held responsible if you damage your registry.

  • Run Regedit.

  • Navigate to: HKEY_LOCAL_MACHINE /System /CurrentControlSet /Services /W3Svc /Parameters /ScriptMap.

  • On the edit menu select: New->String Value.

  • Type in the extension you wish to use for your php scripts. For example .php

  • Double click on the new string value and enter the path to php.exe in the value data field. ex: c:\php\php.exe.

  • Repeat these steps for each extension you wish to associate with PHP scripts.

The following steps do not affect the web server installation and only apply if you want your php scripts to be executed when they are run from the command line (ex. run c:\myscripts\test.php) or by double clicking on them in a directory viewer window. You may wish to skip these steps as you might prefer the PHP files to load into a text editor when you double click on them.

  • Navigate to: HKEY_CLASSES_ROOT

  • On the edit menu select: New->Key.

  • Name the key to the extension you setup in the previous section. ex: .php

  • Highlight the new key and in the right side pane, double click the "default value" and enter phpfile.

  • Repeat the last step for each extension you set up in the previous section.

  • Now create another New->Key under HKEY_CLASSES_ROOT and name it phpfile.

  • Highlight the new key phpfile and in the right side pane, double click the "default value" and enter PHP Script.

  • Right click on the phpfile key and select New->Key, name it Shell.

  • Right click on the Shell key and select New->Key, name it open.

  • Right click on the open key and select New->Key, name it command.

  • Highlight the new key command and in the right side pane, double click the "default value" and enter the path to php.exe. ex: c:\php\php.exe -q %1. (don't forget the %1).

  • Exit Regedit.

  • If using PWS on Windows, reboot to reload the registry.

PWS and IIS 3 users now have a fully operational system. IIS 3 users can use a nifty tool from Steven Genusa to configure their script maps.


Windows and PWS 4 or newer

When installing PHP on Windows with PWS 4 or newer version, you have two options. One to set up the PHP CGI binary, the other is to use the ISAPI module DLL.

If you choose the CGI binary, do the following:

  • Edit the enclosed pws-php4cgi.reg file (look into the SAPI dir) to reflect the location of your php.exe. Backslashes should be escaped, for example: [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\w3svc\parameters\Script Map] ".php"="c:\\php\\php.exe" Now merge this registery file into your system; you may do this by double-clicking it.

  • In the PWS Manager, right click on a given directory you want to add PHP support to, and select Properties. Check the 'Execute' checkbox, and confirm.

If you choose the ISAPI module, do the following:

  • Edit the enclosed pws-php4isapi.reg file (look into the SAPI dir) to reflect the location of your php4isapi.dll. Backslashes should be escaped, for example: [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\w3svc\parameters\Script Map] ".php"="c:\\php\\sapi\\php4isapi.dll" Now merge this registery file into your system; you may do this by double-clicking it.

  • In the PWS Manager, right click on a given directory you want to add PHP support to, and select Properties. Check the 'Execute' checkbox, and confirm.


Windows NT/2000/XP and IIS 4 or newer

To install PHP on an NT/2000/XP Server running IIS 4 or newer, follow these instructions. You have two options to set up PHP, using the CGI binary (php.exe) or with the ISAPI module.

In either case, you need to start the Microsoft Management Console (may appear as 'Internet Services Manager', either in your Windows NT 4.0 Option Pack branch or the Control Panel=>Administrative Tools under Windows 2000/XP). Then right click on your Web server node (this will most probably appear as 'Default Web Server'), and select 'Properties'.

If you want to use the CGI binary, do the following:

  • Under 'Home Directory', 'Virtual Directory', or 'Directory', click on the 'Configuration' button, and then enter the App Mappings tab.

  • Click Add, and in the Executable box, type: c:\php\php.exe (assuming that you have unziped PHP in c:\php\).

  • In the Extension box, type the file name extension you want associated with PHP scripts. Leave 'Method exclusions' blank, and check the Script engine checkbox. You may also like to check the 'check that file exists' box - for a small performance penalty, IIS (or PWS) will check that the script file exists and sort out authentication before firing up php. This means that you will get sensible 404 style error messages instead of cgi errors complaining that php did not output any data.

    You must start over from the previous step for each extension you want associated with PHP scripts. .php and .phtml are common, although .php3 may be required for legacy applications.

  • Set up the appropriate security. (This is done in Internet Service Manager), and if your NT Server uses NTFS file system, add execute rights for I_USR_ to the directory that contains php.exe.

To use the ISAPI module, do the following:

  • If you don't want to perform HTTP Authentication using PHP, you can (and should) skip this step. Under ISAPI Filters, add a new ISAPI filter. Use PHP as the filter name, and supply a path to the php4isapi.dll.

  • Under 'Home Directory', click on the 'Configuration' button. Add a new entry to the Application Mappings. Use the path to the php4isapi.dll as the Executable, supply .php as the extension, leave Method exclusions blank, and check the Script engine checkbox.

  • Stop IIS completely (NET STOP iisadmin)

  • Start IIS again (NET START w3svc)


Servers-Netscape and iPlanet

This section contains notes and hints specific to Netscape and iPlanet installs of PHP, both for Sun Solaris and Windows versions.

You can find more information about setting up PHP for the Netscape Enterprise Server here: http://benoit.noss.free.fr/php/install-php4.html


Installing PHP with Netscape on Sun Solaris

To build PHP with NES or iPlanet web servers, enter the proper install directory for the --with-nsapi = DIR option. The default directory is usually /opt/netscape/suitespot/. Please also read /php-xxx-version/sapi/nsapi/nsapi-readme.txt.

Exemplo 3-10. Installation Example for Netscape Enterprise on Solaris

Instructions for Sun Solaris 2.6 with Netscape Enterprise Server 3.6
From: bhager@invacare.com

1. Install the following packages from www.sunfreeware.com or another
download site: 

    flex-2_5_4a-sol26-sparc-local 
    gcc-2_95_2-sol26-sparc-local 
    gzip-1.2.4-sol26-sparc-local 
    perl-5_005_03-sol26-sparc-local 
    bison-1_25-sol26-sparc-local 
    make-3_76_1-sol26-sparc-local 
    m4-1_4-sol26-sparc-local 
    autoconf-2.13 
    automake-1.4 
    mysql-3.23.24-beta (if you want mysql support) 
    tar-1.13 (GNU tar) 

2. Make sure your path includes the proper directories
    PATH=.:/usr/local/bin:/usr/sbin:/usr/bin:/usr/ccs/bin 
    export PATH 

3. gunzip php-x.x.x.tar.gz (if you have a .gz dist, otherwise go to 4) 
4. tar xvf php-x.x.x.tar 
5. cd ../php-x.x.x 

6. For the following step, make sure /opt/netscape/suitespot/ is where
   your netscape server is installed. Otherwise, change to correct path:
    /configure --with-mysql=/usr/local/mysql --with-nsapi=/opt/netscape/suitespot/ --enable-track-vars --enable-libgcc 
7. make 
8. make install
After performing the base install and reading the appropriate readme file, you may need to performs some additional configuration steps.

Firstly you may need to add some paths to the LD_LIBRARY_PATH environment for Netscape to find all the shared libs. This can best done in the start script for your Netscape server. Windows users can probably skip this step. The start script is often located in: /path/to/server/https-servername/start

You may also need to edit the configuration files that are located in:/path/to/server/https-servername/config/.

Exemplo 3-11. Configuration Example for Netscape Enterprise

Configuration Instructions for Netscape Enterprise Server
From: bhager@invacare.com

1. Add the following line to mime.types:
    type=magnus-internal/x-httpd-php exts=php

2. Add the following to obj.conf, shlib will vary depending on
    your OS, for unix it will be something like
    /opt/netscape/suitespot/bin/libphp4.so.

    You should place the following lines after mime types init.
    Init fn="load-modules" funcs="php4_init,php4_close,php4_execute,php4_auth_trans" shlib="/php4/nsapiPHP4.dll"
    Init fn=php4_init errorString="Failed to initialize PHP!"

    <object name="default">
    . 
    . 
    . 
    .#NOTE this next line should happen after all 'ObjectType' and before all 'AddLog' lines 
    Service fn="php4_execute" type="magnus-internal/x-httpd-php" 
    . 
    . 
    </Object>


    <Object name="x-httpd-php"> 
    ObjectType fn="force-type" type="magnus-internal/x-httpd-php" 
    Service fn=php4_execute 
    </Object> 


    Authentication configuration 

    PHP authentication cannot be used with any other authentication. ALL AUTHENTICATION IS 
    PASSED TO YOUR PHP SCRIPT. To configure PHP Authentication for the entire server, add 
    the following line: 

    <Object name="default"> 
    AuthTrans fn=php4_auth_trans 
    . 
    . 
    . 
    . 
    </Object> 

    To use PHP Authentication on a single directory, add the following: 

    <Object ppath="d:\path\to\authenticated\dir\*"> 
    AuthTrans fn=php4_auth_trans 
    </Object>

If you are running Netscape Enterprise 4.x, then you should use the following:

Exemplo 3-12. Configuration Example for Netscape Enterprise 4.x

Place these lines after the mime types init, and everything else is similar
to the example configuration above.
From: Graeme Hoose (GraemeHoose@BrightStation.com)

Init fn="load-modules" shlib="/path/to/server4/bin/libphp4.so" funcs="php4_init,php4_close,php4_execute,php4_auth_trans"
Init fn="php4_init" LateInit="yes"

Installing PHP with Netscape on Windows

To Install PHP as CGI (for Netscape Enterprise Server, iPlanet, perhaps Fastrack), do the following:

  • Copy php4ts.dll to your systemroot (the directory where you installed windows)

  • Make a file association from the command line. Type the following two lines:
    assoc .php=PHPScript
    ftype PHPScript=c:\php\php.exe %1 %*

  • In the Netscape Enterprise Administration Server create a dummy shellcgi directory and remove it just after (this step creates 5 important lines in obj.conf and allow the web server to handle shellcgi scripts).

  • In the Netscape Enterprise Administration Server create a new mime type (Category: type, Content-Type: magnus-internal/shellcgi, File Suffix:php).

  • Do it for each web server instance you want php to run

More details about setting up PHP as a CGI executable can be found here: http://benoit.noss.free.fr/php/install-php.html

To Install PHP as NSAPI (for Netscape Enterprise Server, iPlanet, perhaps Fastrack, do the following:

  • Copy php4ts.dll to your systemroot (the directory where you installed windows)

  • Make a file association from the command line. Type the following two lines:
    assoc .php=PHPScript
    ftype PHPScript=c:\php\php.exe %1 %*

  • In the Netscape Enterprise Administration Server create a new mime type (Category: type, Content-Type: magnus-internal/x-httpd-php, File Suffix:php).

  • Stop your web service and edit obj.conf. At the end of the Init section, place these two lines (necessarily after mime type init!):
    Init fn="load-modules" funcs="php4_init,php4_close,php4_execute,php4_auth_trans" shlib="c:/php/sapi/php4nsapi.dll"
    Init fn="php4_init" errorString="Failed to initialise PHP!"

  • In The < Object name="default" > section, place this line necessarily after all 'ObjectType' and before all 'AddLog' lines:
    Service fn="php4_execute" type="magnus-internal/x-httpd-php"

  • At the end of the file, create a new object called x-httpd-php, by inserting these lines:
    <Object name="x-httpd-php">
    ObjectType fn="force-type" type="magnus-internal/x-httpd-php"
    Service fn=php4_execute
    </Object>

  • Restart your web service and apply changes

  • Do it for each web server instance you want PHP to run

More details about setting up PHP as an NSAPI filter can be found here: http://benoit.noss.free.fr/php/install-php4.html


Servers-OmniHTTPd Server

This section contains notes and hints specific to OmniHTTPd.


OmniHTTPd 2.0b1 and up for Windows

You need to complete the following steps to make PHP work with OmniHTTPd. This is a CGI executable setup. SAPI is supported by OmniHTTPd, but some tests have shown that it is not so stable to use PHP as an ISAPI module.

Important for CGI users: Read the faq on cgi.force_redirect for important details. This directive needs to be set to 0.

  • Step 1: Install OmniHTTPd server.

  • Step 2: Right click on the blue OmniHTTPd icon in the system tray and select Properties

  • Step 3: Click on Web Server Global Settings

  • Step 4: On the 'External' tab, enter: virtual = .php | actual = c:\path-to-php-dir\php.exe, and use the Add button.

  • Step 5: On the Mime tab, enter: virtual = wwwserver/stdcgi | actual = .php, and use the Add button.

  • Step 6: Click OK

Repeat steps 2 - 6 for each extension you want to associate with PHP.

Nota: Some OmniHTTPd packages come with built in PHP support. You can choose at setup time to do a custom setup, and uncheck the PHP component. We recommend you to use the latest PHP binaries. Some OmniHTTPd servers come with PHP 4 beta distributions, so you should choose not to set up the built in support, but install your own. If the server is already on your machine, use the Replace button in Step 4 and 5 to set the new, correct information.


Servers-Oreilly Website Pro

This section contains notes and hints specific to Oreilly Website Pro.


Oreilly Website Pro 2.5 and up for Windows

This list describes how to set up the PHP CGI binary or the ISAPI module to work with Oreilly Website Pro on Windows.

  • Edit the Server Properties and select the tab "Mapping".

  • From the List select "Associations" and enter the desired extension (.php) and the path to the CGI exe (ex. c:\php\php.exe) or the ISAPI DLL file (ex. c:\php\sapi\php4isapi.dll).

  • Select "Content Types" add the same extension (.php) and enter the content type. If you choose the CGI executable file, enter 'wwwserver/shellcgi', if you choose the ISAPI module, enter 'wwwserver/isapi' (both without quotes).


Servers-Sambar

This section contains notes and hints specific to the Sambar server for Windows.


Sambar Windows

This list describes how to set up the ISAPI module to work with the Sambar server on Windows.

  • Find the file called mappings.ini (in the config directory) in the Sambar isntall directory.

  • Open mappings.ini and add the following line under [ISAPI]:

    *.php = c:\php\php4isapi.dll

    (This line assumes that PHP was installed in c:\php.)

  • Now restart the Sambar server for the changes to take effect.


Servers-Xitami

This section contains notes and hints specific to Xitami.


Xitami for Windows

This list describes how to set up the PHP CGI binary to work with Xitami on Windows.

Important for CGI users: Read the faq on cgi.force_redirect for important details. This directive needs to be set to 0.

  • Make sure the webserver is running, and point your browser to xitamis admin console (usually http://127.0.0.1/admin), and click on Configuration.

  • Navigate to the Filters, and put the extension which PHP should parse (i.e. .php) into the field File extensions (.xxx).

  • In Filter command or script put the path and name of your php executable i.e. c:\php\php.exe.

  • Press the 'Save' icon.

  • Restart the server to reflect changes.


Servers-Other web servers

PHP can be built to support a large number of web servers. Please see Server-related options for a full list of server-related configure options. The PHP CGI binaries are compatible with almost all webservers supporting the CGI standard.


Problems?

Read the FAQ

Some problems are more common than others. The most common ones are listed in the PHP FAQ, part of this manual.


Other problems

If you are still stuck, someone on the PHP installation mailing list may be able to help you. You should check out the archive first, in case someone already answered someone else who had the same problem as you. The archives are available from the support page on http://www.php.net/. To subscribe to the PHP installation mailing list, send an empty mail to php-install-subscribe@lists.php.net. The mailing list address is php-install@lists.php.net.

If you want to get help on the mailing list, please try to be precise and give the necessary details about your environment (which operating system, what PHP version, what web server, if you are running PHP as CGI or a server module, etc.), and preferably enough code to make others able to reproduce and test your problem.


Bug reports

If you think you have found a bug in PHP, please report it. The PHP developers probably don't know about it, and unless you report it, chances are it won't be fixed. You can report bugs using the bug-tracking system at http://bugs.php.net/. Please do not send bug reports in mailing list or personal letters. The bug system is also suitable to submit feature requests.

Read the How to report a bug document before submitting any bug reports!


Complete list of configure options

Nota: These are only used at compile time. If you want to alter PHP's runtime configuration, please see the chapter on Configuration.

The following is a complete list of options supported by PHP 4 configure scripts (as of 4.1.0), used when compiling in Unix-like environments. Some are available in PHP 3, some in PHP 4, and some in both. This is not noted yet.

There are general configuration options for the configure script, consult the appropriate manual pages for GNU autoconf or use the command configure --help for a full, up-to-date list.


Configure Options in PHP 4

Nota: These options are only used in PHP 4 as of PHP 4.1.0. Some are available in older versions of PHP 4, some even in PHP 3, some only in PHP 4.1.0. If you want to compile an older version, some options will probably not be available.


Database options

--with-dbplus

Include dbplus support.

--with-adabas[=DIR]

Include Adabas D support. DIR is the Adabas base install directory, defaults to /usr/local.

--with-sapdb[=DIR]

Include SAP DB support. DIR is SAP DB base install directory, defaults to /usr/local.

--with-solid[=DIR]

Include Solid support. DIR is the Solid base install directory, defaults to /usr/local/solid.

--with-ibm-db2[=DIR]

Include IBM DB2 support. DIR is the DB2 base install directory, defaults to /home/db2inst1/sqllib.

--with-empress[=DIR]

Include Empress support. DIR is the Empress base install directory, defaults to $EMPRESSPATH. From PHP4, this option only supports Empress Version 8.60 and above.

--with-empress-bcs[=DIR]

Include Empress Local Access support. DIR is the Empress base install directory, defaults to $EMPRESSPATH. From PHP4, this option only supports Empress Version 8.60 and above.

--with-birdstep[=DIR]

Include Birdstep support. DIR is the Birdstep base install directory, defaults to /usr/local/birdstep.

--with-custom-odbc[=DIR]

Include a user defined ODBC support. The DIR is ODBC install base directory, which defaults to /usr/local. Make sure to define CUSTOM_ODBC_LIBS and have some odbc.h in your include dirs. E.g., you should define following for Sybase SQL Anywhere 5.5.00 on QNX, prior to run configure script: CPPFLAGS="-DODBC_QNX -DSQLANY_BUG" LDFLAGS=-lunix CUSTOM_ODBC_LIBS="-ldblib -lodbc".

--with-iodbc[=DIR]

Include iODBC support. DIR is the iODBC base install directory, defaults to /usr/local.

--with-esoob[=DIR]

Include Easysoft OOB support. DIR is the OOB base install directory, defaults to /usr/local/easysoft/oob/client.

--with-unixODBC[=DIR]

Include unixODBC support. DIR is the unixODBC base install directory, defaults to /usr/local.

--with-openlink[=DIR]

Include OpenLink ODBC support. DIR is the OpenLink base install directory, defaults to /usr/local. This is the same as iODBC.

--with-dbmaker[=DIR]

Include DBMaker support. DIR is the DBMaker base install directory, defaults to where the latest version of DBMaker is installed (such as /home/dbmaker/3.6).

--disable-unified-odbc

Disable unified ODBC support. Only applicable if iODBC, Adabas, Solid, Velocis or a custom ODBC interface is enabled. PHP 3 only!


Graphics options

--without-gd

Disable GD support. PHP 3 only!

--with-imagick

The imagick extension has been moved to PECL in PEAR and can be found here. Install instructions for PHP 4 can be found on the PEAR site.

Simply doing --with-imagick is only supported in PHP 3 unless you follow the instructions found on the PEAR site.

--with-ming[=DIR]

Include ming support.


Misc options

--enable-force-cgi-redirect

Enable the security check for internal server redirects. You should use this if you are running the CGI version with Apache.

--enable-discard-path

If this is enabled, the PHP CGI binary can safely be placed outside of the web tree and people will not be able to circumvent .htaccess security.

--with-fastcgi=SRCDIR

Build PHP as FastCGI application.

--enable-debug

Compile with debugging symbols.

--with-layout=TYPE

Sets how installed files will be laid out. Type is one of PHP (default) or GNU.

--with-pear=DIR

Install PEAR in DIR (default PREFIX/lib/php).

--without-pear

Do not install PEAR.

--enable-sigchild

Enable PHP's own SIGCHLD handler.

--disable-rpath

Disable passing additional runtime library search paths.

--enable-libgcc

Enable explicitly linking against libgcc.

--enable-php-streams

Include experimental php streams. Do not use unless you are testing the code!

--with-zlib-dir=<DIR>

Define the location of zlib install directory.

--with-aspell[=DIR]

Include ASPELL support.

--with-ccvs[=DIR]

Include CCVS support.

--with-cybercash[=DIR]

Include CyberCash support. DIR is the CyberCash MCK install directory.

--with-icap[=DIR]

Include ICAP support.

--with-ircg-config

Path to the ircg-config script.

--with-ircg

Include ircg support.

--enable-mailparse

Enable mailparse support.

--with-muscat[=DIR]

Include muscat support.

--with-satellite[=DIR]

Enable CORBA support via Satellite (EXPERIMENTAL) DIR is the base directory for ORBit.

--enable-trans-sid

Enable transparent session id propagation.

--with-system-regex

Use system regex library (deprecated).

--with-vpopmail[=DIR]

Include vpopmail support.

--with-tsrm-pthreads

Use POSIX threads (default).

--enable-shared[=PKGS]

Build shared libraries [default=yes].

--enable-static[=PKGS]

Build static libraries [default=yes].

--enable-fast-install[=PKGS]

Optimize for fast installation [default=yes].

--with-gnu-ld

Assume the C compiler uses GNU ld [default=no].

--disable-libtool-lock

Avoid locking (might break parallel builds).

--with-pic

Try to use only PIC/non-PIC objects [default=use both].

--enable-memory-limit

Compile with memory limit support.

--disable-url-fopen-wrapper

Disable the URL-aware fopen wrapper that allows accessing files via HTTP or FTP.

--enable-versioning

Export only required symbols. See INSTALL for more information.

--with-imsp[=DIR]

Include IMSp support (DIR is IMSP's include dir and libimsp.a dir). PHP 3 only!

--with-mck[=DIR]

Include Cybercash MCK support. DIR is the cybercash mck build directory, defaults to /usr/src/mck-3.2.0.3-linux for help look in extra/cyberlib. PHP 3 only!

--with-mod-dav=DIR

Include DAV support through Apache's mod_dav, DIR is mod_dav's installation directory (Apache module version only!) PHP 3 only!

--enable-debugger

Compile with remote debugging functions. PHP 3 only!

--enable-versioning

Take advantage of versioning and scoping provided by Solaris 2.x and Linux. PHP 3 only!


PHP options

--enable-maintainer-mode

Enable make rules and dependencies not useful (and sometimes confusing) to the casual installer.

--with-config-file-path=PATH

Sets the path in which to look for php.ini, defaults to PREFIX/lib.

--enable-safe-mode

Enable safe mode by default.

--with-exec-dir[=DIR]

Only allow executables in DIR when in safe mode defaults to /usr/local/php/bin.

--enable-magic-quotes

Enable magic quotes by default.

--disable-short-tags

Disable the short-form <? start tag by default.


Server options

--with-aolserver=DIR

Specify path to the installed AOLserver.

--with-apxs[=FILE]

Build shared Apache module. FILE is the optional pathname to the Apache apxs tool; defaults to apxs. Make sure you specify the version of apxs that is actually installed on your system and NOT the one that is in the apache source tarball.

--with-apache[=DIR]

Build Apache module. DIR is the top-level Apache build directory, defaults to /usr/local/apache.

--with-mod_charset

Enable transfer tables for mod_charset (Rus Apache).

--with-apxs2[=FILE]

Build shared Apache 2.0 module. FILE is the optional pathname to the Apache apxs tool; defaults to apxs.

--with-fhttpd[=DIR]

Build fhttpd module. DIR is the fhttpd sources directory, defaults to /usr/local/src/fhttpd.

--with-isapi=DIR

Build PHP as an ISAPI module for use with Zeus.

--with-nsapi=DIR

Specify path to the installed Netscape Server.

--with-phttpd=DIR

No information yet.

--with-pi3web=DIR

Build PHP as a module for use with Pi3Web.

--with-roxen=DIR

Build PHP as a Pike module. DIR is the base Roxen directory, normally /usr/local/roxen/server.

--enable-roxen-zts

Build the Roxen module using Zend Thread Safety.

--with-servlet[=DIR]

Include servlet support. DIR is the base install directory for the JSDK. This SAPI prereqs the java extension must be built as a shared dl.

--with-thttpd=SRCDIR

Build PHP as thttpd module.

--with-tux=MODULEDIR

Build PHP as a TUX module (Linux only).


Capítulo 4. Configuração

O arquivo de configuração

O arquivo de configuração (chamado php3.ini no PHP 3.0, e simplesmente php.ini no PHP 4.0) é lido quando o PHP inicia. Para as versões de módulos de servidor do PHP, isso só acontece uma vez quando o servidor é iniciado. Para as versões CGI e CLI acontece em cada execução.

A localização padrão do php.ini é uma opção de compilação (veja a FAQ correspondente), mas pode ser modificada para as versões CGI e CLI com o opcional -c (mais informações em utilizando o PHP na linha de comando). Você também pode utilizar a variavável ambiente PHPRC para colocar caminhos adicionais para a procura do arquivo php.ini.

Note que nem todas as diretivas do PHP estão documentadas a seguir. Para uma lista completa, leia o seu próprio e bem comentado arquivo php.ini. Você também pode ver a versão mais atualizada diretamente do CVS.

Nota: O valor default da diretiva register_globals mudou de on para off a partir do PHP 4.2.0.

Exemplo 4-1. php.ini example

; qualquer texto depois de um ponto e vírgula não delimitado (;) é ignorado
[php] ; marcadores de seção (texto entre colchetes) também são ignorados
; Valores booleanos podem ser:
;    true, on, yes
; ou false, off, no, none
register_globals = off
magic_quotes_gpc = yes

; você pode delimitar strings com aspas
include_path = ".:/usr/local/lib/php"

; barras invertidas são tratadas da mesma maneira que outros caracteres
include_path = ".;c:\php\lib"


Como alterar as configurações definidas

Rodando o PHP como módulo do Apache

Quando usando o PHP como um módulo do Apache, você também pode mudar as definições de configuração usando diretivas na configuração do Apache (httpd.conf) e dos arquivos .htaccess (Você irá precisar de privilégios "AllowOverride Options" ou "AllowOverride All")

Com o PHP 3.0, existem diretivas Apache que correspondem a cada definição de configuração no nome php3.ini, exceto o nome predefinido por "php3_".

Com o PHP 4.0, existem várias diretivas do Apache que lhe permitem mudar a configuração PHP dentro do arquivo de configuração do Apache.

php_value nome valor

Isso define o valor da variável especificada.

php_flag nome on|off

Isto é usado para definir uma opção de configuração Booleana.

php_admin_value nome valor

Isto define o valor da variável especificada. Definições de configuração "Admin" só podem ser definidas a partir dos arquivos principais de configuração do Apache, e não dos arquivos .htaccess.

php_admin_flag nome on|off

Isto é usado para definir uma opção de configuração Booleana.

Exemplo 4-2. Exemplo de configuração do Apache

<IfModule mod_php4.c>
  php_value include_path ".:/usr/local/lib/php"
  php_admin_flag safe_mode on
</IfModule>
<IfModule mod_php3.c>
  php3_include_path ".:/usr/local/lib/php"
  php3_safe_mode on
</IfModule>

Nota: Constantes PHP não existem fora do PHP. Por exemplo, no httpd.conf não adianta utilizar-se de constantes PHP como E_ALL ou E_NOTICE para configurar a diretiva error_reporting, pois elas não tem nenhum sentido e serão avaliados como 0. Nesses casos, utilize seus valores de bit. Essas constantes só podem ser utilizadas dentro do php.ini


Outras interfaces para o PHP

Independentemente da interface do PHP, você pode mudar certos valores em tempo de execução em seus scripts através ini_set(). A tabela seguinte explica em que nível as diretivas podem ser modificadas.

Tabela 4-1. Definições das constantes PHP_INI_*

Constante Valor Significado
PHP_INI_USER 1 Diretiva pode ser modificada em seus scripts
PHP_INI_PERDIR 2 Diretiva pode ser modificada no .htaccess e nas diretivas VHost do httpd.conf.
PHP_INI_SYSTEM 4 Diretiva pode ser modificada no php.ini ou httpd.conf (mas não em blocos VHost do httpd.conf).
PHP_INI_ALL 7 Diretiva pode ser modificada em qualquer lugar

Você pode visualizar as configurações das diretivas na saída de phpinfo(). Você também pode acessar os valores individuais das configurações utilizando ini_get() ou get_cfg_var().


Diretivas de configuração

Opções Httpd

Tabela 4-2. Opções Httpd

Nome Padrão Alterável
async_send "0" PHP_INI_ALL


Opções da Linguagem

Tabela 4-3. Opções gerais da linguagem

Nome Padrão Alterável
short_open_tag On PHP_INI_SYSTEM|PHP_INI_PERDIR
asp_tags Off PHP_INI_SYSTEM|PHP_INI_PERDIR
precision "14" PHP_INI_ALL
y2k_compliance Off PHP_INI_ALL
allow_call_time_pass_reference On PHP_INI_SYSTEM|PHP_INI_PERDIR
expose_php On PHP_INI_SYSTEM

Descrição resumida das diretivas de configuração.

short_open_tag boolean

Informa quando a tag reduzida (<? ?>) do PHP pode ser permitida. Se você quiser usar o PHP em combinação com XML, você pode desligar essa opção para poder utilizar <?xml ?> inline. De outra forma, você pode imprimir com o PHP, por exemplo: <?php echo '<?xml version="1.0"'; ?>. Se desligado, você precisará utilizar a forma longa da tag de abertura do PHP (<?php ?>).

Nota: Esta diretiva também afeta o atalho <?=, que é idêntico a <? echo. A utilização desse atalho requer short_open_tag ligado.

asp_tags boolean

Ativa a utilização das tags estilo ASP <% %> em adição as tags <?php ?>. Isto inclui o atalho de impressão de valores <%= $var %>. Para mais informações, veja Alternando do HTML.

Nota: O suporte a tags estilo APS foi acrescentado no 3.0.4.

precision integer

O número de dígitos significantes exibidos em números de ponto flutuante.

y2k_compliance boolean

Força a especificação Ano 2002 (poderá causar problemas com browsers não compatíveis)

allow_call_time_pass_reference boolean

Especifica a habilidade em forçar que argumentos possam ser passados por referência na chamada de uma função. Este método é obsoleto e logo não será mais suportado nas futuras versões do PHP/Zend. O método recomendado para especificar que argumentos devem ser passados por referência é pela declaração da função. Você é encorajado em tentar desligar essa opção e verificar se seus scripts trabalham adequadamente de forma a garantir que elas irã funcionar nas futuras versões da linguagem (você receberá um alerta cada vez que utilizar esse recurso, e o argumento será passado por valor em vez de por referência).

Veja também Referências Explicadas.

expose_php boolean

Decide se o PHP poderá expor o fato de que ele está instalado no servidor (acrescentando sua assinatura no header do servidor web). Isto não causa problemas de segurança de qualquer forma, mas torna possível determinar se você usa o PHP em seu servidor ou não.


Limitação de recursos

Tabela 4-4. Limitação de recursos

Nome Padrão Alterável
memory_limit "8M" PHP_INI_ALL

Descrição resumida das diretivas de configuração.

memory_limit integer

Isto configura a quantidade máxima de memória, em bytes, que um script poderá alocar. Isto ajuda a prevenir que scripts mal escritos acabem com toda a memória disponível do servidor.

Veja também max_execution_time.


Manipulação de dados

Tabela 4-5. Opções configuráveis para manipulação de dados

Nome Padrão Alterável
track-vars "On" PHP_INI_??
arg_separator.output "&" PHP_INI_ALL
arg_separator.input "&" PHP_INI_SYSTEM|PHP_INI_PERDIR
variables_order "EGPCS" PHP_INI_ALL
register_globals "Off" PHP_INI_PERDIR|PHP_INI_SYSTEM
register_argc_argv "On" PHP_INI_PERDIR|PHP_INI_SYSTEM
post_max_size "8M" PHP_INI_SYSTEM|PHP_INI_PERDIR
gpc_order "GPC" PHP_INI_ALL
auto_prepend_file "" PHP_INI_SYSTEM|PHP_INI_PERDIR
auto_append_file "" PHP_INI_SYSTEM|PHP_INI_PERDIR
default_mimetype "text/html" PHP_INI_ALL
default_charset "iso-8859-1" PHP_INI_ALL
always_populate_raw_post_data "0" PHP_INI_SYSTEM|PHP_INI_PERDIR
allow_webdav_methods "0" PHP_INI_SYSTEM|PHP_INI_PERDIR

Descrição resumida das diretivas de configuração.

track_vars boolean

Se ativado, quaisquer variáveis Environment, GET, POST, Cookie e Server encontradas poderão ser acessadas nos arrays globais associativos $_ENV, $_GET, $_POST, $_COOKIE e $_SERVER.

Note que a partir do PHP 4.0.3, track_vars está sempre ativado.

arg_separator.output string

O separador de parâmetros em URLs geradas pelo PHP.

arg_separator.input string

Lista dos separador(es) utilizados pelo PHP para interpretar URLs em variáveis.

Nota: Cada caracter nesta diretiva é considerado como um separador!

variables_order string

Configura a ordem de interpretação das variáveis EGPCS (Environment, GET, POST, Cookie e Server). O default dessa diretiva é "EGPCS". Configurando para "GP", por exemplo, fará com que o PHP ignore completamente variáveis de ambiente (E), cookies (C) e do servidor (S), sendo que qualquer variável GET será sobrescrita por qualquer variável do método POST com o mesmo nome.

Veja também register_globals.

register_globals boolean

Ativa ou não o registro de variáveis EGPCS (Environment, GET, POST, Cookie e Server) como variáveis globais. Por exemplo: se register_globals = on, a URL http://www.example.com/test.php?id=3 irá criar a variável $id. Ou, $DOCUMENT_ROOT de $_SERVER['DOCUMENT_ROOT']. Você pode desligar essa diretiva se você não deseja sujar o escopo global de seus scripts com dados do usuário. Desde o PHP 4.2.0, o padrão dessa diretiva é off. É preferível utilizar as variáveis predefinidas do PHP, como as superglobals: $_ENV, $_GET, $_POST, $_COOKIE e $_SERVER. Leia cuidadosamente o capitulo de segurança em Utilizando register_globals para mais informações.

Veja que register_globals não pode ser alterado em tempo de execução (ini_set()). Entretanto, você pode utilizar o .htaccess se seu host permitir como descrito anteriormente. Um exemplo de entrada do .htaccess: php_flag register_globals on.

Nota: register_globals é afetada pela diretiva variables_order .

register_argc_argv boolean

Configura quando o PHP deve declarar ou não as variáveis argv e argc (que podem conter dados do método GET).

Veja também Utilizando o PHP em linha de comando. Além, essa diretiva foi criada no PHP 4.0.0 e sempre foi "ativa" antes disso.

post_max_size integer

Configura o tamanho máximo dos dados postados. Esta configuração também afeta o upload de arquivos. Para receber arquivos grandes, esse valor precisa ser maior que upload_max_filesize.

Se o limite de memória estiver ativado em seu script de configuração, memory_limit também afeta o upload de arquivos. Falando diretamente, memory_limit precisa ser maior que post_max_size.

gpc_order string

Informa a ordem de interpretação das variáveis GET/POST/COOKIE. O padrão dessa diretiva é "GPC". Configurando para "GP", por exemplo, fará com que o PHP ignore completamente cookies e que sobrescreva qualquer dado postado via GET por variáveis postados via POST que tenham o mesmo nome.

Nota: Esta opção não está disponível no PHP 4. Utilize variables_order no seu lugar.

auto_prepend_file string

Especifica o nome do arquivo que será automaticamente interpretado antes do arquivo principal. O arquivo é incluído como se ele fosse chamado com a função include(), então include_path é utilizado.

O valor especial none desabilita a auto inclusão.

auto_append_file string

Especifica se o nome do arquivo que será automaticamente interpretado depois do arquivo principal. O arquivo é incluído como se ele fosse chamada a função include(), então include_path é utilizado.

O valor especial none desabilita a auto inclusão.

Nota: Se o script é terminado com exit(), a auto inclusão não irá ocorrer.

default_mimetype string

default_charset string

A partir da versão 4.0b4, o PHP sempre emite a codificação de caracter por padrão no header Content-type:. Para desabilitar o envio do código de página, simplesmente deixe a diretiva em branco.

always_populate_raw_post_data boolean

Sempre preenche a variável $HTTP_RAW_POST_DATA.

allow_webdav_methods boolean

Permite a manipulação de headers HTTP com scripts PHP (com PROPFIND, PROPPATCH, MOVE, COPY, etc). Se você quiser obter os dados postados dessas requisições, ative always_populate_raw_post_data para isso.

Veja também magic_quotes_gpc, magic-quotes-runtime, e magic_quotes_sybase.


Paths and Directories

Tabela 4-6. Opções de configuração de caminhos e diretórios

Nome Padrão Alterável
include_path PHP_INCLUDE_PATH PHP_INI_ALL
doc_root PHP_INCLUDE_PATH PHP_INI_SYSTEM
user_dir NULL PHP_INI_SYSTEM
extension_dir PHP_EXTENSION_DIR PHP_INI_SYSTEM
cgi.force_redirect "1" PHP_INI_SYSTEM
cgi.redirect_status_env "" PHP_INI_SYSTEM
fastcgi.impersonate "0" PHP_INI_SYSTEM

Descrição resumida das diretivas de configuração.

include_path string

Especifica a lista de diretórios onde as funções require(), include() and fopen_with_path() procurarão por arquivos. O formato é o mesmo que o da variável ambiente PATH: uma lista de diretórios, separador por vírgula no UNIX ou ponto e vírgula no Windows.

Exemplo 4-3. include_path UNIX

include_path=.:/home/httpd/php-lib

Exemplo 4-4. include_path Windows

include_path=".;c:\www\phplib"
O default dessa diretiva é . (somente o diretório atual).

doc_root string

O "diretório root" do PHP no servidor. Utilizado somente se for preenchido. Se o PHP estiver configurado com safe mode, nenhum arquivo acima desse diretório será acessível. Se o PHP não estiver compilado com FORCE_REDIRECT, você DEVE configurar doc_root se estiver rodando o PHP como CGI sob qualquer servidor web (que não o IIS) Outra alternativa é configurar a diretiva cgi.force_redirect, abaixo.

user_dir string

O caminho base do usado como diretório home do usuário para arquivos PHP, por exemplo public_html.

extension_dir string

Diretório de onde o PHP poderá carregar dinamicamente as extensões. Veja também enable_dl e dl().

extension string

Que extensões dinamicamente carregáveis devem ser carregadas quando o PHP inicia.

cgi.force_redirect boolean

cgi.force_redirect é necessário para prover segurança quando rodando o PHP como módulo sob a maioria dos servidores web. Se deixado indefinido, o PHP assume como ativo. Você pode desligá-lo SOB SEU RISCO.

Nota: Usuários Windows: Você PODE desligar isso no ISS, e de fato, você DEVE fazê-lo. Para que o OmniHTTPD ou Xitami funcionem, você PRECISA desligá-lo.

cgi.cgi.redirect_status_env string

Se cgi.force_redirect estiver ativado, e se não estiver rodando o PHP sob os servidores web Apache ou Netscape (iPlanet), você PRECISARÁ configurar uma variável de ambiente que o PHP procurará para saber se ele pode continuar a execução.

Nota: Configurar essa variável PODERÁ causar problemas de segurança, POR ISSO SAIBA QUE ESTEJA FAZENDO PRIMEIRO.

fastcgi.impersonate string

FastCGI sob o IIS (em sistemas baseados em WinNT) suporta a habilidade de despersonalizar tokens de segurança da chamado do cliente. Isto permite ao ISS definir o contexto de segurança da requisição que está rodando. mod_fastcgi sob o Apache ainda não suporta esse recurso (17/03/2002). Configure 1 se estiver rodando sob o ISS. O padrão é zero.


Upload de arquivos

Tabela 4-7. Opções de configuração para upload de arquivos

Nome Padrão Alterável
file_uploads "1" PHP_INI_SYSTEM
upload_tmp_dir NULL PHP_INI_SYSTEM
upload_max_filesize "2M" PHP_INI_SYSTEM|PHP_INI_PERDIR

Descrição resumida das diretivas de configuração.

file_uploads boolean

Permite ou não upload de arquivos HTTP. Veja também upload_max_filesize, upload_tmp_dir e post_max_size directives.

upload_tmp_dir string

O diretório temporário utilizado para armazenar arquivos quando realizando o upload de arquivos. Ele precisa ter permissão de escrita para qualquer usuário que for rodar o PHP. Se não especificado, o PHP utilizará o default do sistema.

upload_max_filesize integer

O tamanho máximo de um arquivo para upload.


SQL Geral

Tabela 4-8. Opções de configuração SQL gerais

Nome Padrão Alterável
sql.safe_mode "0" PHP_INI_SYSTEM

Descrição resumida das diretivas de configuração.

sql.safe_mode boolean


Diretivas de configuração do debugador

debugger.host string

Nome DNS ou endereço IP do host utilizado pelo debugador.

debugger.port string

Porta utilizado pelo debugador.

debugger.enabled boolean

Controle de ativação do debugador.


Capítulo 5. Security

PHP is a powerful language and the interpreter, whether included in a web server as a module or executed as a separate CGI binary, is able to access files, execute commands and open network connections on the server. These properties make anything run on a web server insecure by default. PHP is designed specifically to be a more secure language for writing CGI programs than Perl or C, and with correct selection of compile-time and runtime configuration options, and proper coding practices, it can give you exactly the combination of freedom and security you need.

As there are many different ways of utilizing PHP, there are many configuration options controlling its behaviour. A large selection of options guarantees you can use PHP for a lot of purposes, but it also means there are combinations of these options and server configurations that result in an insecure setup.

The configuration flexibility of PHP is equally rivalled by the code flexibility. PHP can be used to build complete server applications, with all the power of a shell user, or it can be used for simple server-side includes with little risk in a tightly controlled environment. How you build that environment, and how secure it is, is largely up to the PHP developer.

This chapter starts with some general security advice, explains the different configuration option combinations and the situations they can be safely used, and describes different considerations in coding for different levels of security.


General considerations

A completely secure system is a virtual impossibility, so an approach often used in the security profession is one of balancing risk and usability. If every variable submitted by a user required two forms of biometric validation (such as a retinal scan and a fingerprint), you would have an extremely high level of accountability. It would also take half an hour to fill out a fairly complex form, which would tend to encourage users to find ways of bypassing the security.

The best security is often inobtrusive enough to suit the requirements without the user being prevented from accomplishing their work, or over-burdening the code author with excessive complexity. Indeed, some security attacks are merely exploits of this kind of overly built security, which tends to erode over time.

A phrase worth remembering: A system is only as good as the weakest link in a chain. If all transactions are heavily logged based on time, location, transaction type, etc. but the user is only verified based on a single cookie, the validity of tying the users to the transaction log is severely weakened.

When testing, keep in mind that you will not be able to test all possibilities for even the simplest of pages. The input you may expect will be completely unrelated to the input given by a disgruntled employee, a cracker with months of time on their hands, or a housecat walking across the keyboard. This is why it's best to look at the code from a logical perspective, to discern where unexpected data can be introduced, and then follow how it is modified, reduced, or amplified.

The Internet is filled with people trying to make a name for themselves by breaking your code, crashing your site, posting inappropriate content, and otherwise making your day interesting. It doesn't matter if you have a small or large site, you are a target by simply being online, by having a server that can be connected to. Many cracking programs do not discern by size, they simply trawl massive IP blocks looking for victims. Try not to become one.


Installed as CGI binary

Possible attacks

Using PHP as a CGI binary is an option for setups that for some reason do not wish to integrate PHP as a module into server software (like Apache), or will use PHP with different kinds of CGI wrappers to create safe chroot and setuid environments for scripts. This setup usually involves installing executable PHP binary to the web server cgi-bin directory. CERT advisory CA-96.11 recommends against placing any interpreters into cgi-bin. Even if the PHP binary can be used as a standalone interpreter, PHP is designed to prevent the attacks this setup makes possible:

  • Accessing system files: http://my.host/cgi-bin/php?/etc/passwd

    The query information in a url after the question mark (?) is passed as command line arguments to the interpreter by the CGI interface. Usually interpreters open and execute the file specified as the first argument on the command line.

    When invoked as a CGI binary, PHP refuses to interpret the command line arguments.

  • Accessing any web document on server: http://my.host/cgi-bin/php/secret/doc.html

    The path information part of the url after the PHP binary name, /secret/doc.html is conventionally used to specify the name of the file to be opened and interpreted by the CGI program. Usually some web server configuration directives (Apache: Action) are used to redirect requests to documents like http://my.host/secret/script.php to the PHP interpreter. With this setup, the web server first checks the access permissions to the directory /secret, and after that creates the redirected request http://my.host/cgi-bin/php/secret/script.php. Unfortunately, if the request is originally given in this form, no access checks are made by web server for file /secret/script.php, but only for the /cgi-bin/php file. This way any user able to access /cgi-bin/php is able to access any protected document on the web server.

    In PHP, compile-time configuration option --enable-force-cgi-redirect and runtime configuration directives doc_root and user_dir can be used to prevent this attack, if the server document tree has any directories with access restrictions. See below for full the explanation of the different combinations.


Case 1: only public files served

If your server does not have any content that is not restricted by password or ip based access control, there is no need for these configuration options. If your web server does not allow you to do redirects, or the server does not have a way to communicate to the PHP binary that the request is a safely redirected request, you can specify the option --enable-force-cgi-redirect to the configure script. You still have to make sure your PHP scripts do not rely on one or another way of calling the script, neither by directly http://my.host/cgi-bin/php/dir/script.php nor by redirection http://my.host/dir/script.php.

Redirection can be configured in Apache by using AddHandler and Action directives (see below).


Case 2: using --enable-force-cgi-redirect

This compile-time option prevents anyone from calling PHP directly with a url like http://my.host/cgi-bin/php/secretdir/script.php. Instead, PHP will only parse in this mode if it has gone through a web server redirect rule.

Usually the redirection in the Apache configuration is done with the following directives:

Action php-script /cgi-bin/php
AddHandler php-script .php

This option has only been tested with the Apache web server, and relies on Apache to set the non-standard CGI environment variable REDIRECT_STATUS on redirected requests. If your web server does not support any way of telling if the request is direct or redirected, you cannot use this option and you must use one of the other ways of running the CGI version documented here.


Case 3: setting doc_root or user_dir

To include active content, like scripts and executables, in the web server document directories is sometimes consider an insecure practice. If, because of some configuration mistake, the scripts are not executed but displayed as regular HTML documents, this may result in leakage of intellectual property or security information like passwords. Therefore many sysadmins will prefer setting up another directory structure for scripts that are accessible only through the PHP CGI, and therefore always interpreted and not displayed as such.

Also if the method for making sure the requests are not redirected, as described in the previous section, is not available, it is necessary to set up a script doc_root that is different from web document root.

You can set the PHP script document root by the configuration directive doc_root in the configuration file, or you can set the environment variable PHP_DOCUMENT_ROOT. If it is set, the CGI version of PHP will always construct the file name to open with this doc_root and the path information in the request, so you can be sure no script is executed outside this directory (except for user_dir below).

Another option usable here is user_dir. When user_dir is unset, only thing controlling the opened file name is doc_root. Opening an url like http://my.host/~user/doc.php does not result in opening a file under users home directory, but a file called ~user/doc.php under doc_root (yes, a directory name starting with a tilde [~]).

If user_dir is set to for example public_php, a request like http://my.host/~user/doc.php will open a file called doc.php under the directory named public_php under the home directory of the user. If the home of the user is /home/user, the file executed is /home/user/public_php/doc.php.

user_dir expansion happens regardless of the doc_root setting, so you can control the document root and user directory access separately.


Case 4: PHP parser outside of web tree

A very secure option is to put the PHP parser binary somewhere outside of the web tree of files. In /usr/local/bin, for example. The only real downside to this option is that you will now have to put a line similar to:

#!/usr/local/bin/php

as the first line of any file containing PHP tags. You will also need to make the file executable. That is, treat it exactly as you would treat any other CGI script written in Perl or sh or any other common scripting language which uses the #! shell-escape mechanism for launching itself.

To get PHP to handle PATH_INFO and PATH_TRANSLATED information correctly with this setup, the php parser should be compiled with the --enable-discard-path configure option.


Installed as an Apache module

When PHP is used as an Apache module it inherits Apache's user permissions (typically those of the "nobody" user). This has several impacts on security and authorization. For example, if you are using PHP to access a database, unless that database has built-in access control, you will have to make the database accessable to the "nobody" user. This means a malicious script could access and modify the database, even without a username and password. It's entirely possible that a web spider could stumble across a database administrator's web page, and drop all of your databases. You can protect against this with Apache authorization, or you can design your own access model using LDAP, .htaccess files, etc. and include that code as part of your PHP scripts.

Often, once security is established to the point where the PHP user (in this case, the apache user) has very little risk attached to it, it is discovered that PHP is now prevented from writing any files to user directories. Or perhaps it has been prevented from accessing or changing databases. It has equally been secured from writing good and bad files, or entering good and bad database transactions.

A frequent security mistake made at this point is to allow apache root permissions, or to escalate apache's abilitites in some other way.

Escalating the Apache user's permissions to root is extremely dangerous and may compromise the entire system, so sudo'ing, chroot'ing, or otherwise running as root should not be considered by those who are not security professionals.

There are some simpler solutions. By using open_basedir you can control and restrict what directories are allowed to be used for PHP. You can also set up apache-only areas, to restrict all web based activity to non-user, or non-system, files.


Filesystem Security

PHP is subject to the security built into most server systems with respect to permissions on a file and directory basis. This allows you to control which files in the filesystem may be read. Care should be taken with any files which are world readable to ensure that they are safe for reading by all users who have access to that filesystem.

Since PHP was designed to allow user level access to the filesystem, it's entirely possible to write a PHP script that will allow you to read system files such as /etc/passwd, modify your ethernet connections, send massive printer jobs out, etc. This has some obvious implications, in that you need to ensure that the files that you read from and write to are the appropriate ones.

Consider the following script, where a user indicates that they'd like to delete a file in their home directory. This assumes a situation where a PHP web interface is regularly used for file management, so the Apache user is allowed to delete files in the user home directories.

Exemplo 5-1. Poor variable checking leads to....

<?php
// remove a file from the user's home directory
$username = $_POST['user_submitted_name'];
$homedir = "/home/$username";
$file_to_delete = "$userfile";
unlink ("$homedir/$userfile");
echo "$file_to_delete has been deleted!";
?>
Since the username is postable from a user form, they can submit a username and file belonging to someone else, and delete files. In this case, you'd want to use some other form of authentication. Consider what could happen if the variables submitted were "../etc/" and "passwd". The code would then effectively read:

Exemplo 5-2. ... A filesystem attack

<?php
// removes a file from anywhere on the hard drive that
// the PHP user has access to. If PHP has root access:
$username = "../etc/";
$homedir = "/home/../etc/";
$file_to_delete = "passwd";
unlink ("/home/../etc/passwd");
echo "/home/../etc/passwd has been deleted!";
?>
There are two important measures you should take to prevent these issues.

  • Only allow limited permissions to the PHP web user binary.

  • Check all variables which are submitted.

Here is an improved script:

Exemplo 5-3. More secure file name checking

<?php
// removes a file from the hard drive that
// the PHP user has access to.
$username = $_SERVER['REMOTE_USER']; // using an authentication mechanisim

$homedir = "/home/$username";

$file_to_delete = basename("$userfile"); // strip paths
unlink ($homedir/$file_to_delete);

$fp = fopen("/home/logging/filedelete.log","+a"); //log the deletion
$logstring = "$username $homedir $file_to_delete";
fputs ($fp, $logstring);
fclose($fp);

echo "$file_to_delete has been deleted!";
?>
However, even this is not without it's flaws. If your authentication system allowed users to create their own user logins, and a user chose the login "../etc/", the system is once again exposed. For this reason, you may prefer to write a more customized check:

Exemplo 5-4. More secure file name checking

<?php
$username = $_SERVER['REMOTE_USER']; // using an authentication mechanisim
$homedir = "/home/$username";

if (!ereg('^[^./][^/]*$', $userfile))
     die('bad filename'); //die, do not process

if (!ereg('^[^./][^/]*$', $username))
     die('bad username'); //die, do not process
//etc...
?>

Depending on your operating system, there are a wide variety of files which you should be concerned about, including device entries (/dev/ or COM1), configuration files (/etc/ files and the .ini files), well known file storage areas (/home/, My Documents), etc. For this reason, it's usually easier to create a policy where you forbid everything except for what you explicitly allow.


Database Security

Nowadays, databases are cardinal components of any web based application by enabling websites to provide varying dynamic content. Since very sensitive or secret informations can be stored in such database, you should strongly consider to protect them somehow.

To retrieve or to store any information you need to connect to the database, send a legitimate query, fetch the result, and close the connecion. Nowadays, the commonly used query language in this interaction is the Structured Query Language (SQL). See how an attacker can tamper with an SQL query.

As you can realize, PHP cannot protect your database by itself. The following sections aim to be an introduction into the very basics of how to access and manipulate databases within PHP scripts.

Keep in mind this simple rule: defence in depth. In the more place you take the more action to increase the protection of your database, the less probability of that an attacker succeeds, and exposes or abuse any stored secret information. Good design of the database schema and the application deals with your greatest fears.


Designing Databases

The first step is always to create the database, unless you want to use an existing third party's one. When a database is created, it is assigned to an owner, who executed the creation statement. Usually, only the owner (or a superuser) can do anything with the objects in that database, and in order to allow other users to use it, privileges must be granted.

Applications should never connect to the database as its owner or a superuser, because these users can execute any query at will, for example, modifying the schema (e.g. dropping tables) or deleting its entire content.

You may create different database users for every aspect of your application with very limited rights to database objects. The most required privileges should be granted only, and avoid that the same user can interact with the database in different use cases. This means that if intruders gain access to your database using one of these credentials, they can only effect as many changes as your application can.

You are encouraged not to implement all the business logic in the web application (i.e. your script), instead to do it in the database schema using views, triggers or rules. If the system evolves, new ports will be intended to open to the database, and you have to reimplement the logic in each separate database client. Over and above, triggers can be used to transparently and automatically handle fields, which often provides insight when debugging problems with your application or tracing back transactions.


Connecting to Database

You may want to estabilish the connections over SSL to encrypt client/server communications for increased security, or you can use ssh to encrypt the network connection between clients and the database server. If either of them is done, then monitoring your traffic and gaining informations in this way will be a hard work.


Encrypted Storage Model

SSL/SSH protects data travelling from the client to the server, SSL/SSH does not protect the persistent data stored in a database. SSL is an on-the-wire protocol.

Once an attacker gains access to your database directly (bypassing the webserver), the stored sensitive data may be exposed or misused, unless the information is protected by the database itself. Encrypting the data is a good way to mitigate this threat, but very few databases offer this type of data encryption.

The easiest way to work around this problem is to first create your own encryption package, and then use it from within your PHP scripts. PHP can assist you in this case with its several extensions, such as Mcrypt and Mhash, covering a wide variety of encryption algorithms. The script encrypts the data be stored first, and decrypts it when retrieving. See the references for further examples how encryption works.

In case of truly hidden data, if its raw representation is not needed (i.e. not be displayed), hashing may be also taken into consideration. The well-known example for the hashing is storing the MD5 hash of a password in a database, instead of the password itself. See also crypt() and md5().

Exemplo 5-5. Using hashed password field

// storing password hash
$query  = sprintf("INSERT INTO users(name,pwd) VALUES('%s','%s');",
            addslashes($username), md5($password));
$result = pg_exec($connection, $query);

// querying if user submitted the right password
$query = sprintf("SELECT 1 FROM users WHERE name='%s' AND pwd='%s';",
            addslashes($username), md5($password));
$result = pg_exec($connection, $query);

if (pg_numrows($result) > 0) {
    echo "Welcome, $username!";
}
else {
    echo "Authentication failed for $username.";
}

SQL Injection

Many web developers are unaware of how SQL queries can be tampered with, and assume that an SQL query is a trusted command. It means that SQL queries are able to circumvent access controls, thereby bypassing standard authentication and authorization checks, and sometimes SQL queries even may allow access to host operating system level commands.

Direct SQL Command Injection is a technique where an attacker creates or alters existing SQL commands to expose hidden data, or to override valuable ones, or even to execute dangerous system level commands on the database host. This is accomplished by the application taking user input and combining it with static parameters to build a SQL query. The following examples are based on true stories, unfortunately.

Owing to the lack of input validation and connecting to the database on behalf of a superuser or the one who can create users, the attacker may create a superuser in your database.

Exemplo 5-6. Splitting the result set into pages ... and making superusers (PostgreSQL and MySQL)

$offset = argv[0]; // beware, no input validation!
$query  = "SELECT id, name FROM products ORDER BY name LIMIT 20 OFFSET $offset;";
// with PostgreSQL 
$result = pg_exec($conn, $query);
// with MySQL
$result = mysql_query($query);
Normal users click on the 'next', 'prev' links where the $offset is encoded into the URL. The script expects that the incoming $offset is decimal number. However, someone tries to break in with appending urlencode()'d form of the following to the URL

// in case of PostgreSQL
0;
insert into pg_shadow(usename,usesysid,usesuper,usecatupd,passwd)
    select 'crack', usesysid, 't','t','crack'
    from pg_shadow where usename='postgres';
--

// in case of MySQL
0;
UPDATE user SET Password=PASSWORD('crack') WHERE user='root';
FLUSH PRIVILEGES;

If it happened, then the script would present a superuser access to him. Note that 0; is to supply a valid offset to the original query and to terminate it.

Nota: It is common technique to force the SQL parser to ignore the rest of the query written by the developer with -- which is the comment sign in SQL.

A feasible way to gain passwords is to circumvent your search result pages. What the attacker needs only is to try if there is any submitted variable used in SQL statement which is not handled properly. These filters can be set commonly in a preceding form to customize WHERE, ORDER BY, LIMIT and OFFSET clauses in SELECT statements. If your database supports the UNION construct, the attacker may try to append an entire query to the original one to list passwords from an arbitrary table. Using encrypted password fields is strongly encouraged.

Exemplo 5-7. Listing out articles ... and some passwords (any database server)

$query  = "SELECT id, name, inserted, size FROM products
                  WHERE size = '$size'
                  ORDER BY $order LIMIT $limit, $offset;";
$result = odbc_exec($conn, $query);
The static part of the query can be combined with another SELECT statement which reveals all passwords:

'
union select '1', concat(uname||'-'||passwd) as name, '1971-01-01', '0' from usertable;
--

If this query (playing with the ' and --) were assigned to one of the variables used in $query, the query beast awakened.

SQL UPDATEs are also subject to attacking your database. These queries are also threatened by chopping and appending an entirely new query to it. But the attacker might fiddle with the SET clause. In this case some schema information must be possessed to manipulate the query successfully. This can be acquired by examing the form variable names, or just simply brute forcing. There are not so many naming convention for fields storing passwords or usernames.

Exemplo 5-8. From resetting a password ... to gaining more privileges (any database server)

$query = "UPDATE usertable SET pwd='$pwd' WHERE uid='$uid';";
But a malicious user sumbits the value ' or uid like'%admin%'; -- to $uid to change the admin's password, or simply sets $pwd to "hehehe', admin='yes', trusted=100 " (with a trailing space) to gain more privileges. Then, the query will be twisted:

// $uid == ' or uid like'%admin%'; --
$query = "UPDATE usertable SET pwd='...' WHERE uid='' or uid like '%admin%'; --";

// $pwd == "hehehe', admin='yes', trusted=100 "
$query = "UPDATE usertable SET pwd='hehehe', admin='yes', trusted=100 WHERE ...;"

A frightening example how operating system level commands can be accessed on some database hosts.

Exemplo 5-9. Attacking the database host's operating system (MSSQL Server)

$query  = "SELECT * FROM products WHERE id LIKE '%$prod%'";
$result = mssql_query($query);
If attacker submits the value a%' exec master..xp_cmdshell 'net user test testpass /ADD' -- to $prod, then the $query will be:

$query  = "SELECT * FROM products
                    WHERE id LIKE '%a%'
                    exec master..xp_cmdshell 'net user test testpass /ADD'--";
$result = mssql_query($query);

MSSQL Server executes the SQL statements in the batch including a command to add a new user to the local accounts database. If this application were running as sa and the MSSQLSERVER service is running with sufficient privileges, the attacker would now have an account with which to access this machine.

Nota: Some of the examples above is tied to a specific database server. This does not mean that a similar attack is impossible against other products. Your database server may be so vulnerable in other manner.


Avoiding techniques

You may plead that the attacker must possess a piece of information about the database schema in most examples. You are right, but you never know when and how it can be taken out, and if it happens, your database may be exposed. If you are using an open source, or publicly available database handling package, which may belong to a content management system or forum, the intruders easily produce a copy of a piece of your code. It may be also a security risk if it is a poorly designed one.

These attacks are mainly based on exploiting the code not being written with security in mind. Never trust on any kind of input, especially which comes from the client side, even though it comes from a select box, a hidden input field or a cookie. The first example shows that such a blameless query can cause disasters.

  • Never connect to the database as a superuser or as the database owner. Use always customized users with very limited privileges.

  • Check if the given input has the expected data type. PHP has a wide range of input validating functions, from the simplest ones found in Variable Functions and in Character Type Functions (e.g. is_numeric(), ctype_digit() respectively) onwards the Perl compatible Regular Expressions support.

  • If the application waits for numerical input, consider to verify data with is_numeric(), or silently change its type using settype(), or use its numeric representation by sprintf().

    Exemplo 5-10. A more secure way to compose a query for paging

    settype($offset, 'integer');
    $query = "SELECT id, name FROM products ORDER BY name LIMIT 20 OFFSET $offset;";
    
    // please note %d in the format string, using %s would be meaningless
    $query = sprintf("SELECT id, name FROM products ORDER BY name LIMIT 20 OFFSET %d;",
                     $offset);

  • Quote each non numeric user input which is passed to the database with addslashes() or addcslashes(). See the first example. As the examples shows, quotes burnt into the static part of the query is not enough, and can be easily hacked.

  • Do not print out any database specific information, especially about the schema, by fair means or foul. See also Error Reporting and Error Handling and Logging Functions.

  • You may use stored procedures and previously defined cursors to abstract data access so that users do not directly access tables or views, but this solution has another impacts.

Besides these, you benefit from logging queries either within your script or by the database itself, if it supports. Obviously, the logging is unable to prevent any harmful attempt, but it can be helpful to trace back which application has been circumvented. The log is not useful by itself, but through the information it contains. The more detail is generally better.


Error Reporting

With PHP security, there are two sides to error reporting. One is beneficial to increasing security, the other is detrimental.

A standard attack tactic involves profiling a system by feeding it improper data, and checking for the kinds, and contexts, of the errors which are returned. This allows the system cracker to probe for information about the server, to determine possible weaknesses. For example, if an attacker had gleaned information about a page based on a prior form submission, they may attempt to override variables, or modify them:

Exemplo 5-11. Attacking Variables with a custom HTML page

<form method="post" action="attacktarget?username=badfoo&password=badfoo">
<input type="hidden" name="username" value="badfoo">
<input type="hidden" name="password" value="badfoo">
</form>

The PHP errors which are normally returned can be quite helpful to a developer who is trying to debug a script, indicating such things as the function or file that failed, the PHP file it failed in, and the line number which the failure occured in. This is all information that can be exploited. It is not uncommon for a php developer to use show_source(), highlight_string(), or highlight_file() as a debugging measure, but in a live site, this can expose hidden variables, unchecked syntax, and other dangerous information. Especially dangerous is running code from known sources with built-in debugging handlers, or using common debugging techniques. If the attacker can determine what general technique you are using, they may try to brute-force a page, by sending various common debugging strings:

Exemplo 5-12. Exploiting common debugging variables

<form method="post" action="attacktarget?errors=Y&amp;showerrors=1"&debug=1">
<input type="hidden" name="errors" value="Y">
<input type="hidden" name="showerrors" value="1">
<input type="hidden" name="debug" value="1">
</form>

Regardless of the method of error handling, the ability to probe a system for errors leads to providing an attacker with more information.

For example, the very style of a generic PHP error indicates a system is running PHP. If the attacker was looking at an .html page, and wanted to probe for the back-end (to look for known weaknesses in the system), by feeding it the wrong data they may be able to determine that a system was built with PHP.

A function error can indicate whether a system may be running a specific database engine, or give clues as to how a web page or programmed or designed. This allows for deeper investigation into open database ports, or to look for specific bugs or weaknesses in a web page. By feeding different pieces of bad data, for example, an attacker can determine the order of authentication in a script, (from the line number errors) as well as probe for exploits that may be exploited in different locations in the script.

A filesystem or general PHP error can indicate what permissions the webserver has, as well as the structure and organization of files on the web server. Developer written error code can aggravate this problem, leading to easy exploitation of formerly "hidden" information.

There are three major solutions to this issue. The first is to scrutinize all functions, and attempt to compensate for the bulk of the errors. The second is to disable error reporting entirely on the running code. The third is to use PHP's custom error handling functions to create your own error handler. Depending on your security policy, you may find all three to be applicable to your situation.

One way of catching this issue ahead of time is to make use of PHP's own error_reporting(), to help you secure your code and find variable usage that may be dangerous. By testing your code, prior to deployment, with E_ALL, you can quickly find areas where your variables may be open to poisoning or modification in other ways. Once you are ready for deployment, by using E_NONE, you insulate your code from probing.

Exemplo 5-13. Finding dangerous variables with E_ALL

<?php
if ($username) {  // Not initialized or checked before usage
    $good_login = 1;
}
if ($good_login == 1) { // If above test fails, not initialized or checked before usage
    fpassthru ("/highly/sensitive/data/index.html");
}
?>


Using Register Globals

One feature of PHP that can be used to enhance security is configuring PHP with register_globals = off. By turning off the ability for any user-submitted variable to be injected into PHP code, you can reduce the amount of variable poisoning a potential attacker may inflict. They will have to take the additional time to forge submissions, and your internal variables are effectively isolated from user submitted data.

While it does slightly increase the amount of effort required to work with PHP, it has been argued that the benefits far outweigh the effort.

Exemplo 5-14. Working with register_globals=on

<?php
if ($username) {  // can be forged by a user in get/post/cookies
    $good_login = 1;
}

if ($good_login == 1) { // can be forged by a user in get/post/cookies,
    fpassthru ("/highly/sensitive/data/index.html");
}
?>

Exemplo 5-15. Working with register_globals = off

<?php
if($_COOKIE['username']){
    // can only come from a cookie, forged or otherwise
    $good_login = 1;
    fpassthru ("/highly/sensitive/data/index.html");
}
?>
By using this wisely, it's even possible to take preventative measures to warn when forging is being attempted. If you know ahead of time exactly where a variable should be coming from, you can check to see if submitted data is coming from an inappropriate kind of submission. While it doesn't guarantee that data has not been forged, it does require an attacker to guess the right kind of forging.

Exemplo 5-16. Detecting simple variable poisoning

<?php
if ($_COOKIE['username'] &&
    !$_POST['username'] &&
    !$_GET['username'] ) {
    // Perform other checks to validate the user name...
    $good_login = 1;
    fpassthru ("/highly/sensitive/data/index.html");
} else {
   mail("admin@example.com", "Possible breakin attempt", $_SERVER['REMOTE_ADDR']);
   echo "Security violation, admin has been alerted.";
   exit;
}
?>
Of course, simply turning off register_globals does not mean code is secure. For every piece of data that is submitted, it should also be checked in other ways.


User Submitted Data

The greatest weakness in many PHP programs is not inherent in the language itself, but merely an issue of code not being written with security in mind. For this reason, you should always take the time to consider the implications of a given piece of code, to ascertain the possible damage if an unexpected variable is submitted to it.

Exemplo 5-17. Dangerous Variable Usage

<?php
// remove a file from the user's home directory... or maybe
// somebody else's?
unlink ($evil_var);

// Write logging of their access... or maybe an /etc/passwd entry?
fputs ($fp, $evil_var);

// Execute something trivial.. or rm -rf *?
system ($evil_var);
exec ($evil_var);

?>
You should always carefully examine your code to make sure that any variables being submitted from a web browser are being properly checked, and ask yourself the following questions:

  • Will this script only affect the intended files?

  • Can unusual or undesirable data be acted upon?

  • Can this script be used in unintended ways?

  • Can this be used in conjunction with other scripts in a negative manner?

  • Will any transactions be adequately logged?

By adequately asking these questions while writing the script, rather than later, you prevent an unfortunate re-write when you need to increase your security. By starting out with this mindset, you won't guarantee the security of your system, but you can help improve it.

You may also want to consider turning off register_globals, magic_quotes, or other convenience settings which may confuse you as to the validity, source, or value of a given variable. Working with PHP in error_reporting(E_ALL) mode can also help warn you about variables being used before they are checked or initialized (so you can prevent unusual data from being operated upon).


Hiding PHP

In general, security by obscurity is one of the weakest forms of security. But in some cases, every little bit of extra security is desirable.

A few simple techniques can help to hide PHP, possibly slowing down an attacker who is attempting to discover weaknesses in your system. By setting expose_php = off in your php.ini file, you reduce the amount of information available to them.

Another tactic is to configure web servers such as apache to parse different filetypes through PHP, either with an .htaccess directive, or in the apache configuration file itself. You can then use misleading file extensions:

Exemplo 5-18. Hiding PHP as another language

# Make PHP code look like other code types
AddType application/x-httpd-php .asp .py .pl
Or obscure it completely:

Exemplo 5-19. Using unknown types for PHP extensions

# Make PHP code look like unknown types
AddType application/x-httpd-php .bop .foo .133t
Or hide it as html code, which has a slight performance hit because all html will be parsed through the PHP engine:

Exemplo 5-20. Using html types for PHP extensions

# Make all PHP code look like html
AddType application/x-httpd-php .htm .html
For this to work effectively, you must rename your PHP files with the above extensions. While it is a form of security through obscurity, it's a minor preventative measure with few drawbacks.


Keeping Current

PHP, like any other large system, is under constant scrutiny and improvement. Each new version will often include both major and minor changes to enhance and repair security flaws, configuration mishaps, and other issues that will affect the overall security and stability of your system.

Like other system-level scripting languages and programs, the best approach is to update often, and maintain awareness of the latest versions and their changes.

II. Referência da Linguagem


Capítulo 6. Sintaxe básica

Alternado/Escaping do HTML

Quando o PHP interpreta um arquivo, ele simplesmente repassa o texto do arquivo até encontrar uma das tags especiais que lhe diz para começar a interpretar o texto como código PHP. O interpretador então executa todo o código que encontra, até chegar em uma tag de fechamento PHP, que novamente o coloca simplesmente repassando texto novamente. Este é o mecanismo que permite a inclusão de código PHP dentro do HTML: qualquer coisa fora das tags PHP é deixado como encontrado, enquanto tudo dentro é interpretado e executado.

Há quatro conjuntos de tags que podem ser usadas para marcar blocos de código PHP. Delas, somente duas (<?php. . .?> e <script language="php">. . .</script>) são sempre disponíveis. As outras podem ser ativadas ou desativadas a partir do arquivo de configuração php.ini. Enquanto as formas reduzidas das tags ou no seu estilo ASP serem convenientes, elas não são portáveis em todas as versões. Além disso, se você pretende incluir código PHP em XML ou XHTML, você precisará usar a forma <?php ... ?> para compatibilidade com o padrão XML.

As tags suportadas pelo PHP são:

Exemplo 6-1. Maneiras de alternar do HTML

1.  <?php echo("se você precisa dispor documentos XHTML ou XML, use assim\n"); ?>

2.  <? echo ("este é o mais simples, como uma instrução de processamento SGML\n"); ?>
    <?= espressao ?> Uma redução de "<? echo expressao ?>"

3.  <script language="php">
        echo ("alguns editores (como o FrontPage) não
              gostam de processas instruções");
    </script>

4.  <% echo ("Você também pode usar tags ASP opcionalmente"); %>
    <%= $variavel; # Uma redução para "<% echo ..." %>

O primeiro método, <?php. . .?>, é o preferencial, já que ele permite o uso do PHP em códigos padrão XML como o XHTML.

O segundo método pode não estar sempre disponível. Tags curtas estão disponíveis apenas quando ativadas. Isto pode ser realizando através da função short_tags() (PHP 3 somente), ativando a diretiva de configuração short_open_tag no arquivo de configuração do PHP ou compilando o PHP com a opção --enable-short-tags no configure. Mesmo que ele esteja configurado por default no php.ini-dist, o uso de tags curtas é desencorajado.

A quarta maneira só está disponível se a tag estilo ASP for ativada utilizando a diretiva asp_tags no arquivo de configuração.

Nota: O suporte as tags estilo APS foi incorporada na versão 3.0.4.

Nota: A utilização das tags curtas deve ser evitada quando do desenvolvimento de aplicações ou bibliotecas com intenção de redistribuição ou no desenvolvimento de serviços em PHP que não ficarão sob seu controle, uma vez que as tags curtas podem não estar disponíveis no servidor de instalação. Para portabilidade de código para distribuição, tenha certeza de não usar tags curtas.

A tag de fechamento incluirá uma linha nova linha em branco automaticamente se uma não estiver presente. Além, a tag de fechamento automaticamente implica num ponto e vírgula: você não precisa ter um ponto e vírgula no fim da última linha de código PHP.

O PHP também suporta a utilização de estruturas como essa:

Exemplo 6-2. Alternagem avançada

<?php
if ($expression) {
    ?>
    <strong>Isso é verdadeiro.</strong>
    <?php
} else {
    ?>
    <strong>Isto é falso.</strong>
    <?php
}
?>
Isso funciona como esperado porque quando o PHP encontra a tag de fechamento ?>, ele simplesmente começa a imprimir tudo até encontrar outra tag de abertura. Obviamente, o exemplo acima se aplica a exibição de grandes blocos de texto, uma vez que sair do modo de interpretação do PHP é geralmente mais eficiente que imprimir todo o texto através de funções como echo(), print() e outras.


Separador de instruções

Instruções são separadas da mesma forma que o C ou o Perl - cada instrução termina com um ponto e vírgula.

A tag de fechamento (?>) também implica no fim de uma instrução, então os exemplos seguintes são equivalentes:

<?php
    echo "Isto é um teste";
?>

<?php echo "Isto é um outro teste" ?>


Comentários

O PHP suporta comentários do 'C', 'C++' e Unix shell. Por exemplo

<?php
    echo "Isto é um teste"; //Comentário de uma linha no C++
    /* Isto é um comentário de mais de uma linha
       e aqui temos outra linha */
    echo "Isto é um outro teste";
    echo "O último teste"; #Comentário no estilo Unix shell
?>

Os comentário de uma linha só tem efeito até o fim da linha ou fim do bloco de código PHP atual, o que ocorrer primeiro.

<h1>Isto é um <?php # echo " simples";?> exemplo.</h1>
<p>No título acima você lerá 'Isto é um exemplo'.

Você precisa ser cuidadoso com comentários estilo 'C' encadeados, pois eles podem causar problemas em grandes blocos.

<?php
 /*
    echo "Isto é um teste"; /* Este comentário causará um erro */
 */
?>

Os comentários de uma linha somente agem até o fim da linha atual ou o fim do bloco de código PHP, o que ocorrer primeiro. Isto significa que código HTML após // ?> SERÁ impresso: ?> continuará desligando o modo PHP, retornando para o modo HTML, e o // não pode influenciar isso.


Capítulo 7. Tipos

Introdução

O PHP suporta os oitos tipos primitivos.

São quatros tipos básicos:

Dois tipos compostos:

E finalmente dois tipos especiais:

Este manual também introduz alguns pseudo-tipos por razões de legibilidade:

O tipo da variável geralmente não é configurado pelo programador: isto é decidido em tempo de execução pelo PHP, dependendo do contexto no qual a variável é usada.

Nota: Se você quiser checar o tipo e valor de uma certa expressão, utilize var_dump().

Se você simplesmente quiser uma representação legível de seu tipo para debugagem, use gettype(). Para verificar por certos tipos, não use gettype(), mas sim as funções is_type.

Se você quiser forçar a conversão de uma variável para um certo tipo, você pode moldar (casting) a variável ou usar a função settype() nela.

Note que uma variável pode se comportar de maneiras diferentes em certas situações, dependendo de qual tipo ela é no momento. Para mais informações, veja a seção Manipulação de tipos.


Booleanos

Este é o tipo mais fácil. Umbooleano expressa um valor de verdade. Ele pode ser TRUE ou FALSE.

Nota: O tipo booleano foi introduzido no PHP 4.


Sintaxe

Para especificar um literal booleano, use as palavras chave TRUE ou FALSE. Ambas são insensitivas ao caso.

$foo = True; // assimila o valor TRUE para $foo

Usualmente você pode utilizar algum tipo de operador que retorne um valor booleano, e passá-lo para uma estrutura de controle.

// == é um operador que retorna um booleano
if ($action == "mostrar_versao") {
    echo "A versão é 1.23";
}

// isto não é necessário
if ($exibir_separadores == TRUE) {
    echo "<hr>\n";
}

// porque você pode simplesmente escrever isso:
if ($exibir_separadores) {
    echo "<hr>\n";
}


Convertendo para booleano

Para converter explicitamente um valor para booleano, utilize-se dos modificadores (bool) ou (boolean). Entretanto, na maioria dos casos, você não precisa utilizar o modificador, desde que qualquer valor será convertido automaticamente se um operador, função ou estrutura de controle requerer um argumento booleano.

Veja também Manipulação de tipos.

Quando convertendo para booleano, os seguintes valores são considerados FALSE:

Qualquer outro valor é considerado TRUE (incluindo qualquer recurso).

Atenção

-1 é considerado TRUE, como qualquer valor não zero (negativos ou positivos)!


Inteiros

Um inteiro é um número do conjunto Z = {..., -2, -1, 0, 1, 2, ...}.

Veja também: Inteiros de tamanho arbitrário e Números de ponto flutuante


Sintaxe

Inteiros podem ser especificados em notação decimal (base 10), hexadecimal (base 16) ou octal (base 8), opcionalmente precedido de sinal (- ou +).

Para usar a notação octal, você precisa preceder o número com um 0 (zero). Para utilizar a notação hexadecimal, preceda número com 0x.

Exemplo 7-1. Literais inteiras

$a = 1234; # número decimal
$a = -123; # um número negativo
$a = 0123; # número octal (equivalente a 83 em decimal)
$a = 0x1A; # número hexadecimal (equivalente a 26 em decimal)
O tamanho de um inteiro é dependente de plataforma, sendo um numero aproximado a 2 bilhões o valor mais comum (número de 32 bits com sinal). O PHP não suporta inteiros não sinalizados.


Overflow de inteiros

Se você especifica um número além dos limites do tipo inteiro, ele será interpretado como um ponto flutuante. Assim, se você realizar uma operação que resulte em um número além dos limites do tipo inteiro, um ponto flutuante será retornado também.

$ numero_grande =  2147483647;
var_dump($numero_grande);
// saida: int(2147483647)

$numero_grande =  2147483648;
var_dump($numero_grande);
// saida: float(2147483648)

// isto também é permitido para especificação de números hexadecimais:
var_dump( 0x80000000 );
// saida: float(2147483648)

$milhao = 1000000;
$numero_grande =  50000 * $milhao;
var_dump($numero_grande);
// saida: float(50000000000)

Atenção

Infelizmente, há um bug no PHP que faz que ele nem sempre trabalhe corretamente quando há números negativos envolvidos. Por exemplo, quando você faz -50000 * $milhao, o resultado será -429496728. Entretanto, quando ambos os operadores são positivos, isso não ocorre.

Isto foi resolvido no PHP 4.1.0.

Não há operador de divisão inteira no PHP. 1/2 retorna o ponto flutuante 0.5.

var_dump( 25/7 );
// saida: float(3.5714285714286)


Convertendo para inteiro

Para converter explicitamente um valor para inteiro, utilize-se dos modificadores (int) ou (integer). Entretanto, na maioria dos casos, você não precisa utilizar o modificador, desde que qualquer valor será automaticamente convertido se um operador, função ou estrutura de controle requerer um argumento inteiro.

Veja também Manipulação de tipos.


de booleanos

FALSE será retornado como 0 (zero), e TRUE como 1 (um).


De números de ponto flutuante

Quando convertendo de números de ponto flutuante para inteiros, o número será truncado.

Se o número convertido estiver além dos limites de um inteiro (usualmente +/- 2.15e+9 = 2^31), o resultado é indefinido, mesmo porque o ponto flutuante não tem a mesma precisão para fornecer um resultado inteiro exato. Não se preocupe, pois nenhum aviso será emitido neste caso!

Atenção

Nunca modifique uma fração desconhecida para inteiro, porque isto pode fornecer resultados inesperados as vezes.

echo (int) ( (0.1+0.7) * 10 ); // imprime 7!

Para maiores informações, veja o alerta sobre a precisão de número flutuante..


De strings

Veja Conversão de strings


De outros tipos

Cuidado

O comportamento da conversão de um inteiro é indefinido de outros tipos. Atualmente, o comportamento é o mesmo como se primeiro o valor fosse convertido para booleano. Entretanto, não confie neste comportamento, pois ele pode mudar sem aviso.


Números de ponto flutuante

Números de ponto flutuante (AKA "floats", "doubles" ou "números reais") podem ser especificados utilizando qualquer uma das sintaxes seguintes:
$a = 1.234; $a = 1.2e3; $a = 7E-10;
O tamanho de um número de ponto flutuante é dependente de plataforma, sendo o máximo de ~1.8e308 com uma precisão de 14 decimais digitais um valor comum (número de 64 bits no formato IEEE).

Precisão de números de ponto flutuante

É sabido que frações simples como 0.1 ou 0.7 não podem ser convertidos em sua representação binária interna sem uma pequena perda de precisão. Isto pode causar erros confusos: por exemplo, floor((0.1+0.7)*10) irá retornar 7 em vez do esperado 8, como resultado da representação interna realmente ser algo como 7.9999999999....

Isto está relacionado ao fato de que é impossível expressar, exatamente, algumas frações em notação decimal com um número finito de dígitos. Por exemplo, 1/3 na forma decimal se torna 0.3333333. . ..

Então, nunca confie em resultados com números de ponto flutuante até a última casa e nunca compare números de ponto flutuante em igualdades. Se você realmente precisar de alta precisão, você pode utilizar as funções matemáticas de precisão arbitrária ou as funções relacionadas ao gmp.


Strings

Uma string é uma série de caracteres. No PHP, um caracter é o mesmo que um byte, ou seja, há exatamente 256 caracteres diferentes possíveis. Isto implica que o PHP não tem suporte nativo ao Unicode.

Nota: Não há nenhum problema nas strings se tornarem muito grandes. Não há nenhum limite para o tamanho de strings imposta pelo PHP, então não há razão para se preocupar com strings longas.


Sintaxe

Uma string literal pode ser especificada de três formas diferentes.


Apóstrofos

A maneira mais simples para especificar uma string é delimitá-la entre apóstrofos (o caracter ').

Para especificar um apóstrofo. você precisará "escapá-la" com uma contra barra (\), como em muitas outras linguagens. Se uma contra barra precisa ocorrer antes de um apóstrofo ou no final da string, você precisa duplicá-la. Note que se você tentar escapar qualquer outro caracter, a contra barra também será impressa! Então geralmente não é necessário escapar a própria contra barra.

Nota: No PHP 3, um aviso com nível E_NOTICE será emitido quando isto acontecer.

Nota: Diferentemente das duas outras sintaxes, variáveis não serão substituídas quando elas ocorrerem dentro de strings delimitadas por apóstrofes.

echo 'isto é uma string comum';
echo 'Você pode incluir novas linhas em strings,
dessa maneira';
echo 'Arnold disse uma vez: "I\'ll be back"';
// saida: ... "I'll be back"
echo 'Você tem certeza em apagar C:\\*.*?';
// saida: ... apagar C:\*.*?
echo 'Você tem certeza em apagar C:\*.*?';
// output: ... apagar C:\*.*?
echo 'Estou tentando incluir uma nova linha \n neste ponto';
// output: ... nova linha \n neste ponto


Aspas

Se a string é delimitada entre aspas ("), o PHP entende mais seqüências de escape para caracteres especiais:

Tabela 7-1. Seqüências de escape

Seqüência Significado
\n fim de linha (linefeed ou LF ou 0x0A (10) em ASCII)
\r retorno de carro (carriage return ou CR ou 0x0D (13) em ASCII)
\t TAB horizontal (HT ou 0x09 (9) em ASCII)
\\ contra barra ou barra invertida
\$ sinal de cifrão
\" aspas
\[0-7]{1,3} a seqüência de caracteres batendo a expressão regular dos caracteres em notação octal
\x[0-9A-Fa-f]{1,2} a seqüência de caracteres batendo a expressão regular de um caracter em notação hexadecimal

Novamente se você tentar escapar qualquer outro caracter, a contra barra será impressa também!

Mas o mais importante dado a respeito de strings delimitadas por aspas está no fato de que nome de variáveis serão substituídos. Veja interpretação de strings para detalhes.


Heredoc

Outra maneira para delimitar strings é utilizando a sintaxe heredoc ("<<<"). É informado um identificador depois de <<<, então a string, e então o mesmo identificador para fechar a delimitação.

O identificador de fechamento precisa começar na primeira coluna da linha. Além, o identificador utilizado precisa seguir as mesmas regras de nomeação que qualquer outro rótulo no PHP: só pode conter caracteres alfanuméricos e sublinhados, e precisa começar com um caracter não numérico ou sublinhado.

Atenção

É muito importante verificar que a linha do identificador de fechamento não contenha nenhum outro caracter, exceto, possivelmente um ponto e vírgula (;). O que significa que o identificador não pode ser endentado, e que não pode haver nenhum espaço ou tabulações antes ou depois do ponto e vírgula.

Textos heredoc se comportam como strings delimitadas por aspas, com apenas uma diferença. Você não precisa escapar apóstrofos e aspas em seus heredocs, mas você ainda pode continuar utilizando os códigos de escape listados acima. Variáveis são substituídas, mas o mesmo cuidado precisa ser tomado quando expressando variáveis complexas dentro de heredocs assim como nas strings.

Exemplo 7-2. Exemplo de delimitação de strings heredoc

<?php
$str = <<<EOD
Exemplo de uma string
distribuída em várias linhas
utilizando a sintaxe heredoc.
EOD;

/* Exemplo mais complexo, com variáveis */
class foo
{
    var $foo;
    var $bar;

    function foo()
    {
        $this->foo = 'Foo';
        $this->bar = array('Bar1', 'Bar2', 'Bar3');
    }
}

$foo = new foo();
$name = 'Meu nome';

echo <<<EOT
Meu nome é "$name". Eu estou imprimindo $foo->foo.
Agora, eu estou imprimindo {$foo->bar[1]}.
Isto deve imprimir um 'A' maiúsculo: \x41
EOT;
?>

Nota: O suporte a heredoc foi acrescentado no PHP 4.


Interpretação de variáveis

Quando uma string é especificada dentro de aspas ou heredoc, variáveis são interpretadas dentro delas.

Há dois tipos de sintaxe, um simples e um complexo . A sintaxe simples é a mais comum e conveniente, provendo uma maneira de interpretar uma variável, um valor de array ou uma propriedade de objeto.

A sintaxe completa foi introduzida no PHP 4, e pode ser reconhecida por chaves ({}) envolvendo a expressão.


Sintaxe simples

Se um sinal de cifrão ($) é encontrado, o interpretador tentará obter tantos identificadores quanto possíveis para formar um nome de variável válido. Envolva o nome da variável com chaves se você deseja explicitamente especificar o fim do nome.

$cerveja = 'Heineken';
echo "O sabor das '$cerveja's é otimo"; // funciona, "'" é um caracter inválido para nome de variáveis
echo "Ele bebeu algumas $cervejas";     // não funciona, 's' é um caracter válido para nome de variáveis
echo "Ele bebeu algumas ${cerveja}s";   // funciona

Similarmente, você também pode interpretar um índice de array ou uma propriedade de objeto. Com índices de arrays, o colchete de fechamento (]) marca o final do índice. Para propriedades de objetos se aplicam as mesmas regras das variáveis comuns, embora não exista um truque para as propriedades de objetos como para as variáveis.

$frutas = array( 'morangos' => 'vermelho' , 'banana' => 'amarelo' );

// note que isto funciona diferentemente fora de delimitadores de string
echo "Uma banana é $frutas[banana].";

echo "Este quadrado tem $square->width metros de lado.";

// Não funciona. Para uma solução, veja a sintaxe complexa.
echo "Este quadrado tem $square->width00 centímetros de lado.";

Para qualquer coisa mais complexa, você precisa utilizar a sintaxe complexa.


Sintaxe complexa (chaves)

Isto não é chamado sintaxe complexa porque a sintaxe em si é complexa, mas porque você pode incluir expressões complexas desta maneira.

De fato, você pode incluir qualquer valor no que esteja no espaço de nomes dentro de strings com esta sintaxe. Você simplesmente escreve a expressão da mesma maneira que faria fora da string, e então incluí-la entre chaves. Desde que você não pode escapar '{', esta sintaxe somente será reconhecida quando o $ é imediatamente seguido de um {. (Utilize "{\$" ou "\{$" para obter um literal "{$"). Alguns exemplos para tornar isso mais claro:

$maravilhoso = 'fantástico';
echo "Isto é { $maravilhoso}"; // não funciona, imprime: Isto é { fantástico}
echo "Isto é {$maravilhoso}";  // funciona, imprime: Isto é fantástico
echo "Este quadrado tem {$square->width}00 centímetros de lado.";
echo "E isto funciona: {$arr[4][3]}";

// E isto está errado pela mesma razão
// como $foo[bar] é incorreto fora de uma string.
echo "Isto está errado: {$arr[foo][3]}";

echo "Você deve fazer desta maneira: {$arr['foo'][3]}";
echo "Você pode sempre escrever {$obj->values[3]->name}";
echo "Este é o valor da variável chamada $name: {${$name}}";


Acesso a caracteres da string

Caracteres nas strings podem ser acessados apenas especificando o deslocamento baseado em zero do caracter desejado depois da string dentro de chaves.

Nota: Para manutenção de compatibilidade, você ainda pode utilizar colchetes. Entretanto, esta sintaxe for marcada como em extinção desde o PHP 4.

Exemplo 7-3. Alguns exemplos com strings

<?php
/* Assimilando uma string. */
$str = "Isto é uma string";

/* Anexando a ela. */
$str = $str . " com uma pouco mais de texto";

/* Outra maneira de acrescentar, incluindo uma nova linha. */
$str .= " e um fim de linha no final (duh).\n";

/* Esta string será mostrada assim '<p>Número: 9</p>' */
$num = 9;
$str = "<p>Número: $num</p>";

/* Isto será apenas '<p>Número: $num</p>' */
$num = 9;
$str = '<p>Número: $num</p>';

/* Pega o primeiro caracter de uma string */
$str = 'Isto é um teste.';
$first = $str{0};

/* Pega o último caracter da string. */
$str = 'Isto ainda é um teste.';
$last = $str{strlen($str)-1};
?>


Funções úteis

Strings podem ser concatenados utilizando o operador '.' (ponto). Note que o operador '+' (adição) não funciona para isso. Veja operadores de string para mais informações.

Há uma grande quantidade de funções úteis para modificação de strings.

Veja a seção de funções de string para funções gerais e funções de expressões regulares para busca e substituição avançada.(em dois sabores: Perl e POSIX estendido).

Há também funções para strings URL e funções para criptografia e descriptografia de strings (mcrypt e mhash).

Finalmente, se você ainda não encontrar o que está procurando, veja também as funções de tipos de caracteres.


Conversão de strings

Quando uma string é avaliada como um valor numérico, o valor resultante e o tipo é determinado como segue.

A string será avaliada como um ponto flutuante se conter qualquer um dos caracteres '.', 'e', ou 'E'. Em outros casos, ela será avaliada como um inteiro.

O valor é obtido da porção inicial da string. Se a string começa com dados numéricos válidos, esse será o valor utilizado. Em outro caso, o valor será 0 (zero). Dados numéricos válidos são: um sinal opcional, seguido por um ou mais dígitos (opcionalmente contendo um ponto decimal), seguido de um expoente, também opcional. O expoente é um 'e' ou 'E' seguido de um ou mais dígitos.

$foo = 1 + "10.5";                // $foo é ponto flutuante (11.5)
$foo = 1 + "-1.3e3";              // $foo é ponto flutuante (-1299)
$foo = 1 + "bob-1.3e3";           // $foo é ponto inteiro (1)
$foo = 1 + "bob3";                // $foo é ponto inteiro (1)
$foo = 1 + "10 Small Pigs";       // $foo é ponto inteiro (11)
$foo = 4 + "10.2 Little Piggies"; // $foo é ponto flutuante (14.2)
$foo = "10.0 pigs " + 1;          // $foo é ponto flutuante (11)
$foo = "10.0 pigs " + 1.0;        // $foo é ponto flutuante (11)

Para mais informações sobre esta conversão, veja página do manual UNIX de strtod(3).

Se você deseja testar qualquer um dos exemplo dessa seção, você pode copiar e colar os exemplos e inserir as linhas seguintes para ver por si mesmo como isso funciona.

echo "\$foo==$foo; tipo " . gettype ($foo) . "<br />\n";


Arrays

Um array no PHP é atualmente um mapa ordenado. Um mapa é um tipo que relaciona valores para chaves. Este tipo é otimizado de várias maneiras, então você pode usá-lo como um array real, ou uma lista (vetor), hashtable (que é uma implementação de mapa), dicionário, coleção, pilha, fila e provavelmente mais. Como você pode ter outro array PHP como um valor, você pode facilmente simular árvores.

A explicação dessas estruturas estão além do escopo desse manual, mas você pode encontrar exemplos para cada uma dessas estruturas a seguir. Para mais informações sobre estruturas, refira-se a literatura externa sobre esses tópicos.


Sintaxe

Especificando com array()

Um array pode ser criado com o construtor de linguagem array(). Ele pega um certo número de pares separados por vírgula chave => valor .

Uma chave pode ser tanto um inteiro ou uma string. Se a chave é uma representação padrão de um inteiro, ele será interpretado assim (por exemplo, "8" será interpretado como 8, enquanto "08" será interpretado como "08").

O valor pode ser qualquer coisa.

Se omitir a chave, o maior índice inteiro é obtido, e a nova chave será esse máximo + 1. Como inteiros podem ser negativos, isto também é verdadeiro para índices negativos. Sendo, por exemplo, o maior índice -6, resultará em um novo índice -5. Se nenhum índice inteiro existir ainda, a chave será 0 (zero). Se você especifica uma chave que já possui um valor assimilada a ela, então o valor é sobrescrito.

Utilizar true como chave será interpretado como inteiro 1 na chave. Utilizando false como chave será avaliado como o inteiro 0. Usar NULL como chave é interpretado como uma string vazia. Usar uma string vazia como chave irá criar (ou sobrescerver) uma chave com uma string vazia e seu valor, e isto não é o mesmo que usar colchetes vazios.

Você não pode usar arrays ou objetos como chaves. Fazendo isso resultará em um alerta: Illegal offset type.

array( [chave =>] valor
     , ...
     )
// chave pode ser string ou integer não negativo
// valor pode ser qualquer coisa


Criando/modificando com a sintaxe de colchetes

Você pode também modificar um array existente, explicitando assimilando valores.

Isto é feito apenas assimilando valores para o array enquanto especificando a chave em colchetes. Você pode omitir a chave, colocando um par vazio de colchetes ("[]").
$arr[chave] = valor;
$arr[] = valor;
// chave tanto um string ou inteiro não negativo
// valor pode ser qualquer coisa
Se $arr não existir ainda, ele será criado. Então isto é um meio alternativo para especificar um array. Para mudar um certo valor, apenas assimile um novo valor para nele. Se você quiser remover um par chave/valor, você precisa aplicar unset() nele.


Funções úteis

Há uma série de funções muito úteis para trabalhar com arrays, veja a seção sobre arrays .

Nota: A função unset() permite apagar chaves de um array. Esteja avisado que o array NÃO vai ser reindexado.

$a = array( 1 => 'um', 2 => 'dois', 3 => 'três' );
unset( $a[2] );
/* irá produzir um array que pode ser definido como
   $a = array( 1=>'um', 3=>'três');
   e NÃO
   $a = array( 1 => 'um', 2 => 'três');
*/

foreach existe especificamente para lidar com arrays. Ele provém uma maneira fácil de percorrer qualquer array.


Array: faça e não faça

Porque $foo[bar] está errado?

Você sempre deve usar delimitadores em volta um índice de um array associativo. Por exemplo, utilizar $foo['bar'] e não $foo[bar]. Mas porque $foo[bar] está errado? Afinal de contas, você vê essa sintaxe nos scripts antigos:

$foo[bar] = 'inimigo';
echo $foo[bar];
// etc

Isto está errado, mas funciona. Então, porque está errado? A razão está neste código, que tem uma constante indefinida (bar) em vez de uma string ('bar' - repare nos delimitadores), e o PHP pode no futuro definir constantes que, infelizmente em seu código, podem ter o mesmo nome. Isto funciona, porque constantes não definidas são convertidas em uma string com o mesmo nome.

Como explicado na seção sintaxe, a chave precisa estar entre colchetes ('[' e ']'). Isto significa que você pode escrever coisas como isso:

echo $arr[ foo(true) ];

Isto é um exemplo de utilização de um valor de retorno de função como um índice de array. O PHP conhece constantes, como você deve ter visto E_* antes.

$error_descriptions[E_ERROR] = "Um erro fatal ocorreu";
$error_descriptions[E_WARNING] = "O PHP emitiu um alarme";
$error_descriptions[E_NOTICE] = "Apenas um aviso informal";

Note que E_ERROR é um identificador válido, assim como bar no primeiro exemplo. Mas no último exemplo seria a mesma coisa que escrevendo:

$error_descriptions[1] = "Um erro fatal ocorreu";
$error_descriptions[2] = "O PHP emitiu um alarme";
$error_descriptions[8] = "Apenas um aviso informal";

porque E_ERROR é igual a 1, e assim por diante.

Então, como é possível que $foo[bar] funcione? Funciona porque bar, na sintaxe onde é utilizada é esperada como uma expressão constante. Entretanto, nesse caso não existe constante com o nome bar. O PHP, hoje, assume que você quer bar literalmente, como a string "bar", mas que você esqueceu de escrever os delimitadores.


Então, porque isso é tão mal?

Se em algum ponto do futuro, o time do PHP quiser acrescentar outra constante ou palavra chave, você terá problemas. Por exemplo, se você já não pode utilizar as palavras empty e default dessa maneira, desde que elas são palavras reservadas especiais.

Nota: Quando você liga error_reporting em E_ALL, você irá ver as notícias que o PHP gera quando um índice é utilizado sem ser definido (coloque a linha error_reporting(E_ALL); em seu script).

Nota: Com strings delimitadas por aspas, uma outra sintaxe é válida. Veja interpretação de variáveis em string para mais detalhes.


Exemplos

O tipo array do PHP é muito versátil, por isso temos aqui alguns exemplos para mostrar todo o poder dos arrays.

// isto
$a = array( 'color' => 'vermelha'
          , 'taste' => 'doce'
          , 'shape' => 'redonda'
          , 'name'  => 'maçã'
          ,            4        // a chave será 0
          );

// isto é equivalente a acima
$a['cor'] = 'vermelha';
$a['sabor'] = 'doce';
$a['formato'] = 'redonda';
$a['nome'] = 'maçã';
$a[]        = 4;        // a chave será 0

$b[] = 'a';
$b[] = 'b';
$b[] = 'c';
// o mesmo de array( 0 => 'a' , 1 => 'b' , 2 => 'c' ),
// ou simplesmente array('a', 'b', 'c')

Exemplo 7-4. Utilizando array()

// Array como (propriedade-)mapa
$map = array( 'versão'     => 4
            , 'OS'         => 'Linux'
            , 'lang'       => 'inglês'
            , 'short_tags' => true
            );
            
// apenas chaves numéricas
$array = array( 7
              , 8
              , 0
              , 156
              , -10
              );
// que é o mesmo que array( 0 => 7, 1 => 8, ...)

$switching = array(         10 // chave = 0
                  , 5    =>  6
                  , 3    =>  7
                  , 'a'  =>  4
                  ,         11 // chave = 6 (o índice máximo era 5)
                  , '8'  =>  2 // chave = 8 (inteiro!)
                  , '02' => 77 // chave = '02'
                  , 0    => 12 // o valor 10 será sobrescrito por 12
                  );

// array vazio
$empty = array();

Exemplo 7-5. Coleção

$cores = array('vermelho','azul','verde','amarelo');

foreach ( $cores as $cor ) {
    echo "Você gosta de $cor?\n";
}

/* saida:
Você gosta de vermelho?
Você gosta de azul?
Você gosta de verde?
Você gosta de amarelo?
*/

Note que atualmente não se pode mudar os valores de um array diretamente dentro de um loop. Superar essa limitação é possível da seguinte forma:

Exemplo 7-6. Coleção

foreach ($cores as $key => $cor) {
    // não funciona:
    //$cor = strtoupper($cor);

    //funciona:
    $cores[$key] = strtoupper($cor);
}
print_r($cores);

/* saida:
Array
(
    [0] => VERMELHO
    [1] => AZUL
    [2] => VERDE
    [3] => AMARELO
)
*/

Este exemplo cria um array na base 1.

Exemplo 7-7. Array baseado em 1

$primeiroquarto  = array(1 => 'Janeiro', 'Fevereiro', 'Março');
print_r($primeiroquarto);

/* saida:
Array
(
    [1] => 'Janeiro'
    [2] => 'Fevereiro'
    [3] => 'Março'
)
*/

Exemplo 7-8. Preenchendo um array real

// preenchendo um array com todos os itens de um diretório
$handle = opendir('.');
while ($file = readdir($handle))
{
    $files[] = $file;
}
closedir($handle);

Arrays são ordenados. Você pode mudar sua ordem utilizando vários funções de ordenação. Veja as funções de arrays para mais informações.

Exemplo 7-9. Ordenando arrays

sort($files);
print_r($files);

Porque o valor de um array pode ser qualquer coisa, isto pode ser outro array. Isto pode criar arrays recursivos e multidimensionais.

Exemplo 7-10. Arrays recursivos e multidimensionais

$fruits = array ( "frutas"  => array ( "a" => "laranja"
                                     , "b" => "banana"
                                     , "c" => "maçã"
                                     )
                , "numeros" => array ( 1
                                     , 2
                                     , 3
                                     , 4
                                     , 5
                                     , 6
                                     )
                , "buracos" => array (      "primeiro"
                                     , 5 => "segundo"
                                     ,      "terceiro"
                                     )
                );

Objetos

Inicialização de objetos

Para inicializar um objeto, você usa a instrução new, criando uma instância do objeto em uma variável.

<?php
class foo
{
    function do_foo()
    {
        echo "Fazendo foo.";
    }
}

$bar = new foo;
$bar->do_foo();
?>

Para uma explicação completa, consulte a seção Classes e Objetos.


Resource

Recurso é uma variável especial, mantendo uma referência de recurso externo. Recursos são criados e utilizados por funções especiais. Veja o apêndice para uma lista de todas essas funções e seus tipos correspondentes.

Nota: O tipo resource foi incluído no PHP 4


Liberando recursos

Através do sistema de contagem de referências introduzido com o engine da Zend no PHP 4, é automaticamente detectado quando um recurso não mais é referenciado (assim como o Java). Quando isto acontece, todos os recursos em uso por esse resource são liberados pelo coletor de lixo. Por essa razão, é raramente necessário liberar memória manualmente utilizando alguma função free_result.

Nota: Conexões persistentes de bancos são especiais. Eles não são destruídos pelo coletor de lixo. Veja também conexões permanentes.


NULL

O valor especial NULL representa que a variável não tem valor. NULL é o único valor possível do tipo NULL.

Nota: O tipo NULL foi incluído no PHP 4

A variável é considerada NULL se

  • ela foi assimilada com a constante NULL.

  • ela ainda não recebeu nenhum valor ainda.

  • ela foi apagada com unset().


Sintaxe

Há apenas um único valor do tipo NULL, e é a palavra (insensitiva ao caso) NULL.

$var = NULL;

Veja também is_null() e unset().


Pseudo-tipos utilizados nesta documentação

mixed

mixed indica que um parâmetro pode aceitar vários (mas não necessariamente todos) os tipos

gettype(), por exemplo, aceita todos os tipos do PHP, enquanto str_replace() somente aceita strings e arrays.


number

number indica que um parâmetro pode ser tanto um integer ou float.


callback

Some functions like call_user_function() or usort() accept user defined callback functions as a parameter. Callback functions can not only be simple functions but also object methods including static class methods.

A PHP function is simply passed by its name as a string. You can pass any builtin or user defined function with the exception of array(), echo(), empty(), eval(), exit(), isset(), list(), print() and unset().

A method of an instantiated object is passed as an array containing an object as the element with index 0 and a method name as the element with index 1.

Static class methods can also be passed without instantiating an object of that class by passing the class name instead of an object as the element with index 0.

Exemplo 7-11. Exemplo de funções callback

<?php

// Exemplo simples de callback
function foobar() {
    echo "Olá mundo!";
}
call_user_function("foobar");

// Exemplo de métodos callback
class foo {
  function bar() {
    echo "Olá mundo!";
  }
}

$foo = new foo;

call_user_function(array($foo, "bar")); // chamada do método do objeto

call_user_function(array("foo", "bar")); // chamada do método estático da classe

?>


Manipulação de tipos

O PHP não requer (ou suporta) a definição de tipo explicita na declaração de variáveis: o tipo de uma variável é determinado pelo contexto em que a variável é utilizada. Isto significa que, se você assimila um valor string para a variável var, var se torna uma string. Se você então assimila um valor inteiro para var, ela se torna um inteiro.

Um exemplo da conversão automática do PHP é o operador de adição '+'. Se qualquer um dos operadores for float, então todos os operadores são avaliados como floats, e o resultado será um float. De outra forma, se os operadores forem interpretados como inteiros então o resultado será um inteiro. Note que isso NÃO muda os tipos dos operadores: apenas muda em como esses operadores são avaliados.

$foo = "0";  // $foo é string (ASCII 48)

$foo += 2;   // $foo é agora um inteiro (2)
$foo = $foo + 1.3;  // $foo é agora um float (3.3)
$foo = 5 + "10 Little Piggies"; // $foo é inteiro (15)
$foo = 5 + "10 Small Pigs";     // $foo é inteiro (15)

Se os últimos dois exemplos lhe parecerem estranhos, veja Conversão de strings.

Se você deseja forçar uma variável para ser avaliada como um certo tipo, veja a seção Moldando o tipo (casting). Se você deseja mudar o tipo de uma variável, veja settype().

Se quiser testar qualquer um dos exemplo desta seção, você pode usar a função var_dump().

Nota: O comportamento de uma conversão automática para array é atualmente indefinida.

$a = "1";     // $a é uma string
$a[0] = "f";  // E com relação aos índices da string? O que acontece?

Desde que o PHP suporta indexação de strings através de offsets utilizando a mesma sintaxe da indexação de arrays, o exemplo acima nos deixa um problema: $a se tornou um array sendo o primeiro elemento "f", ou será que "f" se tornou o primeiro caracter da string $a ?

Por essa razão, como no PHP 3.0.12 e PHP 4.0b3-RC4, o resultado dessa conversão automática é considerada como indefinida. Correções, entretanto, estão sendo discutidas.


Moldando Tipos - Type Casting

A moldagem de tipos no PHP funciona como no C: o nome de um tipo desejado é escrito entre parênteses antes da variável em que se deseja a moldagem.

$foo = 10;   // $foo é um inteiro
$bar = (float) $foo;   // $bar é um número de ponto flutuante

As moldagens permitidas são:

  • (int), (integer) - molde para inteiro

  • (bool), (boolean) - molde para booleano

  • (float), (double), (real) - molde para número de ponto flutuante

  • (string) - molde para string

  • (array) - molde para array

  • (object) - molde para objeto

Nota: Em vez de moldar uma variável para string, você também pode circundar a variável entre aspas.

Note que tabulações e espaços são permitidos dentro dos parênteses, então o seguinte são funcionalmente equivalentes:

$foo = (int) $bar;
$foo = ( int ) $bar;

Pode não ser tão óbvio o que exatamente ocorre quando se molda entre certos tipos. Para mais informações, veja essas seções:

Quando moldando ou forçando a conversão de um array para string, o resultado será a palavra Array. Quando moldando ou forçando o tipo de um objeto para string, o resultado será a palavra Object.

Quando moldando de uma variável escalar ou string para um array, a variável se torna o primeiro elemento do array:

$var = 'ciao';
$arr = (array) $var;
echo $arr[0];  // outputs 'ciao'

Quando moldando de uma variável escalar ou string para um objeto, a variável se torna um atributo do objeto: o nome do atributo se chamará 'scalar':

$var = 'ciao';
$obj = (object) $var;
echo $obj->scalar;  // imprime 'ciao'


Capítulo 8. Variáveis

Introdução

As variáveis no PHP são representadas por um cifrão ($) seguido pelo nome da variável. Os nomes de variável no PHP fazem distinção entre maiúsculas e minúsculas.

Os nomes de variável seguem as mesmas regras como outros rótulos no PHP. Um nome de variável válido se inicia com uma letra ou sublinhado, seguido de qualquer número de letras, algarismos ou sublinhados. Em uma expressão regular isto poderia ser representado desta forma: '[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*'

Nota: Para nossos propósitos, as letras a-z, A-Z e os caracteres ASCII de 127 a 255 (0x7f-0xff).

<?php
$var = "Bob";
$Var = "Joe";
echo "$var, $Var";      // exibe "Bob, Joe"

$4site = 'not yet';     // inválido; começa com um número
$_4site = 'not yet';    // válido; começa com um sublinhado
$täyte = 'mansikka';    // válido; 'ä' é um caracter ASCII 228.
?>

No PHP 3, as variáveis são sempre atribuídas por valor. Isto significa que quando você atribui uma expressão a uma variável, o valor da expressão original é copiado integralmente para a variável de destino. Isto significa também que, após atribuir o valor de uma variável a outra, a alteração de uma destas variáveis não afetará a outra. Para maiores informações sobre este tipo de atribuição, veja o capítulo em Expressões.

O PHP 4 oferece um outro meio de atribuir valores a variáveis: a atribuição por referência. Isto significa que a nova variável simplesmente referencia (em outras palavras, "torna-se um apelido para" ou "aponta para") a variável original. Alterações na nova variável afetam a original e vice versa. Isto significa também que nenhuma cópia é realizada, de modo que a atribuição ocorre mais rapidamente. Entretanto, qualquer aumento de velocidade só será realmente notado em *loops* complexos ou em atribuições de grandes arrays ou objetos.

Para atribuir por referência, simplesmente adicione um e-comercial (&) na frente do nome da variável que estiver sendo atribuída (variável de origem) Por exemplo, o trecho de código abaixo imprime 'My name is Bob' duas vezes:

<?php
$foo = 'Bob';              // Atribui o valor 'Bob' a variável $foo
$bar = &$foo;              // Referecia $foo através de $bar.
$bar = "My name is $bar";  // Altera $bar...
echo $bar;
echo $foo;                 // $foo é alterada também.
?>

Uma observação importante a se fazer: somente variáveis nomeadas podem ser atribuídas por referência.

<?php
$foo = 25;
$bar = &$foo;      // Esta atribuição é válida.
$bar = &(24 * 7);  // Inválido; referencia uma expressão sem nome.

function test()
{
   return 25;
}

$bar = &test();    // Inválido.
?>


Variáveis Predefinidas

O PHP oferece um grande número de variáveis predefinidas para qualquer script que ele execute. Muitas destas variáveis, entretanto, não podem ser completamente documentadas uma vez dependem de diversos fatores, como o servidor no qual scripts são executados, a versão e configuração deste servidor e outros. Algumas destas variáveis não estarão disponíveis quando o PHP for executado na linha de comando. Para uma lista destas variáveis, veja a seção Variáveis reservadas.

Atenção

No PHP 4.2.0 e posteriores, o valor default da diretiva register_globals é off. Esta é a maior modificação no PHP. Tendo register_globals off afeta o conjunto de variáveis predefinidas disponíveis no escopo global. POr exemplo, para ler DOCUMENT_ROOT você usará $_SERVER['DOCUMENT_ROOT'] em vez de $DOCUMENT_ROOT, ou $_GET['id'] da URL http://www.example.com/test.php?id=3 em vez de $id, or $_ENV['HOME'] em vez de $HOME.

Para informações relacionadas desta modificação, veja detalhes da diretiva register_globals, no capítulo de segurança em Usando register_globals , assim como o detalhamento de lançamento das versões do PHP 4.1.0 e 4.2.0.

Utilizar as Variáveis Predefinidas do PHP, como os arrays superglobais, é muito mais preferível.

Desde a versão 4.1.0, o PHP fornece um conjunto adicional de arrays predefinidos contendo as variáveis do servidor web (se aplicável), as variáveis ambiente e as entradas do usuário. Esses novos arrays são especiais pelo motivo que são automaticamente globais (significa que são automaticamente disponíveis em qualquer escopo. Por causa disso, são também conhecidas como 'autoglobais' ou 'superglobais' (Não há um mecanismo no PHP para superglobais definidas pelo usuário) As superglobais são listadas abaixo. Entretanto, para uma explicação de seu conteúdo e detalhes sobre as variáveis predefinidas do PHP e sua natureza, veja a seção Variáveis Predefinidas. Veja também que todas as outras variáveis predefinidas antigas ($HTTP_*_VARS) ainda existem.

Se todos os indicadores não estiverem configurados no variables_order, seus arrays superglobais predefinidos respectivos estarão vazios.

Superglobais do PHP

$GLOBALS

Contém um referência para todas as variáveis que são atualmente disponíveis dentro do escopo global do script. As chaves desse array são os nomes das variáveis globais. $GLOBALS existe desde o PHP 3.

$_SERVER

Variáveis criadas pelo servidor web ou diretamente relacionadas ao ambiente de execução do script atual. Análogo ao antigo array $HTTP_SERVER_VARS (que ainda continua disponível, mas em decadência).

$_GET

Variáveis postadas para o script via método HTTP GET. Análogo ao antigo array $HTTP_GET_VARS (que ainda continua disponível, mas em decadência).

$_POST

Variáveis postadas para o script via método HTTP POST. Análogo ao antigo array $HTTP_POST_VARS (que ainda continua disponível, mas em decadência).

$_COOKIE

Variáveis postadas para o script via cookies HTTP. Análogo ao antigo array $HTTP_COOKIE_VARS (que ainda continua disponível, mas em decadência).

$_FILES

Variáveis postadas para o script via transferência de arquivos HTTP. Análogo ao antigo array $HTTP_POST_FILES (que ainda continua disponível, mas em decadência). Veja uploads via método POST para maiores informações.

$_ENV

Variáveis disponíveis no script do ambiente de execução. Análogo ao antigo array $HTTP_ENV_VARS (que ainda continua disponível, mas em decadência).

$_REQUEST

Variáveis postadas para o script por todas os mecanismos de input, e que não podem ter seu conteúdo garantido de qualquer forma. A presença e a ordem de inclusão das variáveis nesse array é definida de acordo com a diretiva de configuração variables_order. Este array não tem um equivalente nas versões anteriores do PHP 4.1.0. Veja também import_request_variables().

Nota: Quando executando na linha de comando , isto não inclui as entradas argv e argc; elas estão presentes no array $_SERVER.

$_SESSION

Variáveis que estão atualmente registradas na sessão do script. Análogo ao antigo array $HTTP_SESSION_VARS (que ainda continua disponível, mas em decadência). Veja a sessão funções de manipulação de Sessões para maiores informações.


Escopo de variáveis

O escopo de uma variável é o contexto onde ela foi definida. A maior parte das variáveis do PHP tem somente escopo local. Este escopo local inclui os arquivos incluídos. Por exemplo:

<?php
$a = 1;
include "b.inc";
?>

Aqui a variável $a estará disponível no script incluído b.inc. Entretanto, com as funções definidas pelo usuário, um escopo local é introduzido. Quaisquer variáveis utilizadas dento da função é por default limitada dentro do escopo local da função. Por exemplo:

<?php
$a = 1; /* escopo global */

function Teste()
{
    echo $a; /* referencia uma variável do escopo local (não definida) */
}

Test();
?>

Este script não produz nenhuma saída porque a instrução echo() refere-se a uma versão local da variável $a, e ela não tem nenhum valor assimilado nesse escopo. Essa é uma pequena diferença da linguagem C quando variáveis globais são automaticamente disponíveis para funções sem sobreescrever uma eventual definição local. Isto causa problemas quando as pessoas mudam inadivertidamente uma variável global. No PHP, as variáveis globais precisam ser declaradas globais dentro de uma função se ela vai ser utilizada naquela função. Um exemplo:

<?php
$a = 1;
$b = 2;

function Soma()
{
    global $a, $b;

    $b = $a + $b;
}

Soma();
echo $b;
?>

O script acima imprimirá "3". Declarando $a e $b globais na função, todas as referências a essas variáveis referem-se a versão global. Não há um limite para o número de variáveis globais que podem ser manipuladas por uma função.

Uma segunda maneira de acessar variáveis do escopo global é utilizando o array especial $GLOBALS definido pelo PHP. O exemplo anterior poderia ser rescrito como:

<?php
$a = 1;
$b = 2;

function Soma()
{
    $GLOBALS["b"] = $GLOBALS["a"] + $GLOBALS["b"];
}

Soma();
echo $b;
?>

O array $GLOBALS é um array associativo onde o nome da variável global é a chave do array e o seu conteúdo da variável como o valor do elemento do array. Veja que $GLOBALS existe em qualquer escopo, isto porque $GLOBALS é uma superglobal. Segue um exemplo demonstrando o poder das superglobais:

<?php
function test_global()
{
    // A maioria das variaveis predefinidas nao sao 'super' e requerem
    // 'global' para serem disponiveis para funcoes em qualquer escopo.
    global $HTTP_POST_VARS;

    print $HTTP_POST_VARS['name'];

    // Superglobais são disponiveis em qualquer escopo e
    // nao precisam de 'global'. Superglobais existem
    // desde o PHP 4.1.0
    print $_POST['name'];
}
?>

Outro recurso importante do escopo de variáveis é a variável estática. Uma variável estática existe somente no escopo local da função, mas ela não perde seu valor quando o nível de execução do programa deixa o escopo. Considere o seguinte exemplo:

<?php
function Teste ()
{
    $a = 0;
    echo $a;
    $a++;
}
?>

Essa função é inútil partindo de que cada vez que ela é chamada, ela coloca em $a o valor 0 e imprime "0". A instrução $a++ , que aumenta o valor da variável não tem sentido desde que a função sai e a variável $a desaparece. Para faze-la mais útil como contadora sem deixar de perder o sua conta atual, a variável $a é declarada como estática:

<?php
function Teste()
{
    static $a = 0;
    echo $a;
    $a++;
}
?>

Agora, cada vez que a função Teste() for chamada ele imprimirá o valor de $a e o incrementará.

Variáveis estáticas fornecem uma solução ideal para funções recursivas. Uma função recursiva é aquela se chama a si mesma. Cuidados especiais precisam ser tomados quando escrevendo funções recursivas porque é possível que ela continue na recursão indefinidamente. Você tem de ter certeza que há uma maneira segura de terminar a recursão. A seguinte função recursiva conta até 10, utilizando a variável estática $count para saber quando parar:

<?php
function Teste()
{
    static $count = 0;

    $count++;
    echo $count;
    if ($count < 10) {
        Test ();
    }
    $count--;
}
?>

O Zend Engine 1, base do PHP4, implementa os modificadores static e global para variáveis em termos de referência. Por exemplo, uma variável global importada dentro do escopo de uma função com a instrução global atualmente cria uma referência para a variável global. Isto pode causar comportamentos impresíveis para os seguintes casos:

<?php
function test_global_ref() {
    global $obj;
    $obj = &new stdclass;
}

function test_global_noref() {
    global $obj;
    $obj = new stdclass;
}

test_global_ref();
var_dump($obj);
test_global_noref();
var_dump($obj);
?>

Executando esse exemplo você terá as seguites saídas:

NULL
object(stdClass)(0) {
}

Uma situação similar se aplica ao modificador static. Referências não são armazenadas estaticamente:

<?php
function &get_instance_ref() {
    static $obj;

    echo "Objeto estatico: ";
    var_dump($obj);
    if (!isset($obj)) {
        // Assimila uma referencia a variavel estatica
        $obj = &new stdclass;
    }
    $obj->property++;
    return $obj;
}

function &get_instance_noref() {
    static $obj;

    echo "Objeto estatico: ";
    var_dump($obj);
    if (!isset($obj)) {
        // Assimila o objeto para a veriavel estatica
        $obj = new stdclass;
    }
    $obj->property++;
    return $obj;
}

$obj1 = get_instance_ref();
$still_obj1 = get_instance_ref();
echo "\n";
$obj2 = get_instance_noref();
$still_obj2 = get_instance_noref();
?>

Executando esse exemplo você terá as seguites saídas:

Objeto estatico: NULL
Objeto estatico: NULL

Objeto estatico: NULL
Objeto estatico: object(stdClass)(1) {
  ["property"]=>
  int(1)
}

Este exemplo demonstra que quando assimilando uma referência para uma variável estática, ela não se lembra quando você chama a função &get_instance_ref() uma segunda vez.


Variáveis variáveis

As vezes é conveniente poder trabalhar com variáveis variáveis. Isto é, nomes de variáveis que pode ser criadas e utilizadas dinamicamente. Uma variável normal é criada numa instrução como:

<?php
$a = "hello";
?>

Uma variável variável pega o valor de uma variável e a trata como o nome de uma variável. No exemplo acima, hello pode ser utilizada como o nome de uma variável utilizando dois sinais de cifrão:

<?php
$$a = "world";
?>

Neste ponto, duas variáveis foram definidas e preservadas na árvore de símbolos do PHP: $a contendo "hello" e $hello contendo "world". Da mesma forma, esta instrução:

<?php
echo "$a ${$a}";
?>

produz a mesma saida que:

<?php
echo "$a $hello";
?>

no caso: hello world.

Para poder utilizar variáveis variáveis com arrays, você precisa resolver um problema de ambigüidade. Assim, se você escrever $$a[1] então o interpretador pode entender que você quer usar $a[1] como uma variável ou que você quer usar $$a como uma variável e [1] como o índice dessa variável. A sintaxe para resolver essa ambigüidade é ${$a[1]} para o primeiro caso e ${$a}[1] para o segundo.

Atenção

Verifique que variáveis variáveis não podem ser utilizadas com os novos arrays superglobais. Isto significa que você não pode fazer coisas como ${$_GET}. Se você está procurando uma maneira de manipular as superglobais como as antigas HTTP_*_VARS, você deve tentar referenciá-las.


Variáveis externas ao PHP

Formulários HTML (GET and POST)

Quando um formulário é submetido para um script PHP, qualquer variável do formulário será automaticamente disponível para o script. Há várias maneiras de acessar estas informações, por exemplo:

Exemplo 8-1. Um formulário HTML simples

<form action="foo.php" method="post">
    Nome:  <input type="text" name="username"><br>
    Email: <input type="text" name="email"><br>
    <input type="submit" name="submit" value="Me aperte!">
</form>

Dependendo da configuração local e suas preferencias pessoais, essas são as vias pela qual você pode acessar os dados de seus formulários:

Exemplo 8-2. Acessando dados de um formulário HTML via POST

<?php
// Disponível desde o PHP 4.1.0

   print $_POST['username'];
   print $_REQUEST['username'];

   import_request_variables('p', 'p_');
   print $p_username;

// Disponível deste o PHP 3.

   print $HTTP_POST_VARS['username'];

// Disponível se a diretiva register_globals = on.
// Desde o PHP 4.2.0 o valor default de register_globals é off
// Usar/manter esse método é preferível.

   print $username;
?>

Utilizar um formulário GET é similar, exceto que você use a variável GET predefinida. O metodo GET obtem os dados da QUERY_STRING (a informação depois do '?' numa URL). Então, por exemplo, http://www.example.com/test.php?id=3 contém os dados GET que serão acessíveis com $_GET['id']. Veja também $_REQUEST e import_request_variables().

Nota: Arrays superglobais, como $_POST e $_GET, estão disponíveis desde o PHP 4.1.0.

Como explicado, antes do PHP 4.2.0 o valor default de register_globals era on. E no PHP ele era sempre on. A comunidade PHP está encorajando todos a não alterarem essa diretiva, assumindo-a sempre como off e codificando em conformidade com isso.

Nota: A diretiva de configuração magic_quotes_gpc afeta os valores de GET, POST e Cookies. Se estiver ativada, o valor (It's "PHP!") se tornará automaticamente (It\'s \"PHP!\"). Escaping é necessário para inserção em bancos de dados. Veja também addslashes(), stripslashes() e magic_quotes_sybase.

O PHP entende arrays no contexto de variáveis de formulários (veja o FAQ relacionado). Você pode, por exemplo, agrupar variáveis relacionadas juntas, ou usar esse recurso para receber valores de um campo de seleção múltipla. Por exemplo, podemos ter um formulario que manda informações para si mesmo até um comando submetido para mostrar todos os dados.

Exemplo 8-3. Variáveis de formulários mais complexos

<?php
if ($HTTP_POST_VARS['action'] == 'submitted') {
    print '<pre>';

    print_r($HTTP_POST_VARS);
    print '<a href="'. $HTTP_SERVER_VARS['PHP_SELF'] .'">De novo</a>';

    print '</pre>';
} else {
?>
<form action="<?php echo $HTTP_SERVER_VARS['PHP_SELF']; ?>" method="post">
    Nome:  <input type="text" name="personal[name]"><br>
    Email: <input type="text" name="personal[email]"><br>
    Cerveja: <br>
    <select multiple name="beer[]">
        <option value="antartica">Antartica</option>
        <option value="brahma">Brahma</option>
        <option value="skol">Skol</option>
    </select><br>
    <input type="hidden" name="action" value="submitted">
    <input type="submit" name="submit" value="Enviar dados!">
</form>
<?php
}
?>

No PHP 3, os arrays variáveis de formulários eram limitados a uma dimensão. No PHP 4, essa restrição não existe mais.


Nomes de variáveis SUBMIT IMAGE

Quando submetendo um formulário, é possível de se utilizar imagens ao invés do botão de submit padrão com uma tag do tipo:

<input type="image" src="image.gif" name="sub">

Quando o usuário clica em algum lugar da imagem, o formulário que o acompanha é transmitido para o servidor com duas variáveis adicionais, sub_x e sub_y. Eles contém a coordenadas do clique do usuário na imagem. Os mais experientes percebem que os atuais nomes dessas variáveis enviados pelo browser contém um ponto ao invés de um sublinhado, mas o PHP converte o ponto para um sublinhado automaticamente.


Cookies HTTP

O PHP suporta transparentemente cookies HTTP como os definidos pela especificação da Netscape. Cookies são um mecanismo de armazenamento de dados no browser cliente e permite o rastreamento ou identificação do retorno de usuários. Você pode criar cookies com a função setcookie(). Cookies são parte do header HTTP, então, a função setcookie() precisa ser chamada antes de qualquer saída ser enviada ao browser. Esta é a mesma restrição da função header(). Dados de cookies são disponíveis nos arrays de dados de cookies apropriados, como $_COOKIE, $HTTP_COOKIE_VARS como também em $_REQUEST. Veja o manual de setcookie() para mais detalhes e exemplos.

Se você deseja assimilar vários valores para uma única variável cookie, você pode fazer dele um array:

<?php
  setcookie("MeuCookie[foo]", "Testando 1", time()+3600);
  setcookie("MeuCookie[bar]", "Testando 2", time()+3600);
?>

Isso irá criar dois cookies separados enquanto MeuCookie será um único array em seu script. Se você quiser colocar em apenas um cookie vários valores, considere utilizar serialize() ou explode() nos valores primeiro.

Note que um cookie substituirá um anterior com o mesmo nome em seu browser mesmo se o nome ou o caminho for diferente. Então, para uma aplicação de carrinho de compras em que você quer ter um contador e repassá-lo:

Exemplo 8-4. Exemplo setcookie()

<?php
$count++;
setcookie("count", $count, time()+3600);
setcookie("Cart[$count]", $item, time()+3600);
?>

Pontos em nomes de variáveis postadas

Normalmente o PHP não altera o nome de variáveis quando elas são passadas para o script. Entretanto, é necessário notar que o ponto (ponto final) não é um caracter válido no nomes de variáveis do PHP. Para ilustrar, veja o seguinte exemplo:
<?php
$varname.ext;  /* nome de variável inválido */
?>
Dessa forma, o interpretador entende isso como uma variável nomeada $varname, seguida do operador de concatenação de strings, seguida de um identificador (uma string não delimitada que não bate com nenhuma palavra chave ou reservada) 'ext'. Obviamente, isso não tem os resultados pretendidos.

Nessa situação, é importante saber que o PHP automaticamente substituirá qualquer ponto nos nomes de variáveis recebidas com sublinhados.


Determinando o tipo das variáveis

Porque o PHP determina os tipos de variáveis e faz conversões (geralmente) quando necessárias, nem sempre é óbvio o tipo de uma variável tem em todos os momentos. O PHP incluí várias funções que permitem determinar qual o tipo de uma variável, por exemplo: gettype(), is_array(), is_float(), is_int(), is_object(), e is_string(). Veja também o capítulo Tipos.


Capítulo 9. Constantes

Uma constante é um identificador (nome) para um valor simples. Como o nome sugere, esse valor não pode mudar durante a execução do script (as 'constantes mágicas' __FILE__ e __LINE__ parecem ser uma exceção a essa regra, mas elas não são realmente constantes). As constantes são sensíveis ao caso por padrão. Por convenção, o nomes de constantes são sempre em maiúsculas.

O nome de uma constante tem as mesmas regras de qualquer identificador no PHP. Um nome de constante válida começa com uma letra ou sublinhado, seguido por qualquer número de letras, números ou sublinhados. Em expressões regulares, ela pode ser representada por: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*

Nota: Para nossos exemplos, as letras a-z, A-Z e os caracteres ASCII do 127 ao 255 (0x7f-0xff).

O escopo de uma constante é global. Você pode acessá-la em qualquer lugar em seu script sem se preocupar com seus escopo.


Sintaxe

Você pode definir uma constante utilizando-se da função define(). Quando uma constante é definida, ela não pode ser mais modificada ou anulada.

Somente dados escalares (boolean, integer, float e string) pode ser colocados em constantes.

Você pode obter o valor de uma constante simplismente especificando seu nome. Diferentemente de variáveis, você não pode prefixar uma constante com um sinal de $. Você também pode utilizar a função constant() para ler o valor de uma constante, se você precisar obter seu valor dinamicamente. Utilize get_defined_constants() para obter a lista de todas as constantes definidas.

Nota: As constantes e variáveis (globais) estão em espaços de nomes diferentes. Isto implica, por exemplo, que TRUE e $TRUE são geralmente diferentes.

Se você usar uma constante indefinida, o PHP assume o nome da constante como seu próprio valor. Uma notice será informada quando isso acontecer. Use a função defined() se você precisar saber se uma constante está definida ou não.

Estas são as diferenças entre constantes e variáveis:

  • Constantes não podem ter um sinal de cifrão ($) antes delas;

  • Constantes só podem ser definidas utilizando a função define(), e não por simples assimilação;

  • Constantes podem ser definidas e acessadas de qualquer lugar sem que a regras de escopo de variáveis seja aplicadas;

  • Constantes não podem ser redefinidas ou eliminadas depois que elas são criadas; e

  • Constantes só podem conter valores escalares.

Exemplo 9-1. Definindo Constantes

<?php
define("CONSTANT", "Hello world.");
echo CONSTANT; // imprime "Hello world."
echo Constant; // imprime "Constant" e gera um alerta notice.
?>


Constantes Predefinidas

O PHP fornece um grande número de constantes predefinidas para qualquer script que ele execute. A maioria dessas constantes, entretanto, são criadas por várias extensões, e somente estarão presentes quando essas extensões estiverem disponíveis, por carregamento dinamico ou por compilação direta.

A lista de constantes predefinidas está disponível na seção Constantes Predefinidas.


Capítulo 10. Expressões

Expressões são as peças de construção mais importantes do PHP. No PHP, quase tudo o que você escreve são expressões. A maneira mais simples e ainda mais precisa de definir uma expressão é "tudo o que tem um valor".

As formas mais básicas de expressões são constantes e variáveis. Quando você digita "$a = 5", você está atribuindo '5' para $a. '5', obviamente, tem o valor 5, ou, em outras palavras, '5' é uma expressão com o valor 5 (neste caso, '5' é uma constante inteira).

Depois desta atribuição, você pode esperar que o valor de $a seja 5 também, assim se você escrever $b = $a, você pode esperar que $b se comporte da mesma forma que se você escrevesse $b = 5. Em outras palavras, $a é uma expressão com valor 5 também. Se tudo funcionou bem, isto é exatamente o que acontecerá.

Exemplos ligeiramente mais complexos para expressões são as funções. Por exemplo, considere a seguinte função:

function foo ()
{
    return 5;
}

Assumindo que você está familiarizado com o conceito de funções (se não estiver, dê uma olhada no capítulo sobre funções), você pode assumir que digitar $c = foo() é essencialmente a mesma coisa que escrever $c = 5, e você está certo. Funções são expressões com o valor igual ao seu valor de retorno. Como foo() retorna 5, o valor da expressão 'foo()' é 5. Geralmente, as funções não retornam apenas um valor estático, mas computam algo.

Obviamente, os valores em PHP não têm que ser inteiros, e muito freqüentemente eles não são. O PHP suporta três tipos de valores escalares: valores inteiros, valores de ponto flutuante e valores de string (valores escalares são valores que você não pode quebrar em pedaços menores, diferente de matrizes, por exemplo). O PHP também suporta dois tipos compostos (não-escalares): matrizes e objetos. Cada um destes tipos de valor podem ser atribuídos a variáveis ou retornadas de funções.

Até agora, os usuários de PHP/FI 2 não sentiriam qualquer mudança. Porém, o PHP traz expressões bem mais novas, da mesma forma que muitas outras linguagens. O PHP é uma linguagem orientada a expressões, no sentido de que quase tudo são expressões. Considere o exemplo com o qual já lidamos, '$a = 5'. É fácil ver que há dois valores envolvidos aqui, o valor da constante inteira '5', e o valor de $a que está sendo atualizado para 5 também. Mas a verdade é que há um valor adicional envolvido, e que é o próprio valor da atribuição. A própria atribuição é avaliada com o valor atribuído, neste caso 5. Na prática, significa que '$a = 5', independente do que faça, é uma expressão com o valor 5. Portanto, escrever algo como '$b = ($a = 5)' é como escrever '$a = 5; $b = 5;' (um ponto-e-vírgula marca o fim do comando). Como atribuições são analisadas da direita para a esquerda, você também pode escrever '$b = $a = 5'.

Outro bom exemplo de orientação de expressão é o pré e o pós-incremento e decremento. Usuários de PHP/FI 2 e muitas outras linguagens podem estar familiarizados com a notação de variável++ e variável--. Estes são os operadores de incremento e decremento. No PHP/FI 2, o comando '$a++' não tem valor (não é uma expressão), e portanto você não pode atribuir desta forma ou usá-la de jeito nenhum. O PHP evoluiu a capacidade de incremento/decremento criando estas expressões também, como em C. Em PHP, como em C, há dois tipos de incremento - pré-incremento e pós-incremento. Tanto o pré-incremento quanto o pós-incremento, essencialmente, incrementam variáveis, e o efeito sobre a variável é idêntico. A diferença é com o valor da expressão de incremento. O pré-incremento, que é escrito '++$variavel', é avaliado como o valor de incremento (o PHP incrementa a variável antes de ler seu valor, por isso o nome pré-incremento). O pós-incremento, que é escrito '$variavel++' é avaliado como o valor original da variável, antes de ser incrementada (o PHP incrementa a variável depois de ler seu valor, por isso o nome 'pós-incremento').

Um tipo muito comum de expressão são expressões de comparação. Estas expressões são avaliadas como 0 ou 1, significando FALSE ou TRUE, respectivamente. O PHP suporta > (maior que), >= (maior ou igual), == (igual), != (diferente), < (menor que) e <=(menor ou igual). Estas expressões são usadas mais freqüentemente dentro de instruções condicionais, como em comandos if.

O último exemplo de expressões com que nós vamos lidar aqui são as expressões combinadas operador-atribuição. Você já sabe que se você quer incrementar $a de 1, você só precisa escrever '$a++' ou '++$a'. Mas e se você quiser somar mais que um a ele, por exemplo 3? Você poderia escrever '$a++' várias vezes, mas esta obviamente não é uma forma muito eficiente ou confortável. Uma prática muito mais comum é escrever '$a = $a + 3'. '$a + 3' é avaliada como o valor de $a mais 3, e é atribuído de volta a $a, que resulta em incrementar $a de 3. Em PHP, como em várias outras linguagens como o C, você pode escrever isto de uma forma mais curta, que com o tempo se torna mais limpa e rápida de se entender, também. Somar 3 ao valor corrente de $a pode ser escrito '$a +=3'. Isto significa exatamente "pegue o valor de $a, some 3 a ele, e atribua-o de volta a $a." Além de ser mais curto e mais limpo, isto também resulta em execução mais rápida. O valor de '$a += 3', como o valor de uma atribuição regular, é o valor atribuído. Note que NÃO é 3, mas o valor combinado de $a mais 3 (este é o valor que é atribuído a $a). Qualquer operador de dois parâmetros pode ser usado neste modo operador-atribuição, por exemplo '$a -= 5' (subtrai 5 do valor de $a), '$b *= 7' (multiplica o valor de $b por 7), etc.

Há mais uma expressão que podem parecer estranha se você não a viu em outras linguagens, o operador condicional ternário:

$primeira ? $segunda : $terceira

Se o valor da primeira sub-expressão é verdadeiro (TRUE, não-zero), então a segunda sub-expressão é avaliada, e este é o resultado da expressão condicional. Caso contrário, a terceira sub-expressão é avaliada e este é o valor.

O seguinte exemplo deve ajudá-lo a entender um pouco melhor pré e pós-incremento e expressões em geral:

function double($i)
{
    return $i*2;
}
$b = $a = 5;        /* atribui o valor cinco às variáveis $a e $b */
$c = $a++;          /* pós-incremento, atribui o valor original de $a
                       (5) para $c */
$e = $d = ++$b;     /* pré-incremento, atribui o valor incrementado de
                       $b (6) a $d e $e */

/* neste ponto, tanto $d quanto $e são iguais a 6 */

$f = double($d++);  /* atribui o dobro do valor de $d <emphasis>antes</emphasis>
                       do incremento, 2*6 = 12 a $f */
$g = double(++$e);  /* atribui o dobro do valor de $e <emphasis>depois</emphasis>
                       do incremento, 2*7 = 14 a $g */
$h = $g += 10;      /* primeiro, $g é incrementado de 10 e termina com o valor
                       24. o valor da atribuição (24) é então atribuído
                       a $h, e $h termina com o valor 24 também. */

No começo do capítulo, nós dissemos que descreveríamos os vários tipos de comandos, e como prometido, expressões podem ser comandos. Porém, nem toda expressão é um comando. Neste caso, um comando tem a forma 'expr' ';', ou seja, uma expressão seguida de ponto-e-vírgula. E '$b=$a=5;', $a=5 é uma expressão válida, mas não é um comando por si só. '$b=$a=5;' porém é um comando válido.

Uma última coisa que vale mencionar é o valor-verdade de expressões. Em muitos eventos, principalmente em instruções condicionais e loops, você não está interessado no valor específico da expressão, mas somente se ela significa TRUE ou FALSE (o PHP não tem um tipo booleano dedicado). As constantes TRUE e FALSE (insensitivas ao caso) são seus dois valores booleanos possíveis. As vezes uma expressão é automaticamente convertida para um booleano. Veja a seção sobre type-casting para detalhes de como isso é feito.

O PHP fornece uma implementação completa e poderosa de expressões, e a completa documentação dela vai além do escopo deste manual. Os exemplos acima devem dar a você uma boa idéia sobre o que são as expressões e como você pode construir expressões úteis. Através do restante do manual nós escreveremos expr ou expressao para indicar qualquer expressão PHP válida.


Capítulo 11. Operadores


Precedência de Operadores

A precedência de um operador especifica quem tem mais prioridade quando há duas delas juntas. Por exemplo, na expressão, 1 + 5 * 3, a resposta é 16 e não 18 porque o operador de multiplicação ("*") tem prioridade de precedência que o operador de adição ("+"). Parênteses podem ser utilizados para forçar a precedência, se necessário. Assim, (1 + 5) * 3 é avaliado como 18.

A tabela seguinte mostra a precedência dos operadores, da menor precedência para a maior.

Tabela 11-1. Precedência dos operadores

Associação Operador
esquerda ,
esquerda or
esquerda xor
esquerda and
direita print
esquerda = += -= *= /= .= %= &= |= ^= ~= <<= >>=
esquerda ? :
esquerda ||
esquerda &&
esquerda |
esquerda ^
esquerda &
não associativo == != === !==
não associativo < <= > >=
esquerda << >>
esquerda + - .
esquerda * / %
direita ! ~ ++ -- (int) (float) (string) (array) (object) @
direita [
não associativo new


Operadores Aritméticos

Lembra-se da aritmética básica da escola? Estes operadores funcionam exatamente como aqueles.

Tabela 11-2. Operadores Aritméticos

Exemplo Nome Resultado
$a + $b Adição Soma de $a e $b.
$a - $b Subtração Diferença entre $a e $b.
$a * $b Multiplicação Produto de $a e $b.
$a / $b Divisão Quociente de $a por $b.
$a % $b Módulo Resto de $a dividido por $b.

O operador de divisão ("/") sempre retorna um valor com ponto flutuante, mesmo que os dois operandos sejam inteiros (ou strings que sejam convetidos para inteiros).


Operadores de Atribuição

O operador básico de atribuição é "=". A sua primeira inclinação deve ser a de pensar nisto como "é igual". Não. Isto quer dizer, na verdade, que o operando da esquerda recebe o valor da expressão da direita (ou seja, "é configurado para").

O valor de uma expressão de atribuição é o valor atribuído. Ou seja, o valor de "$a = 3" é 3. Isto permite que você faça alguns truques:

$a = ($b = 4) + 5; // $a é igual a 9 agora e $b foi configurado como 4.

Além do operador básico de atribuição, há "operadores combinados" para todos os operadores binários, aritméticos e de string, que permitem a você pegar um valor de uma expressão e então usar seu próprio valor para o resultado daquela expressão. Por exemplo:

$a = 3;
$a += 5; // configura $a para 8, como se disséssemos: $a = $a + 5;
$b = "Bom ";
$b .= "Dia!"; // configura $b para "Bom Dia!", como em $b = $b . "Dia!";

Note que a atribuição copia a variável original para a nova (atribuição por valor), assim a mudança de uma não afeta a outra. Isto pode ter relevância se você precisa copiar algo como uma grande matriz dentro de um loop longo. O PHP 4 suporta atribuições por referência, usando a sintaxe $var = &$outra_var;, mas isto não é possível no PHP3. 'Atribuição por referência' significa que ambas as variáveis acabam apontando para os mesmos dados, e nada é copiado para lugar nenhum. Para aprender mais sobre referências, leia Referências explicadas.


Operador Bit-a-bit

Operadores bit-a-bit permitem que você acione ou desligue bits específicos dentro de um inteiro. Se ambos os parâmetros da esquerda e da direita forem strings, esses operadores irão trabalhar nos caracteres dessa string.

<?php
    echo 12 ^ 9; // Imprime '5'

    echo "12" ^ "9"; // Imprime o caracter de volta (backspace - ASCII 8)
                     // ('1' (ASCII 49)) ^ ('9' (ASCII 57)) = 8

    echo "hallo" ^ "hello"; // Imprime os valores ASCII 0 4 0 0 0
                            // 'a' ^ 'e' = 4
?>

Tabela 11-3. Operadores Bit-a-bit

Exemplo Nome Resultado
$a & $b E Os bits que estão ativos tanto em $a quanto em $b são ativados.
$a | $b OU Os bits que estão ativos em $a ou em $b são ativados.
$a ^ $b XOR Os bits que estão ativos em $a ou em $b, mas não em ambos, são ativados.
~ $a NÃO Os bits que estão ativos em $a não são ativados, e vice-versa.
$a << $b Deslocamento à esquerda Desloca os bits de $a $b passos para a esquerda (cada passo significa "multiplica por dois")
$a >> $b Deslocamento à direita Desloca os bits de $a $b passos para a direita (cada passo significa "divide por dois")

Operadores de Comparação

Operadores de comparação, como os seus nomes implicam, permitem que você compare dois valores.

Tabela 11-4. Operadores de comparação

Exemplo Nome Resultado
$a == $b Igual Verdadeiro (TRUE) se $a é igual a $b.
$a === $b Idêntico Verdadeiro (TRUE) se $a é igual a $b, e eles são do mesmo tipo (somente para PHP4).
$a != $b Diferente Verdadeiro se $a não é igual a $b.
$a <> $b Diferente Verdadeiro se $a não é igual a $b.
$a !== $b Não idêntico Verdadeiro de $a não é igual a $b, ou eles não são do mesmo tipo (somente para o PHP4).
$a < $b Menor que Verdadeiro se $a é estritamente menor que $b.
$a > $b Maior que Verdadeiro se $a é estritamente maior que $b.
$a <= $b Menor ou igual Verdadeiro se $a é menor ou igual a $b.
$a >= $b Maior ou igual Verdadeiro se $a é maior ou igual a $b.

Outro operador condicional é o operador "?:" (ou trinário), que opera como no C e em muitas outras linguagens.

(expr1) ? (expr2) : (expr3);

Esta expressão avalia para expr2 se expr1 é avaliada como TRUE, ou expr3 se expr1 é avaliada como FALSE.


Operadores de controle de erro

O PHP suporta um operador de controle de erro: o sinal 'arroba' (@). Quando ele precede uma expressão em PHP, qualquer mensagem de erro que possa ser gerada por aquela expressão será ignorada.

Se o recurso track_errors estiver habilitado, qualquer mensagem de erro gerada pela expressão será gravada na variável global $php_errormsg. Esta variável será sobrescrita em cada erro, assim verifique-a constantemente se você quiser usá-la.

<?php
/* Erro de arquivo intencional */
$my_file = @file ('arquivo_nao_existente') ou
    die ("Falha abrindo arquivo: '$php_errormsg'");

// Isto funciona para qualquer expressão, não apenas para funções:
$value = @$cache[$key];
// você não receberá nenhum aviso se a chave $key não existir.

?>

Nota: O operador @ funciona somente em expressões. Uma regra simples para lembrar disso: se você pode pegar o valor de alguma coisa, você pode prefixar isso com o @. Assim, você pode prefixar chamadas de variáveis, funções e include()s, constantes e afins. Você não pode prefixar definições de funções ou classe, estruturas condicionais como o if, foreach e assim por diante.

Veja também: error_reporting().

Nota: O prefixo de controle de erro "@" não desabilita mensagens que são resultado de erros de interpretação (parse errors).

Atenção

Atualmente, o operador de controle de erro "@" sempre desativa mensagens de erro, mesmo para erros críticos, que terminam a execução de scripts. Além de outras coisas, isto significa que se você usar "@" para suprimir erros de certas funções e elas não estiverem disponíveis ou com tipos incorretos, o script vai parar exatamente aí sem nenhuma indicação da razão.


Operadores de Execução

O PHP suporta um operador de execução: acentos graves (``). Note que não são apóstrofes! O PHP tentará executar o conteúdo dos acentos graves como um comando do shell; a saída será retornada (isto é, ela não será simplesmente descarregada para a saída; ela pode ser atribuída a uma variável).

$output = `ls -al`;
echo "<pre>$output</pre>";

Nota: O operador de execução fica desabilitado quando o safe mode está ativo ou shell_exec() está desabilitado.

Veja também: escapeshellcmd(), exec(), passthru(), popen(), shell_exec() e system().


Operadores de Incremento/Decremento

O PHP suporta operadores de pré e pós-incremento e decremento no estilo C.

Tabela 11-5. Operadores de Incremento/Decremento

Exemplo Nome Efeito
++$a Pré-incremento Incrementa $a em um, e então retorna $a.
$a++ Pós-incremento Retorna $a, e então incrementa $a em um.
--$a Pré-decremento Decrementa $a em um, e então retorna $a.
$a-- Pós-decremento Retorna $a, e então decrementa $a em um.

Aqui está um script de exemplo simples:

<?php
echo "<h3>Pós-incremento</h3>";
$a = 5;
echo "Deve ser 5: " . $a++ . "<br />\n";
echo "Deve ser 6: " . $a . "<br />\n";

echo "<h3>Pré-incremento</h3>";
$a = 5;
echo "Deve ser 6: " . ++$a . "<br />\n";
echo "Deve ser 6: " . $a . "<br />\n";

echo "<h3>Pós-decremento</h3>";
$a = 5;
echo "Deve ser 5: " . $a-- . "<br />\n";
echo "Deve ser 4: " . $a . "<br />\n";

echo "<h3>Pré-decremento</h3>";
$a = 5;
echo "Deve ser 4: " . --$a . "<br />\n";
echo "Deve ser 4: " . $a . "<br />\n";
?>


Operadores Lógicos

Tabela 11-6. Operadores Lógicos

Exemplo Nome Resultado
$a and $b E Verdadeiro (TRUE) se tanto $a quanto $b são verdadeiros.
$a or $b OU Verdadeiro se $a ou $b são verdadeiros.
$a xor $b XOR Verdadeiro se $a ou $b são verdadeiros, mas não ambos.
! $a NÃO Verdadeiro se $a não é verdadeiro.
$a && $b E Verdadeiro se tanto $a quanto $b são verdadeiros.
$a || $b OU Verdadeiro se $a ou $b são verdadeiros.

A razão para as duas variantes dos operandos "and" e "or" é que eles operam com precedências diferentes. (Veja Precedência de Operadores.)


Operadores de String

Há dois operadores de string. O primeiro é o operador de concatenação ('.'), que retorna a concatenação dos seus argumentos direito e esquerdo. O segundo é o operador de atribuição de concatenação ('.='), que acrescenta o argumento do lado direito no argumento do lado esquerdo. Veja em Operadores de Atribuição para mais informações.

$a = "Olá ";
$b = $a . "mundo!"; // agora $b contém "Olá mundo!"

$a = "Olá ";
$a .= "mundo!";     // agora $a contém "Olá mundo!"


Operadores de Arrays

O único operador de arrays no PHP é o +. Ele acrescenta o array informado à direita no array informado à esquerda, onde chaves duplicadas NÃO são sobrescritos.

$a = array("a" => "maçã", "b" => "banana");
$b = array("a" =>"pêra", "b" => "framboesa", "c" => "morango");

$c = $a + $b;

var_dump($c);
array(3) {
  ["a"]=>
  string(5) "maçã"
  ["b"]=>
  string(6) "banana"
  ["c"]=>
  string(6) "morango"
}


Capítulo 12. Estruturas de Controle

Qualquer script PHP é construído por uma série de instruções. Uma instrução pode ser uma atribuição, uma chamada de função, um 'loop', uma instrução condicional, ou mesmo uma instrução que não faz nada(um comando vazio). Instruções geralmente terminam com um ponto e vírgula. Além disso, as instruções podem ser agrupados em um grupo de comandos através do encapsulamento de um grupo de comandos com chaves. Um grupo de comandos é uma instrução também. Os vários tipos de instruções são descritos neste capítulo.


if

A construção if é uma das mais importantes implementações de muitas linguagens, incluindo o PHP. Ela permite a execução condicional de fragmentos de código. O PHP implementa uma estrutura if que é similar àquela do C:

if (expressao)
    instrucoes

Como descrita na seção sobre expressões , expressao é avaliado por seu contexto Booleano. Se expressao for avaliado como TRUE, o PHP executará instrucoes, e se for avaliado como FALSE, ele será ignorado. Maiores informações sobre a avaliação para FALSE podem ser encontradas na seção Convertendo para Booleanos .

Os exemplos a seguir mostrariam que a é maior que b se $a for maior que $b:

if ($a > $b)
    print "a é maior que b";

Freqüentemente você vai querer ter mais que uma instrução seja executado condicionalmente. E é claro, não há necessidade de englobar cada instrução com uma cláusula if. Em vez disso, você pode colocar várias instruções em um agrupamento de comandos. Por exemplo, este código mostraria a é maior que b se $a for maior que $b, e então atribuiria o valor de $a para $b:

if ($a > $b) {
    print "a é maior que b";
    $b = $a;
}

Comandos if podem ser aninhados indefinidamente dentro de outros comandos if, o que faz com que você complete a flexibilidade para a execução condicional de várias partes do seu programa.


else

Freqüentemente você vai querer executar uma instrução se uma certa condição for encontrada, e uma instrução diferente se a condição não for encontrada. Isto é o que o else faz. else estende um comando if para executar uma instrução caso a expressão no comando if seja avaliada como FALSE. Por exemplo, o código a seguir mostraria a é maior que b se $a for maior que $b, e a NÃO é maior que b caso contrário:

if ($a > $b) {
    print "a é maior que b";
} else {
    print "a NÃO é maior que b";
}

O comando else só é executado se a expressão if for avaliada como FALSE, e se havendo qualquer expressão elseif, somente se todas elas forem avaliadas como FALSE também (veja elseif).


elseif

elseif, como seu nome sugere, é uma combinação de if e else. Da mesma forma que o else, ele estende um comando if para executar uma instrução diferente no caso de a expressão if original ser avaliada como FALSE. Porém, ao contrário de else, ele executará aquela expressão alternativa somente se a expressão condicional do elseif for avaliada como TRUE. Por exemplo, o código a seguir mostraria a é maior que b, a é igual a b ou a é menor que b:

if ($a > $b) {
    print "a é maior que b";
} elseif ($a == $b) {
    print "a é igual a b";
} else {
    print "a é menor que b b";
}

Podem haver vários elseifs dentro da mesma instrução if. A primeira expressão elseif (se houver) que for avaliada como TRUE será executada. No PHP, você também pode escrever 'else if' (em duas palavras) e o comportamento será idêntico a um 'elseif' (em uma só palavra). O significado sintático é ligeiramente diferente (se você está familiarizado com C, eles tem o mesmo comportamento), mas no final de contas ambos teriam exatamente o mesmo comportamento.

O comando elseif só é executado se a expressão if precedente e quaisquer expressões elseif anteriores forem avaliadas como FALSE, e a expressão elseif atual for avaliada como TRUE.


Sintaxe alternativa para estruturas de controle

O PHP oferece uma sintaxe alternativa para algumas das suas estruturas de controle: if, while, for, foreach e switch. Em cada caso, a forma básica da sintaxe alternativa é mudar o sinal de abertura para dois-pontos (:) e o sinal de fechamento para endif;, endwhile;, endfor;, endforeach; ou endswitch;, respectivamente.

<?php if ($a == 5): ?>
A é igual a 5
<?php endif; ?>

No exemplo acima, o bloco HTML "A é igual a 5" está aninhado dentro de uma instrução if escrito na sintaxe alternativa. O bloco HTML será mostrado somente se $a é igual a 5.

A sintaxe alternativa se aplica a else e elseif também. A seguir temos uma estrutura if com elseif e else no formato alternativo:

if ($a == 5):
    print "a igual a 5";
    print "...";
elseif ($a == 6):
    print "a igual a 6";
    print "!!!";
else:
    print "a não é nem 5 nem 6";
endif;

Veja também: while, for e if para mais exemplos.


while

Loops while são o tipo mais simples de criar um 'loop' em PHP. Eles se comportam como seus compatíveis em C. O formato básico de um comando while é:

while (expressao) instrucoes

O significado de um comando while é simples. Ele pede que o PHP execute os comandos aninhados repetidamente, enquanto a expressão do while é avaliada como TRUE. O valor da expressão é verificada cada vez que se passa no começo do 'loop', desta forma, mesmo que este valor mude durante a execução do(s) comando(s) aninhado(s), a execução não parará até que o fim da iteração (cada vez que o PHP executa os comandos dentro do 'loop' é uma iteração). Às vezes, se a expressão while é avaliada como FALSE logo no início, o(s) comando(s) aninhado(s) não será(ão) rodado(s) nem uma vez sequer.

Como no comando if, você pode agrupar múltiplos comandos dentro do mesmo laço while englobando um grupo de instruções com chaves, ou usando a sintaxe alternativa:

while (expressao): instrucoes ... endwhile;

Os exemplos a seguir são idênticos, e ambos imprimem números de 1 to 10:

/* exemplo 1 */

$i = 1;
while ($i <= 10) {
    print $i++;  /* o valor impresso será
                    $i depois do acréscimo
                    (post-increment) */
}

/* exemplo 2 */

$i = 1;
while ($i <= 10):
    print $i;
    $i++;
endwhile;


do..while

Loops do..while são bem similares aos loops while, exceto pelo fato de que a condição é verificada no fim de cada iteração em vez de no começo. A diferença principal dos loops while regulares é que a primeira iteração de um loop do..while é garantidamente executada (a condição só é verificada no fim da iteração) enquanto que ele pode não rodar necessariamente em um loop while normal (a condição é verificada no começo de cada iteração, se ela é avaliada como FALSE logo no começo, a execução do loop terminaria imediatamente).

Há apenas uma sintaxe para loops do..while:

$i = 0;
do {
   print $i;
} while ($i>0);

O loop acima rodaria exatamente uma vez, desde que depois da primeira iteração, quando a condição é verificada, ela é avaliada como FALSE ($i não é maior que zero 0) e a execução do loop termina.

Usuários avançados de C podem estar familiarizados com o uso diferenciado do loop do..while, para permitir o fim da execução no meio dos blocos de código, englobando-os com do..while(0), e usando a instrução break . O fragmento de código a seguir demonstra isso:

do {
    if ($i < 5) {
        print "i não é grande o suficiente";
        break;
    }
    $i *= $factor;
    if ($i < $minimum_limit) {
        break;
    }
    print "i está Ok";

     ...process i...

} while(0);

Não se preocupe se você não entendeu isto da forma certa ou de jeito nenhum. Você pode codificar scripts simples ou mesmo poderosos sem usar esse 'recurso'.


for

Loops for são os laços mais complexos em PHP. Eles se comportam como os seus compatíveis em C. A sintaxe de um loop for é:

for (expr1; expr2; expr3) instrucoes

A primeira expressão (expr1) é avaliada (executada) uma vez incondicionalmente no começo do loop.

No começo de cada iteração, expr2 é avaliada. Se ela é avaliada como TRUE, o loop continua e o(s) comando(s) aninhado(s) é(são) executado(s). Se é avaliada como FALSE, a execução do 'loop' termina.

No fim de cada iteração, expr3 é avaliada (executada).

Cada uma das expressões pode ser vazia. expr2 vazia significa que o loop pode rodar indefinidamente (PHP considera-a implicitamente como TRUE, como em C). Isto pode não ser tão inútil quanto você pode pensar, pois freqüentemente você pode querer terminar o 'loop' usando uma instrução break condicional em vez de usar a expressão-verdade do for.

Considere os seguintes exemplos. Todos eles mostram números de 1 a 10:

/* exemplo 1 */

for ($i = 1; $i <= 10; $i++) {
    print $i;
}

/* exemplo 2 */

for ($i = 1;;$i++) {
    if ($i > 10) {
        break;
    }
    print $i;
}

/* exemplo 3 */

$i = 1;
for (;;) {
    if ($i > 10) {
        break;
    }
    print $i;
    $i++;
}

/* exemplo 4 */

for ($i = 1; $i <= 10; print $i, $i++);

Obviamente, o primeiro exemplo parece ser o mais bonito (ou talvez o quarto), mas você pode perceber que a possível utilização de expressões vazias em laços for se torna prático em algumas ocasiões.

O PHP também suporta a "sintaxe de dois-pontos" alternativa para laços for:

for (expr1; expr2; expr3): instrucoes; ...; endfor;

Outras linguagens têm uma instrução foreach para varrer uma matriz ou tabela de hashing. O PHP 3 não tem uma construção deste tipo; O PHP 4 possui (veja foreach). No PHP 3, você pode combinar while com as funções list() e each() para obter o mesmo efeito. Veja a documentação para estas funções para exemplos.


foreach

O PHP4 (mas não o PHP3) inclui um construtor foreach, muito parecido com o PERL e outras linguagens. Isto oferece uma maneira fácil de iterar sobre matrizes. foreach funciona somente com arrays, e lançará um erro se tentar utilizá-lo em uma variável de qualquer tipo diferente ou em variáveis não inicializadas. Há duas sintaxes; a segunda é uma abreviatura, mas útil, da primeira:

foreach(expressao_array as $valor) instrucoes
foreach(expressao_array as $chave => $valor) instrucoes

A primeira forma varre uma dada matriz dada por expressao_array. Em cada 'loop', o valor do elemento corrente é atribuído a $valor e o ponteiro interno da matriz é avançado em uma posição (assim, no próxima iteração você estará olhando para o próximo elemento).

A segunda forma faz a mesma coisa, exceto pelo fato de que a chave do elemento atual será atribuído à variável $chave em cada iteração.

Nota: Quando o foreach inicia sua primeira execução, o ponteiro interno da matriz é zerado automaticamente para o primeiro elemento do array. Isto significa que você não precisa chamar reset() antes de um loop foreach .

Nota: Note também que foreach opera sobre uma cópia do array especificado, não o próprio array, portanto o ponteiro da array não é modificado como na instrução each(), que altera o elemento do array selecionado, mas isso não se reflete o array original.

Nota: foreach tem a habilidade de evitar mensagens de erro com '@'.

Você pode ter notado que os seguintes itens são funcionalmente idênticos:

reset ($arr);
while (list(, $value) = each ($arr)) {
    echo "Valor: $value<br>\n";
}

foreach ($arr as $value) {
    echo "Valor: $value<br>\n";
}

Os seguintes também são funcionalmente idênticos:

reset ($arr);
while (list($key, $value) = each ($arr)) {
    echo "Chave: $key; Valor: $value<br>\n";
}

foreach ($arr as $key => $value) {
    echo "Chave: $key; Valor: $value<br>\n";
}

Mais alguns exemplos para demonstrar os usos:

/* exemplo foreach 1: somente valores */

$a = array (1, 2, 3, 17);

foreach ($a as $v) {
   print "Valor atual de \$a: $v.\n";
}

/* exemplo foreach 2: valores (com as chaves impressas para ilustração) */

$a = array (1, 2, 3, 17);

$i = 0; /* para exemplo somente */

foreach($a as $v) {
    print "\$a[$i] => $v.\n";
    $i++;
}

/* exemplo foreach 3: chaves e valores */

$a = array (
    "um" => 1,
    "dois" => 2,
    "três" => 3,
    "dezessete" => 17
);

foreach($a as $k => $v) {
    print "\$a[$k] => $v.\n";
}

/* exemplo foreach 4: arrays multidimensionais */

$a[0][0] = "a";
$a[0][1] = "b";
$a[1][0] = "y";
$a[1][1] = "z";

foreach($a as $v1) {
    foreach ($v1 as $v2) {
        print "$v2\n";
    }
}

/* exemplo foreach 5: arrays dinâmicos */

foreach(array(1, 2, 3, 4, 5) as $v) {
    print "$v\n";
}


break

break cancela a execução do comando for, foreach while, do..while ou switch atual.

break aceita um argumento numérico opcional que diz a ele quantas estruturas aninhadas englobadas devem ser quebradas.

$arr = array ('um', 'dois', 'três', 'quatro', 'PARE', 'cinco');
while (list (, $val) = each ($arr)) {
    if ($val == 'PARE') {
        break;    /* Você poderia colocar 'break 1;' aqui. */
    }
    echo "$val<br>\n";
}

/* Utilizando o argumento opcional. */

$i = 0;
while (++$i) {
    switch ($i) {
    case 5:
        echo "No 5<br>\n";
        break 1;  /* Sai somente do switch. */
    case 10:
        echo "No 10; saindo<br>\n";
        break 2;  /* Sai do switch e while. */
    default:
        break;
    }
}


continue

continue é usado dentro de estruturas de loops para saltar o resto da iteração do loop atual e continuar a execução no início da próxima iteração.

continue aceita um argumento numérico opcional que diz a ele de quantos níveis de loops aninhados ele deve saltar até o fim.

while (list ($key, $value) = each ($arr)) {
    if (!($key % 2)) { // pula itens pares
        continue;
    }
    do_something_odd ($value);
}

$i = 0;
while ($i++ < 5) {
    echo "Fora<br>\n";
    while (1) {
        echo "&nbsp;&nbsp;Meio<br>\n";
        while (1) {
            echo "&nbsp;&nbsp;Dentro<br>\n";
            continue 3;
        }
        echo "Isto nunca será exibido.<br>\n";
    }
    echo "Nem isso.<br>\n";
}


switch

A instrução switch é similar a uma série de instruções IFs seguidas. Em muitas ocasiões, você poderá ter que comparar a mesma variável (ou expressão) com muitos valores diferentes, executando códigos diferentes dependendo com qual valor ele se encaixar. É exatamente para isso que a instrução switch faz.

Os exemplos seguintes mostram duas maneiras diferentes de escrever a mesma coisa, uma utilizando uma série de iss e a outra utlizando a instrução switch:

if ($i == 0) {
    print "i igual a 0";
}
if ($i == 1) {
    print "i igual a 1";
}
if ($i == 2) {
    print "i igual a 2";
}

switch ($i) {
    case 0:
        print "i igual a 0";
        break;
    case 1:
        print "i igual a 1";
        break;
    case 2:
        print "i igual a 2";
        break;
}

É importante entender como a instrução switch funciona para evitar enganos. A instrução switch executa linha a linha (atualmente, instrução a instrução). No início, nenhum código é executado. Somente quando uma instrução case é encontrada com um valor que combina com a expressão do switch faz com que o PHP execute as instruções a partir daí. O PHP continua executando as instruções até o fim do bloco switch ou na primeira vez que encontrar uma instrução break. Se você não escrever uma instrução break no fim das instruções case, o PHP continuará executando os cases seguintes. Exemplo:

switch ($i) {
    case 0:
        print "i igual a 0";
    case 1:
        print "i igual a 1";
    case 2:
        print "i igual a 2";
}

Aqui, se $i é igual a zero, o PHP executará todas as instruções print!. Se $i é igual a 1, o PHP executará os últimas duas instruções print, e somente se $i for igual a 2, você terá o comportamento 'esperado' apenas onde 'i igual a 2' será mostrado. Então é importante não se esquecer das instruções break (e as vezes não colocá-las para obter esse resultado em certas circunstâncias).

Em uma instrução switch, a condição somente será avaliada e resultado comparado para cada instrução case. Em uma instrução elseif, a condição é avaliada novamente. Se sua condição é mais complicada que um simples comparação e/ou e dentro de um loop, um switch é mais rápido.

Um case pode não ter nenhuma instrução dentro, o que simplesmente passa o controle para o próximo case.

switch ($i) {
    case 0:
    case 1:
    case 2:
        print "i é menor que 3 mas não negativo";
        break;
    case 3:
        print "i é 3";
}

Um case especial é o default. Esse case é executado quando nenhum outro case combina. Ele precisa ser a última instrução case. Por exemplo:

switch ($i) {
    case 0:
        print "i igual a 0";
        break;
    case 1:
        print "i igual a 1";
        break;
    case 2:
        print "i igual a 2";
        break;
    default:
        print "i não é igual a 0, 1 ou 2";
}

A expressão avaliada pelo case precisa ser um tipo simples, ou seja, inteiros, números de ponto flutuante e strings. Arrays ou objetos não podem ser utilizados a não ser que eles impliquem num tipo simples.

A sintaxe alternativa para estruturas de controle é suportada para os switches. Para maiores informações, veja Sintaxe alternativa para estruturas de controle.

switch ($i):
    case 0:
        print "i igual a 0";
        break;
    case 1:
        print "i igual a 1";
        break;
    case 2:
        print "i igual a 2";
        break;
    default:
        print "i não é igual a 0, 1 ou 2";
endswitch;


declare

O construtor declare é utilizado para configurar diretivas de execução para blocos de código. A sintaxe do declare é similar a sintaxe de outros construtores de controle.

declare (diretiva) instrucao

A seção diretiva permite o comportamento do bloco declare a ser configurado. Atualmente somente uma diretiva é reconhecida: a diretiva ticks. (veja abaixo para maiores informações em diretiva ticks)

A parte instrucao do bloco declare será executada. Como ela é executada e que efeitos colaterais que podem ocorrem durante a execução dependem da configuração diretiva.


Ticks

Um tick é um evento que ocorre para cada N níveis de instruções executados pelo interpretador com o bloco declare. O valor para N é especificado utilizando ticks=N nos blocos declare das seções diretiva.

O(s) evento(s) que ocorre(m) em cada tick são especificados utilizando register_tick_function(). Veja o exemplo abaixo para maiores detalhes. Note que mais de um evento pode ocorrer em cada tick.

Exemplo 12-1. Histórico de um trecho de código PHP

<?php
// Uma função que grava o tempo entre as chamadas
function profile ($dump = FALSE)
{
    static $profile;

    // Retorna os tempos preservados no histórico, então apaga
    if ($dump) {
        $temp = $profile;
        unset ($profile);
        return ($temp);
    }

    $profile[] = microtime ();
}

// Ativa o manipulador do tick
register_tick_function("profile");

// Inicializa a função antes de declarar o bloco
profile ();

// Roda um trecho de código, disparando um tick a cada duas instruções
declare (ticks=2) {
    for ($x = 1; $x < 50; ++$x) {
        echo similar_text (md5($x), md5($x*$x)), "<br />;";
    }
}

// Mostra os dados guardados no histórico
print_r (profile (TRUE));
?>
No exemplo acima, o bloco 'declare' grava os tempos a cada segundo nível dentro das instruções no bloco enquanto executam. Esta informação pode ser utilizada para encontrar áreas lentas em segmentos particulares de código. Este processo pode ser realizado de outras formas, mas a utilização de ticks é mais conveniente e fácil de implementar.

Ticks são idealizados para debug, implementação de multitask simples, processos de I/O em background e afins.

Veja também: register_tick_function() e unregister_tick_function().


return

Se chamada em uma função, a instrução return() termina imediatamente a execução da função atual e retorna seu argumento como o valor da função. return() também termina a execução de uma instrução eval() ou de um script.

Se chamada no escopo global, a execução do script atual será terminada. Se o arquivo do script atual foi incluído com include() ou require(), então a execução é devolvida para o arquivo chamador. Especificamente para arquivos de script incluídos com include(), o valor fornecido para return() será devolvido como o valor da chamada include(). Se return() for chamado do arquivo de script principal, então o programa pára. Se o arquivo de script atual é o configurado em auto_prepend_file ou auto_append_file do arquivo de configuração, então a execução desses scripts é finalizada.

Para maiores informações, veja Retornando Valores.

Nota: Note que return() é um construtor de linguagem e não uma função, e parênteses em volta do seus argumentos não são necessários -- de fato, é mais comum não colocá-los que usá-los, sem, entretanto, haver diferença de um jeito ou de outro.


require()

A instrução require() inclui a avalia um arquivo específico.

Informações detalhadas de como essa inclusão funciona está descrita na documentação do include().

require() e include() são idênticos em todas as formas exceto pela manipulação de erros. include() produz um Warning enquanto require() produzirá um Fatal Error. Em outras palavras, não hesite em utilizar require() se na falta de um arquivo quiser parar o processamento da página. include() não se comporta da mesma maneira, e o script poderá continuar nessa situação. Em todo caso, vale a pena confirmar a configuração da diretiva include_path.

Exemplo 12-2. Exemplos de require()s simples

<?php

require 'prepend.php';

require $somefile;

require ('somefile.txt');

?>

Vaja a documentação de include() para mais exemplos.

Nota: Até o PHP 4.0.2, havia o seguinte comportamento: require() mesmo que a linha onde ele está nunca seja executada. É por isso que instruções condicionais não afetam require(). Entretanto, se a linha onde ocorre o require() não for executada, nada do código incluído do arquivo também será. Similarmente, estruturas de loop não afetam o funcionamento do require(). Mas o código incluído pela função será submetida ao loop. A instrução require() apenas ocorre uma vez.

Atenção

A versões Windows do PHP anteriores ao PHP 4.3 não suportam acesso a arquivos remotos através desta função, mesmo se allow_url_fopen estiver ativado.

Veja também: include(), require_once(), include_once(), eval(), file(), readfile(), virtual() e include_path.


include()

A instrução include() inclui e avalia o arquivo informado.

A documentação a seguir se aplica também a require(). Esses dois construtores são idênticos a exceção de como eles manipulam erros. include() produz um Warning enquanto require() produzirá um Fatal Error. Em outras palavras, utilize require() se você deseja que um arquivo faltando interrompa o processamento da página. include() não se comporta da mesma maneira, permitindo que o script continue nessas situações. Em todo caso, vale a pena confirmar a configuração da diretiva include_path.

Quando um arquivo é incluído, seu código entra no escopo de variável da linha onde a inclusão ocorre. Qualquer variável disponível da linha onde a chamada da inclusão ocorre estará disponível para o arquivo incluído, daquele ponto em diante.

Exemplo 12-3. Exemplos de include()s simples

variaveis.php
<?php

$cor = 'verde';
$fruta = 'maçã';

?>

teste.php
<?php

echo "Uma $fruta $cor"; // Uma

include 'vars.php';

echo "Uma $fruta $cor"; // Uma maçã verde

?>

Se o include ocorre dentro de uma função do arquivo principal, então todo o código incluído será executado como se ele tivesse sido definido dentro daquela função. Da mesma forma, ele seguirá o escopo de variáveis da função.

Exemplo 12-4. Incluindo dentro de funções

<?php

function foo()
{
global $cor;

    include 'variaveis.php';

    echo "Uma $fruta $cor";
}

/* variaveis.php está no escopo de foo(),   *
.* então $fruta NÃO está disponível fora de *
.* seu escopo. $cor estará porque ela foi   *
.* declarada como global                    */

foo();                    // Uma maçã verde
echo "A $fruta $cor";   // Uma maçã

?>

Quando um arquivo é incluído, o interpretador sai do modo PHP e entra no modo HTML (no começo do arquivo incluído), e alterna novamente no seu fim. Por isso, qualquer código dentro do arquivo incluído que precisa ser executado como código PHP tem de ser delimitado por tags válidas de abertura e fechamento.

Se "URL fopen wrappers" estão ativas no PHP (normalmente na configuração default), você pode especificar um arquivo utilizando uma URL (via HTTP ou qualquer outro wrapper suportado --- veja Apêndice I para uma lista dos protocolos) em vez de uma caminho local. Se o servidor apontado interpreta o arquivo informado como código PHP, variáveis podem ser passadas ao arquivo incluído na URL de requisição como num HTTP GET. Isto não é necessariamente a mesma coisa que incluir o arquivo e compartilhar o escopo de variável do arquivo principal: o script será executado no servidor remoto e apenas seu resultado será incluído no script local.

Atenção

A versões Windows do PHP anteriores ao PHP 4.3 não suportam acesso a arquivos remotos através desta função, mesmo se allow_url_fopen estiver ativado.

Exemplo 12-5. include() através de HTTP

<?php

/* Este exemplo assume que www.exemplo.com está configurado para interpretar *
 * arquivos .php mas não .txt. Além, 'Funciona' aqui significa que as        *
 * variáveis $foo e $bar estão disponíveis no arquivo incluído               */

// Não funciona: arquivos txt não são manipulados em www.example.com como PHP
include 'http://www.exemplo.com/arquivo.txt?foo=1&bar=2';

// Não funciona: procura por um arquivo chamado 'arquivo.php?foo=1&bar=2' no
// sistemas de arquivo local.
include 'arquivo.php?foo=1&bar=2';

// Funciona.
include 'http://www.exemplo.com/arquivo.php?foo=1&bar=2';

$foo = 1;
$bar = 2;
include 'arquivo.txt';  // Funciona.
include 'arquivo.php';  // Funciona.

?>
Vaja também: Arquivos Remotos, fopen() e file() para informações relacionadas.

Por serem include() e require() dois construtores de linguagem especiais, você precisa delimitá-los como um bloco de instruções quando utilizados dentro de instruções condicionais.

Exemplo 12-6. include() e instruções condicionais

<?php

// Isto está errado e não funcionará como desejado
if ($condition)
    include $arquivo;
else
    include $outro;


// E este está correto
if ($condition) {
    include $arquivo;
} else {
    include $outro;
}

?>

Também é possível executar uma instrução return() dentro de um arquivo incluído de maneira a finalizar o processamento daquele arquivo e retornar para o script que o chamou. Também é possível retornar valores de arquivos incluídos. Você pode pegar o valor de retorno de um include como faria com uma função normal.

Nota: No PHP 3, o return não pode aparecer dento de um bloco a não ser que ele seja um bloco de função, e nesse caso return() se aplica apenas para a função e não para todo o arquivo.

Exemplo 12-7. Instruções include() e return()

return.php
<?php

$var = 'PHP';

return $var;

?>

noreturn.php
<?php

$var = 'PHP';

?>

testreturns.php
<?php

$foo = include 'return.php';

echo $foo; // imprime 'PHP'

$bar = include 'noreturn.php';

echo $bar; // imprime 1

?>

$bar assimila o valor 1 porque a inclusão foi realizada com sucesso. Verifique a diferença entre os exemplo. O primeiro utiliza return() dentro do arquivo incluído enquanto que o outro não. Há outras maneiras de "incluir" arquivos dentro de variáveis, com fopen(), file() ou utilizando include() através das Funções de Controle de Output.

Veja também: require(), require_once(), include_once(), readfile(), virtual() e include_path.


require_once()

A instrução require_once() incluí e avalia o arquivo especificado durante a execução do script. Seu comportamento é similar ao da instrução require(), a não ser que o arquivo informado já tenha sido incluído, não refazendo a operação novamente. Veja a documentação de require() para maiores informações sobre como essa instrução funciona.

require_once() pode ser utilizado nos casos em que o mesmo arquivo pode acabar sendo incluído mais de uma vez durante a execução de um script em particular, quando na verdade ele só pode ser incluído apenas uma, para evitar problemas com redefinições de funções, alterações nos valores de variáveis, etc.

Para exemplos de utilização de require_once() e include_once(), veja o código do PEAR incluído nas últimas distribuições do código fonte do PHP.

Nota: require_once() foi acrescentado a partir PHP 4.0.1pl2

Nota: Esteja avisado que o comportamento de require_once() e include_once() pode não ser o que você espera em um sistema operacional insensitivo ao caso (como o Windows).

Exemplo 12-8. require_once() é sensitivo ao caso

require_once("a.php"); // isto irá incluir a.php
require_once("A.php"); // isto irá incluir a.php de novo no Windows!

Atenção

A versões Windows do PHP anteriores ao PHP 4.3 não suportam acesso a arquivos remotos através desta função, mesmo se allow_url_fopen estiver ativado.

Veja também: require(), include(), include_once(), get_required_files(), get_included_files(), readfile() e virtual().


include_once()

A instrução include_once() inclui e avalia o arquivo especificado durante a execução de um script. Seu comportamento é similar a instrução include(), a não ser que o arquivo informado já tenha sido incluído, não refazendo a operação novamente. Como o nome sugere, ele será incluído apenas uma vez.

include_once() pode ser utilizado nos casos em que o mesmo arquivo pode acabar sendo incluído mais de uma vez durante a execução de um script em particular, quando na verdade ele só pode ser incluído apenas uma para evitar problemas com redefinições de funções, alterações nos valores de variáveis, etc.

Para maiores informações utilizando require_once() e include_once(), veja o código do PEAR incluído nas últimas distribuições do código fonte do PHP.

Nota: include_once() foi acrescentado a partir PHP 4.0.1pl2

Nota: Esteja avisado que o comportamento de include_once() e require_once() pode não ser o que você espera em um sistema operacional insensitivo ao caso (como o Windows).

Exemplo 12-9. include_once() é sensitivo ao caso

include_once("a.php"); // isto irá incluir a.php
include_once("A.php"); // isto irá incluir a.php de novo no Windows!

Atenção

A versões Windows do PHP anteriores ao PHP 4.3 não suportam acesso a arquivos remotos através desta função, mesmo se allow_url_fopen estiver ativado.

Veja também: include(), require(), require_once(), get_required_files(), get_included_files(), readfile() e virtual().


Capítulo 13. Funções

Funções definidas pelo usuário

Uma função pode ser definida usando-se a sintaxe como a seguinte:

function foo ($argumento_1, $argumento_2, ..., $argumento_n)
{
    echo "Exemplo de função.\n";
    return $valor_retornado;
}

Qualquer código PHP válido pode aparecer dentro de uma função, mesmo outras funções e definições de classes.

No PHP3, as funções precisam ser definidas antes de serem referenciadas. Esse requisito não existe no PHP4.

O PHP não suporta sobrecarga de funções, e também não é possível cancelar ou alterar a definição de funções previamente declaradas.

O PHP3 não suporta número variável de argumentos para funções, apesar de os argumentos padrões serem suportados (veja Valores padrão de argumentos para mais informações). O PHP4 suporta ambos: veja Número de argumentos variável e as referências das funções func_num_args(), func_get_arg() e func_get_args() para mais informações.


Argumentos de funções

Informações podem ser passadas para funções através da lista de argumentos, que é uma lista de variáveis e/ou constantes delimitados por vírgulas.

O PHP suporta a passagem de argumentos por valor (o padrão), passagem por referência e valores padrão de argumento . Listas de argumentos de comprimento variável são suportadas apenas no PHP4 e posterior; veja Número de argumentos variável e as referências das funções func_num_args(), func_get_arg() e func_get_args() para mais informações. Um efeito similar pode ser atingido no PHP 3 pela passagem de um array de argumentos para uma função:

function takes_array($input)
{
    echo "$input[0] + $input[1] = ", $input[0]+$input[1];
}


Fazendo argumentos serem passados por referência

Por padrão, argumentos de função são passados por valor (de forma que se você mudar o valor do parâmetro dentro da função, ele não é alterado fora da função). Se você deseja permitir que uma função modifique seus argumentos, você precisa passá-los por referência.

Se você quer que um argumento para uma função sempre seja passado por referência, você pode preceder o nome do argumento com um "e comercial" (&) na definição da função:

function add_some_extra(&$string)
{
    $string .= ' e alguma coisa mais.';
}
$str = 'Isto é uma string,';
add_some_extra($str);
echo $str;    // imprime 'Isto é uma string, e alguma coisa mais.'


Valores padrão de argumentos

Uma função pode definir valores padrão no estilo C++ para argumentos escalares, como a seguir:

function cafeteira ($tipo = "cappuccino")
{
    return "Fazendo uma xícara de café $type.\n";
}
echo cafeteira ();
echo cafeteira ("expresso");

A saída do código acima será:
Fazendo uma xícara de café cappucino.
Fazendo uma xícara de café expresso.

O valor padrão precisa ser uma expressão constante, não (por exemplo) uma variável ou um membro de classe.

Note que usando argumentos padrão, qualquer padrão deve vir após os argumentos sem padrão: caso contrário, as coisas não funcionarão como esperado. Considere o seguinte trecho de código:

function iogurtera ($tipo = "azeda", $sabor)
{
    return "Fazendo uma taça de $tipo $sabor.\n";
}

echo iogurtera ("framboesa");   // não funciona como esperado

A saída do exemplo acima é:
Warning: Missing argument 2 in call to iogurtera() in
/usr/local/etc/httpd/htdocs/php3test/functest.html on line 41
Fazendo uma taça de framboesa.

Agora, compare o que está acima com este:

function iogurtera ($sabor, $tipo = "azeda")
{
    return "Fazendo uma taça de $tipo $sabor.\n";
}

echo iogurtera ("framboesa");   // funciona

A saída deste exemplo é:
Fazendo uma taça de framboesa azeda.


Número variável de argumentos

O PHP4 tem suporte para um número variável de argumentos nas funções definidas pelo usuário. Isto é realmente bem fácil, usando as funções func_num_args(), func_get_arg() e func_get_args().

Nenhuma sintaxe especial é requerida, e a lista de argumentos ainda pode ser fornecida explicitamente com as definições de funções e se comportarão normalmente.


Retornando valores

Valores podem ser retornados utilizando a instrução opcional return. Qualquer tipo pode ser retornado, incluindo arrays e objetos. Isto faz com que as função termine sua execução imediatamente e passa o controle de volta para a linha de onde ela foi chamada. Veja a documentação da função return() para maiores informações.

function quadrado ($num)
{
    return $num * $num;
}
echo quadrado (4);   // imprime '16'.

Você não pode retornar múltiplos valores a partir de uma função, mas resultados similares podem ser devolvidos retornando por uma lista.

function numeros_pequenos()
{
    return array (0, 1, 2);
}
list ($zero, $um, $dois) = numeros_pequenos();

Para retornar uma referência de uma função, você precisa utilizar o operador de referência & tanto na declaração da função como quando assimilando o valor retornado para a variável.

function &retorna_referencia()
{
    return $alguma_referencia;
}

$nova_referencia =& retorna_referencia();

Para mais detalhes sobre referências, leia a seção Referências.


old_function

O comando old_function permite que você declare uma função usando uma sintaxe idêntica ao PHP/FI2 (exceto pelo fato de que você precisa substituir 'function' com 'old_function').

Esta é uma implementação obsoleta, e deve ser usada somente pelo conversor PHP/FI2->PHP3.

Atenção

Funções declaradas como old_function não podem ser chamadas a partir de código interno do PHP. Entre outras coisas, isso significa que você não pode usá-las em funções como usort(), array_walk() e register_shutdown_function(). Você pode contornar essa limitação escrevendo um invólucro de função (no formato PHP3 normal) para chamar o old_function.


Funções variáveis

O PHP suporta o conceito de funções variáveis. Isto significa que se um nome de variável tem parênteses no final dela, o PHP procurará uma função com o mesmo nome, qualquer que seja a avaliação da variável, e tentará executá-la. Entre outras coisas, isto pode ser usado para implementar callbacks, tabelas de função e assim por diante.

Funções variáveis não funcionam com construtores de linguagem como echo(), unset(), isset(), empty(), include() ou print().

Exemplo 13-1. Exemplo de funções variáveis

<?php
function foo()
{
    echo "Chamou foo()<br>\n";
}

function bar($arg = '')
{
    echo "Chamou bar(); com argumento '$arg'.<br>\n";
}

$func = 'foo';
$func();
$func = 'bar';
$func('teste');
?>

Veja também: Variáveis variáveis e function_exists().


Capítulo 14. Classes e Objetos

class

Uma classe é uma coleção de variáveis e funções trabalhando com essas variáveis. Uma classe é definida usando-se a seguinte sintaxe:

<?php
class CarrinhoDeCompras
{
    var $items;  // Itens do carrinho de compras

    // Acrescenta a quantidade $num do artigo $artnr no carrinho

    function add_item ($artnr, $num)
    {
        $this->items[$artnr] += $num;
    }

    // Retira a quantidade $num de artigos $artnr do carrinho

    function remove_item ($artnr, $num)
    {
        if ($this->items[$artnr] > $num) {
            $this->items[$artnr] -= $num;
            return true;
        } else {
            return false;
        }
    }
}
?>

Isto define uma classe chamada CarrinhoDeCompras que consiste de uma matriz associativa de artigos no carrinho e duas funções para acrescentar e remover itens deste carrinho.

Cuidado

Os cuidados a seguir devem ser tomados a partir do PHP 4:

O nome stdClass é utilizado internamente pela Zend e é uma palavra reservada. Você não pode ter uma classe chamada stdClass no PHP.

O nome de função __sleep e __wakeup são especialmente mágicos para as classes PHP. Você não pode ter esses nomes em nenhuma de suas classes a não ser que você deseje aplicar essa funcionalidade mágica com elas. Veja abaixo para mais detalhes.

O PHP reserva todos os nomes de funções começando com __ como mágicas. É recomendável que você não utilize nome de funções começando com __ no PHP a não ser que você precise dessas funcionalidades mágicas.

Nota: No PHP 4, somente inicializações com constantes são permitidas para variáveis com var. Para inicializar variáveis com valores não constantes, você precisará de uma função de inicialização chamada automaticamente quando o objeto for construído a partir da classe. Por isso, essa função é conhecida como construtor (veja baixo).

<?php
/* Nenhuma delas funcionarão com o PHP 4 */
class CarrinhoDeCompras
{
    var $data_de_hoje = date("Y-m-d");
    var $nome = $primeiro_nome;
    var $proprietario = 'Fred ' . 'Jones';
    var $items = array("VCR", "TV");
}

/* Esta é a forma como deve ser feito */
class CarrinhoDeCompras
{
    var $data_de_hoje;
    var $nome;
    var $proprietario;
    var $items;

    function CarrinhoDeCompras()
    {
        $this->data_de_hoje = date("Y-m-d");
        $this->nome = $GLOBALS['primeiro_nome'];
        /* etc. . . */
    }
}
?>

Classes são tipos, ou seja, são apenas um modelo das variáveis normais. Você pode criar uma variável (ou instância) do tipo desejado com o operador new.

<?php
$carrinho = new CarrinhoDeCompras;
$carrinho->add_item("10", 1);

$outro_carrinho = new CarrinhoDeCompras;
$outro_carrinho->add_item("0815", 3);

Isto cria os objetos $carrinho e $outro_carrinho, ambos a partir da classe CarrinhoDeCompras. A função add_item() do objeto $carrinho foi chamada e acrescentou 1 item do artigo número 10 a ele. 3 itens do artigo número 0815 foi acrescentado no $outro_carrinho.

Ambos, $carrinho e $outro_carrinho, tem as funções add_item(), remove_item() e a variável itens. Elas são funções e variáveis distintas entre si. Você pode pensar no objetos como os diretórios de um sistema de arquivos. Num disco você pode ter dois arquivos diferentes README.TXT, partindo de que eles estão em diretórios diferentes. Da mesma forma que você teria de especificar o caminho completo para acessar cada arquivo a partir do diretório principal, você também tem de especificar o nome completo do objeto e função que você quer chamar. Em termos do PHP, o diretório principal pode ser o escopo global de nomes, e o separador de diretórios ->. Portanto, os nomes $carrinho->items e $outro_carrinho->items são duas variáveis diferentes. Note que a variável é chamada $carrinho->items e não $carrinho->$items, mesmo porque, um nome de variável em PHP tem apenas um único sinal de cifrão.

// correcto, apenas um $
$carrinho->items = array("10" => 1);

// inválido, porque $carrinho->$items se transforma em $carrinho->""
$carrinho->$items = array("10" => 1);

// correto, mas pode ou não ser o que você quer:
// $carrinho->$myvar se torna $carrinho->items
$myvar = 'items';
$carrinho->$myvar = array("10" => 1);

Quando definindo uma classe, você não pode saber com que nome os objetos serão acessados em seus programas: enquanto escrevia a classe CarrinhoDeCompras, é impossível saber se o objeto criado a partir dela será chamado $carrinho ou $outro_carrinho (ou ainda ambos). Assim, você não pode escrever $carrinho>items dentro da própria classe CarrinhoDeCompras. Entretanto, para poder acessar suas próprias funções e variáveis de dentro da classe, pode-se utilizar a pseudo-variável $this, que pode ser lida como 'eu mesmo' ou 'objeto atual'. Dessa forma, '$this->items[$artnr] += $num' pode ser lido como 'acrescente $num para o contador $artnr do meu array items' ou 'acrescente $num para o contador $artnr do array do objeto atual'.

Nota: Há funções muito boas para manipulação de classes e objetos. Dê uma olhada em Funções de Classes e Objetos


extends

Permite classes com variáveis e funções similares a uma outra classe. De fato, é uma boa prática definir classes genéricas que podem ser utilizadas em todos os seus projetos, e adaptar essas classes com as necessidades específicas de cada projeto. Para facilitar isso, classes podem ser extensões de outras classes. A classe estendida ou derivada tem todas as variáveis e funções da classe base (isto é chamado herança, afora o fato que ninguém morreu) e mais aquelas que venha a acrescentar na versão estendida. Não é possível subtrair uma classe, ou seja, indefinir quaisquer funções ou variáveis existentes. Uma classe estendida é sempre dependente de uma única classe base, e portanto, herança múltipla não é suportada. Classes são estendidas utilizando a instrução 'extends'.

class CarrinhoDeComprasNomeado extends CarrinhoDeCompras
{
    var $proprietario;

    function set_proprietario ($name)
    {
        $this->proprietario = $name;
    }
}

Isto define uma classe chamada CarrinhoDeComprasNomeado que tem todas as variáveis e funções de CarrinhoDeCompras mais a variável $proprietario e uma função set_proprietario(). Você pode criar um carrinho nomeado da maneira usual e configurar e obter o proprietário do carrinho. Você ainda pode continuar utilizando carrinhos normais e carrinhos nomeados:

$ncart = new CarrinhoDeComprasNomeado;
$ncart->set_proprietario("kris");
print $ncart->proprietario;
$ncart->add_item("10", 1);  // (funcionalidade herdade do CarrinhoDeCompras)

Isto é chamado relacionamento "pai-filho". Você cria uma classe pai e utiliza extends para criar uma nova classe baseada na classe pai: sua classe filha. Você ainda pode criar uma nova classe estendida a partir dessa classe filha e assim por diante.

Nota: As classes precisam ser definidas antes de serem utilizadas! Se você estender a classe CarrinhoDeComprasNomeado da classe CarrinhoDeCompras, você precisa antes criar a classe chamada CarrinhoDeCompras. Se você quiser criar uma outra classe chamada CarrinhoDeComprasNomeadoAmarelo baseada na classe CarrinhoDeComprasNomeado você tem que definir CarrinhoDeComprasNomeado primeiro. Trocando em miúdos: a ordem em que as classes são definidas é importante.


Construtores

Cuidado

Os construtores se comportam diferentemente entre o PHP 3 e o PHP 4. A semântica do PHP 4 é atualmente preferencial.

Construtores são funções numa classe que são automaticamente chamados quando você cria uma nova instância da classe com new. No PHP 3, uma função se torna um construtor quando ele tem o mesmo nome da classe. No PHP 4, uma função se torna um construtor quando ele tem o mesmo nome da classe onde ela foi definida (a diferença é sutil, mas crucial --- veja abaixo).

// Funciona no PHP 3 e 4
class CarrinhoDeComprasAutomatico extends CarrinhoDeCompras
{
    function CarrinhoDeComprasAutomatico()
    {
        $this->add_item ("10", 1);
    }
}

Isto define uma classe chamada CarrinhoDeComprasAutomatico que é um CarrinhoDeCompras mais um construtor que inicializa o carrinho com um item do artigo numero "10" cada vez que um novo CarrinhoDeComprasAutomatico for criado com "new". Construtores pode ter argumentos e esses argumentos podem ser opcionais, o que os torna muito mais práticos. Para permitir a criação de classes sem parâmetros, todos os parâmetros dos construtores pode ser feitos opcionais simplesmente por terem valores default.

// Funciona no PHP 3 e 4
class CarrinhoDeComprasComConstrutor extends CarrinhoDeCompras
{
    function CarrinhoDeComprasComConstrutor($item = "10", $num = 1)
    {
        $this->add_item ($item, $num);
    }
}

// Fazendo compras do mesmo modo antigo

$carrinho_default = new CarrinhoDeComprasComConstrutor;

// Fazendo compres de verdade

$carrinhho_diferente = new CarrinhoDeComprasComConstrutor("20", 17);

Você pode usar o operador @ para esconder erros gerados no construtor do objeto, por exemplo: @new.

Cuidado

No PHP 3, classes derivadas e construtores tem uma série de limitações. Os exemplo seguintes precisam ser lidos cuidadosamente para que você entenda essas limitações.

class A
{
    function A()
    {
      echo "Eu sou o construtor de A.<br>\n";
    }
}

class B extends A
{
    function C()
    {
        echo "Eu sou uma função normal.<br>\n";
    }
}

// nenhum construtor é chamado no PHP 3
$b = new B;

No PHP 3, nenhum construtor é chamado no exemplo acima. A regra no PHP 3 é: 'Um construtor é uma função com o mesmo nome da classe'. O nome da classe é B, e não há nenhuma função chamada B() na classe B. Nada ocorre.

Isto foi corrigido no PHP 4 pela instrução de outra regra: Se uma classe não tem construtor, o construtor da classe base é chamado, se existir. O exemplo acima teriam impresso 'Eu sou o construtor de A<br>'. no PHP 4.

class A
{
    function A()
    {
        echo "Eu sou o construtor de A.<br>\n";
    }

    function B()
    {
        echo "Eu sou uma função normal chamada B na classe A.<br>\n";
        echo "Eu não sou o construtor de A.<br>\n";
    }
}

class B extends A
{
    function C()
    {
        echo "Eu sou uma função normal.<br>\n";
    }
}

// Isto irá chamar B() como um construtor.
$b = new B;

No PHP 3, a função B() na classe A se tornará silenciosamente um construtor na classe B, mesmo que isso nunca tenha sido planejado. A regra no PHP 3 é: 'Um construtor é uma função com o mesmo nome da classe'. PHP 3 não se preocupa se a função foi definida na classe B, ou se ela foi herdada.

Isto foi corrigido no PHP 4 pela modificação da regra para: 'Um construtor é uma função com o mesmo nome da classe onde ela é definida.'. Assim, no PHP 4, como a classe B não tem nenhuma função construtora definida nela mesma então o construtor da classe base será chamado, imprimindo 'Eu sou o construtor de A.<br>'.

Cuidado

Nem o PHP 3 ou o 4 chamam automaticamente os construtores da classe base a partir do construtor da classe derivada. É de sua responsabilidade propagar a chamada dos construtores herança acima, onde apropriado.

Nota: Não existem destrutores no PHP 3 ou 4. Mas você pode usar register_shutdown_function() para simular a maioria dos efeitos de destrutores.

Destrutores são funções que são chamadas automaticamente quando um objeto é destruído, ou pela utilização de unset() ou pela simples saída do escopo. Não existem destrutores no PHP.


::

Cuidado

O seguinte é valido para o PHP 4 somente.

As vezes pode ser útil se referir a funções e variáveis na classe base ou referenciar funções em classes que não possuem qualquer instância. O operador :: pode ser utilizado nessas ocasiões.

class A
{
    function exemplo()
    {
        echo "Eu sou a função original A::exemplo().<br>\n";
    }
}

class B extends A
{
    function exemplo()
    {
        echo "Eu sou a função redefinida B::exemplo().<br>\n";
        A::exemplo();
    }
}

// Nao ha nenhum objeto da classe A.
// Isto ira imprimir
//   Eu sou a função original A::exemplo().<br>
A::exemplo();

// cria um objeto a partir da classe B
$b = new B;

// Isto ira imprimir
//   Eu sou a função redefinida B::exemplo().<br>
//   Eu sou a função original A::exemplo().<br>
$b->exemplo();

O exemplo acima chama a função exemplo() da classe A, mas não há nenhum objeto da classe A, então não podemos escrever $a->exemplo() ou qualquer coisa similar, Em vez disso, nós chamamos exemplo() como uma 'função de classe', ou seja, como uma função da classe propriamente dita, não qualquer objeto dessa classe.

Existem funções de classe, mas não variáveis de classe. De fato, não há nenhum objeto durante toda a execução. Assim, uma função de classe não pode usar qualquer variável de objeto (mas pode usar variáveis locais e globais), e nunca podendo utilizar-se de $this.

Ainda no exemplo acima, a classe B redefine a função exemplo(). A definição da função original na classe A é ocultada e nunca disponível, a não ser que você se referencie especificamente a implementação de exemplo() da classe A utilizando-se do operador ::. Escrevemos A::exemplo() para isso (de fato, você também pode escrever parent::exemplo(), como mostrado na próxima seção).

Nesse contexto, existe um objeto e ele pode ter variáveis de objeto. Assim, quando utilizado de DENTRO de uma função de objeto, você pode usar $this e variáveis de objeto.


parent

Você pode se encontrar escrevendo código que precisa referenciar a variáveis e funções na classe base. Isto é particularmente verdade se você derivou uma classe como um refinamento ou especialização de código de sua classe base.

Em vez de utilizar o nome literal da classe base em seu código, você pode usar o nome especial parent, que se refere ao nome da sua classe base como informado na declaração extends. Fazendo isso, evita assim a utilização do nome da sua classe base em mais de um lugar. Se sua árvore de herança mudar durante a implementação, a modificação é mais facilmente realizada pela simples alteração da declaração extends de suas classes.

class A
{
    function exemplo()
    {
        echo "Eu sou A:exemplo() e provenho funcionalidades básicas.<br>\n";
    }
}

class B extends A
{
    function exemplo()
    {
        echo "Eu sou B::exemplo() e provenho funcionalidades adicionais.<br>\n";
        parent::exemplo();
    }
}

$b = new B;

// Isto ira chamar B::exemplo(), que por sua vez chama A::exemplo().
$b->exemplo();


Serializando objetos - objetos em sessões

Nota: No PHP 3, objetos perdem suas associações entre classes através do processo de serialização e desserialização. A variável resultante é do tipo objeto, mas sem classe nem métodos, algo bem sem utilidade (de fato, ele se torna apenas um array com uma sintaxe engraçada).

Cuidado

As informações seguintes se aplicam somente ao PHP 4.

serialize() retorna uma string contendo uma representação linear de qualquer valor que pode ser armazenado no PHP. unserialize() pode ser utilizado para recriar os valores da variável original. Usando serialize para salvar um objeto irá preservar todas as variáveis de um objeto. As funções de um objeto não serão salvas, apenas o nome da classe.

Para ser possível fazer o unserialize() de um objeto, a classe do objeto precisa estar definida. Ou seja, se você tem um objeto $a da classe A em page1.php e a serializa, você consegue uma string que se refere a classe A e contém todos os valores de variáveis contidos em $a. Se você precisa desserializa-la em page2.php, recriando $a da classe A, a definição da classe A precisa estar presente na page2.php. Isto pode por ser feito, por exemplo, armazenando a definição da classe A em um arquivo separado, incluindo este arquivo e ambos os arquivos page1.php e page2.php.

classe_a.inc.php:
  class A
  {
      var $um = 1;

      function mostre_um()
      {
          echo $this->um;
      }
  }

page1.php:
  include("classe_a.inc.php");

  $a = new A;
  $s = serialize($a);
  // armazena $s em algum lugar que page2,php possa encontra-la
  $fp = fopen("armazenamento", "w");
  fputs($fp, $s);
  fclose($fp);

page2.php:
  // Isto e preciso para que unserialize funcione normalmente
  include("classe_a.inc.php");

  $s = implode("", @file("armazenamento"));
  $a = unserialize($s);

  // Agora podemos usar a funcao mostre_um() do objeto $a
  $a->mostre_um();

Se você está utilizando sessões e usar session_register() para registrar objetos, esses objetos serão serializados automaticamente no final de cada script PHP, e automaticamente desserializados em cada uma das páginas seguintes. Isto significa que esse objetos podem estar em qualquer uma de suas páginas desde que elas sejam parte de sua sessão.

É extremamente recomendável que você inclua as definições de classe de todos os objetos registrados de todas as suas páginas, mesmo que você não use essas classes em todas as suas páginas. Se você não o fizer e um objeto for desserializado sem sua definição de classe presente, ele perde usa associação com a classe e se torna um objeto da classe stdClass, sem qualquer funções disponíveis. o que as deixa silenciosamente sem funcionalidade.

Assim, se no exemplo acima $a se tornar parte de uma sessão pela utilização de session_register("a"), você precisa incluir o arquivo classe_a.inc.php em todos as suas páginas, não somente em page1.php e page2.php.


As funções mágicas __sleep e __wakeup

serialize() verifica se sua classe tem uma função com o nome mágico __sleep. Se sim, essa função será executada antes de qualquer serialização. Assim é possível controlar a persistência do objeto enquanto deve retornar um array com os nomes de todas as variáveis daquele objeto que precisam ser serializadas.

__sleep é planejado para fechar quaisquer conexões com bancos de dados que o objeto tenha, realizar commits pendentes ou realizar tarefas de limpeza semelhantes. A função também é útil se você tem objetos muito grandes que não precisam ser salvos completamente.

Da mesma forma, unserialize() verifica pela presença de uma função com o nome mágico __wakeup. Se presente, esta função pode reconstruir quaisquer recursos que o objeto tenha.

__wakeup é planejado para restabelecer conexões com bancos de dados perdidas durante a serialização e para realizar outras tarefas de reinicialização.


Referências dentro do construtor

A criação de referências em construtores pode gerar resultados confusos. Esta seção tentará ajudá-lo e evitar essas situações.

class Foo
{
    function Foo($name)
    {
        // cria uma referencia dentro do array global $globalref
        global $globalref;
        $globalref[] = &$this;
        // configura o nome conforme o parametro
        $this->setName($name);
        // e o mostra
        $this->echoName();
    }

    function echoName()
    {
        echo "<br>",$this->name;
    }

    function setName($name)
    {
        $this->name = $name;
    }
}

Vamos verificar, abaixo, se há alguma diferença entre $bar1, que foi criado usando operador de cópia =, e $bar2 que foi criado usando o operador de referência =& ...

$bar1 = new Foo('configurado no construtor');
$bar1->echoName();
$globalref[0]->echoName();

/* saida:
configurado no construtor
configurado no construtor
configurado no construtor */

$bar2 =& new Foo('configurado no construtor');
$bar2->echoName();
$globalref[1]->echoName();

/* saida:
configurado no construtor
configurado no construtor
configurado no construtor */

Aparentemente não há nenhuma diferença, mas de fato há uma muito significativa: $bar1 e $globalref[0] não se referenciam, elas NÃO são a mesma variável. Isto acontece porque "new" não retorna uma referência por default. Ao invés, retorna uma cópia.

Nota: Isto não causa perda de performance (desde que o PHP 4 usa a contagem de referências) retornando copias em vez de referências. Do contrário, isso oferece melhora por simplificar o trabalho com cópias ao invés de referências, porque a criação de referências toma mais tempo enquanto a criação de cópias virtualmente não toma tempo algum (a não ser no caso de grandes arrays ou objetos, onde um deles é modificado e o(s) outro(s) também na seqüência, então é melhor usar referências para mudar todos ao mesmo tempo).

Para comprovar o que escrevemos acima, analise o seguinte código.

// Agora nos vamos mudar o nome. O que voce espera?
// Voce pode acreditar que ambos $bar1 e $globalref[0] mudem seus nomes...
$bar1->setName('configurado por fora');

// Como mencionado, este nao eh o caso.
$bar1->echoName();
$globalref[0]->echoName();

/* output:
configurado por fora
configurado no construtor */

// Agora vamos ver a diferenca entre $bar2 e $globalref[1]
$bar2->setName('configurado por fora');

// Por sorte, eles nao sao apenas iguais, eles sao a mesma variavel
// Assim, $bar2->name e $globalref[1]->name sao o mesmo tambem
$bar2->echoName();
$globalref[1]->echoName();

/* output:
configurado por fora
configurado por fora */

E apenas mais um exemplo final. Entenda-o com cuidado.

class A
{
    function A($i)
    {
        $this->value = $i;
        // tente entender porque aqui nos nao precisamos de referencia
        $this->b = new B($this);
    }

    function createRef()
    {
        $this->c = new B($this);
    }

    function echoValue()
    {
        echo "<br>","classe ",get_class($this),': ',$this->value;
    }
}


class B
{
    function B(&$a)
    {
        $this->a = &$a;
    }

    function echoValue()
    {
        echo "<br>","classe ",get_class($this),': ',$this->a->value;
    }
}

// Tente entender porque usando uma simples copia aqui ter
// um resultado indesejavel na linha marcada com *
$a =& new A(10);
$a->createRef();

$a->echoValue();
$a->b->echoValue();
$a->c->echoValue();

$a->value = 11;

$a->echoValue();
$a->b->echoValue(); // *
$a->c->echoValue();

/*
output:
classe A: 10
classe B: 10
classe B: 10
classe A: 11
classe B: 11
classe B: 11
*/


Capítulo 15. Referências

O que são referências

Referências, em PHP, significa acessar o mesmo conteúdo de variável através de vários nomes. Isto não é parecido como os ponteiros em C: aqui temos apelidos numa tabela simbólica. Note que no PHP nomes de variáveis e conteúdo de variável são tratados diferentemente, então um mesmo conteúdo pode ter nomes diferentes. A analogia mais próxima é a dos arquivos e seus nomes em sistemas UNIX: nomes de variáveis são o caminho completo dos arquivos, enquanto o conteúdo da variável são os dados desse arquivo. Assim, referências pode ser tomadas como os links físicos dentro do sistema de arquivos UNIX.


O as referências fazem

Referências PHP permitem fazer duas variáveis se referirem ao mesmo conteúdo. Ou seja:

$a =& $b

aqui $a e $b apontam para a mesma variável.

Nota: $a e $b são completamente iguais aqui, mas não porque $a está apontando para $b ou vice versa, mas sim que $a e $b apontam para o mesmo lugar.

A mesma sintaxe pode ser utilizada com funções, que retornem referências, e com o operador new (a partir do PHP 4.0.4):

$bar =& new fooclass();
$foo =& find_var ($bar);

Nota: A não utilização do operador & causará a cópia do objeto. Se você utiliza $this em classes, ele operará na instância atual do objeto. A assimilação sem & irá copiar a instância (o objeto em si) e $this irá operar na cópia, podendo não ser esse procedimento sempre desejável. Normalmente você precisará trabalhar com uma instância única, seja por motivos de performance ou de consumo de memória.

Você pode utilizar o operador @ para esconder quaisquer erros em construtores na forma @new, mas isto não funciona quando utilizada a instrução &new. Esta é uma limitação da Zend Engine e irá gerar um erro de interpretação (parser error).

A segunda coisa que referências permitem é passar variáveis por referência. Isto é feito marcando uma variável local de uma função e a variável do escopo chamador como referências ao mesmo conteúdo. Exemplo:

function foo (&$var)
{
    $var++;
}

$a=5;
foo ($a);

fará que $a seja 6. Isto acontece porque na função foo a variável $var se refere ao mesmo conteúdo que $a. Veja explicações mais detalhadas em passagem por referência.

Em terceiro lugar, referências permitem também retorno por referência.


O que as referências não são

Como dito anteriormente, referências não são ponteiros. Isto significa que o construtor seguinte não fará o que você espera:

function foo (&$var)
{
    $var =& $GLOBALS["baz"];
}
foo($bar);

Acontece que $var na função foo estará apontada para $bar na chamada, mas ela será re-apontada para $GLOBALS["baz"]. Não existe maneira de apontar $bar no escopo chamador para qualquer outra coisa utilizando o mecanismo de referências, desde que $bar não está disponível na função foo (ela é representa por $var, mas $var somente tem o conteúdo da variável e não um relacionamento nome para valor na tabela simbólica).


Passagem por referência

Você pode passar variáveis para funções por referência, então a função poderá modificar seus argumentos. A sintaxe é a seguinte:

function foo (&$var)
{
    $var++;
}

$a=5;
foo ($a);
// $a é 6 aqui

Note que não há o sinal de referência na chamada da função, somente na definição da função. A marcação na definição da função sozinha é suficiente para configurar corretamente a passagem de argumentos por referência.

As coisas a seguir podem ser passadas por referência:

  • Variáveis. Exemplo: foo($a)

  • Instrução new. Exemplo foo(new foobar())

  • Outra referência, retornada de uma função. Exemplo:

    function &bar()
    {
        $a = 5;
        return $a;
    }
    foo(bar());

    Veja explicações sobre isso em retorno por referência.

Nenhuma outra expressão poderá ser passada por referência, com resultados indefinidos. Por exemplo, o exemplo seguinte de passagem por referência é inválido:

function bar() // Note a falta do &
{
    $a = 5;
    return $a;
}
foo(bar());

foo($a = 5) // Expressão, não é variável
foo(5) // Constante, não é variável

Essas limitações valem para o PHP 4.0.4 em diante.


Retornando referências

Retorno por referência é útil quando você precisa utilizar uma função para localizar variável cuja referência precisa ser obtida. Para retornar referências, utilize esta sintaxe:

function &procura_var ($param)
{
    ...codigo...
    return $variavel_encontrada;
}

$foo =& procura_var ($bar);
$foo->x = 2;

Neste exemplo, a propriedade do objeto retornado pela função procura_var precissa ser assimilada, não copiada, como acontecerá se não utilizar a sintaxe de referências.

Nota: Diferentemente da passagem de parâmetros por referência, aqui você precisa utilizar & em ambos os lugares --- primeiro para indicar o retorno por referência (e não a cópia), e depois para indicar a ligação da referência (em vez da assimilação convencional) que precisa ser explícita.


Destruindo referências

Quando você quebra uma referência, ela apenas pára de fazer o apontamento entre o nome da variável e o conteúdo. Mas isto não significa que o conteúdo da variável será destruído. Por exemplo:

$a = 1;
$b =& $a;
unset ($a);

não apaga $b, apenas $a.

Novamente, é mais fácil pensar em analogia ao comando UNIX unlink.


Demonstrando referências

Vários construtores sintáticos do PHP são implementados através de mecanismos de referência, assim, tudo o explicado até aqui sobre referências também se aplica a esses construtores. Alguns desses construtores, como a passagem e o retorno de referências foram mencionados acima. Outros construtores que também utilizam referências são:


global

Quando você declara uma variável com global, você está de fato criando um referência para a variável global. Isto significa que isto é o mesmo que:

$var =& $GLOBALS["var"];

O que significa também que destruir $var não apaga a variável global.


$this

Num método de objeto, $this sempre referencia o instância atual.


Capítulo 16. HTTP authentication with PHP

The HTTP Authentication hooks in PHP are only available when it is running as an Apache module and is hence not available in the CGI version. In an Apache module PHP script, it is possible to use the header() function to send an "Authentication Required" message to the client browser causing it to pop up a Username/Password input window. Once the user has filled in a username and a password, the URL containing the PHP script will be called again with the predefined variables PHP_AUTH_USER, PHP_AUTH_PW, and PHP_AUTH_TYPE set to the user name, password and authentication type respectively. These predefined variables are found in the $_SERVER and $HTTP_SERVER_VARS arrays. Only "Basic" authentication is supported. See the header() function for more information.

PHP Version Note: Autoglobals, such as $_SERVER, became available in PHP version 4.1.0. $HTTP_SERVER_VARS has been available since PHP 3.

An example script fragment which would force client authentication on a page is as follows:

Exemplo 16-1. HTTP Authentication example

<?php
  if (!isset($_SERVER['PHP_AUTH_USER'])) {
    header('WWW-Authenticate: Basic realm="My Realm"');
    header('HTTP/1.0 401 Unauthorized');
    echo 'Text to send if user hits Cancel button';
    exit;
  } else {
    echo "<p>Hello {$_SERVER['PHP_AUTH_USER']}.</p>";
    echo "<p>You entered {$_SERVER['PHP_AUTH_PW']} as your password.</p>";
  }
?>

Compatibility Note: Please be careful when coding the HTTP header lines. In order to guarantee maximum compatibility with all clients, the keyword "Basic" should be written with an uppercase "B", the realm string must be enclosed in double (not single) quotes, and exactly one space should precede the 401 code in the HTTP/1.0 401 header line.

Instead of simply printing out PHP_AUTH_USER and PHP_AUTH_PW, as done in the above example, you may want to check the username and password for validity. Perhaps by sending a query to a database, or by looking up the user in a dbm file.

Watch out for buggy Internet Explorer browsers out there. They seem very picky about the order of the headers. Sending the WWW-Authenticate header before the HTTP/1.0 401 header seems to do the trick for now.

As of PHP 4.3.0, in order to prevent someone from writing a script which reveals the password for a page that was authenticated through a traditional external mechanism, the PHP_AUTH variables will not be set if external authentication is enabled for that particular page and safe mode is enabled. Regardless, REMOTE_USER can be used to identify the externally-authenticated user. So, you can use $_SERVER['REMOTE_USER'].

Configuration Note: PHP uses the presence of an AuthType directive to determine whether external authentication is in effect.

Note, however, that the above does not prevent someone who controls a non-authenticated URL from stealing passwords from authenticated URLs on the same server.

Both Netscape Navigator and Internet Explorer will clear the local browser window's authentication cache for the realm upon receiving a server response of 401. This can effectively "log out" a user, forcing them to re-enter their username and password. Some people use this to "time out" logins, or provide a "log-out" button.

Exemplo 16-2. HTTP Authentication example forcing a new name/password

<?php
  function authenticate() {
    header('WWW-Authenticate: Basic realm="Test Authentication System"');
    header('HTTP/1.0 401 Unauthorized');
    echo "You must enter a valid login ID and password to access this resource\n";
    exit;
  }
 
  if (!isset($_SERVER['PHP_AUTH_USER']) ||
      ($_POST['SeenBefore'] == 1 && $_POST['OldAuth'] == $_SERVER['PHP_AUTH_USER'])) {
   authenticate();
  } 
  else {
   echo "<p>Welcome: {$_SERVER['PHP_AUTH_USER']}<br>";
   echo "Old: {$_REQUEST['OldAuth']}";
   echo "<form action='{$_SERVER['PHP_SELF']}' METHOD='POST'>\n";
   echo "<input type='hidden' name='SeenBefore' value='1'>\n";
   echo "<input type='hidden' name='OldAuth' value='{$_SERVER['PHP_AUTH_USER']}'>\n";
   echo "<input type='submit' value='Re Authenticate'>\n";
   echo "</form></p>\n";
  }
?>

This behavior is not required by the HTTP Basic authentication standard, so you should never depend on this. Testing with Lynx has shown that Lynx does not clear the authentication credentials with a 401 server response, so pressing back and then forward again will open the resource as long as the credential requirements haven't changed. The user can press the '_' key to clear their authentication information, however.

Also note that this does not work using Microsoft's IIS server and the CGI version of PHP due to a limitation of IIS.

Nota: If safe mode is enabled, the uid of the script is added to the realm part of the WWW-Authenticate header.


Capítulo 17. Cookies

O PHP suporta transparentemente cookies HTTP. Cookies são um mecanismo para guardar dados no navegador remoto possibilitando o acompanhamento ou identificação de usuários que retornam. Você pode criar cookies usando a função setcookie(). Os cookies são uma parte do cabeçalho HTTP, logo setcookie() precisa ser chamada antes que qualquer outro dado seja enviado ao navegador. Esta é a mesma limitação que a função header() tem. Você pode usar as funções de output buferizado para atrasar as impressões do script até que você tenha decidido ou não configurar qualquer cookie ou enviar mais headers.

Qualquer cookie enviado por você para o cliente automaticamente será uma variável do PHP assim como dados de postagens GET ou POST, dependendo dos valores de register_globals e variables_order. Se você deseja assimilar vários valores em um único cookie, simplesmente acrescente [] ao nome do cookie.

NO PHP 4.1.0 e posteriores, o array superglobal $_COOKIE sempre estará preenchido com quaisquer cookies enviados do cliente. $HTTP_COOKIE_VARS, existente nas versões anteriores do PHP, também, quando a variável de configuração track_vars estiver ativa.

Para mais detalhes, incluindo comentários sobre problemas de browsers, veja a função setcookie().


Capítulo 18. Gerenciar o upload de arquivos

Upload de arquivos com o método POST

O PHP é capaz de receber o upload de qualquer browser que siga a norma RFC-1867 (o que inclui Netscape Navigator 3 ou posterior, Microsoft Internet Explorer 3 com um patch da Microsoft, ou posterior sem patch). Isto permite que se faça o upload de arquivos de texto e binários. Com as funções de autenticação e manipulação de arquivos do PHP, você tem o controle completo de quem pode fazer o upload de arquivo e o que fazer com o arquivo após seu upload.

Nota Sobre Configurações Relacionadas: Veja também file_uploads, upload_max_filesize, upload_tmp_dir, e post_max_size no php.ini

Note que o PHP também suporta o método PUT para upload de arquivos como o usado por Netscape Composer e W3C's Amaya clients. Veja Suporte ao Método Put para maiores detalhes.

Uma tela para upload de arquivo pode ser criada com um formulário especial parecido com este:

Exemplo 18-1. Formulário para Upload de Arquivo

<form enctype="multipart/form-data" action="_URL_" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="30000">
Send this file: <input name="userfile" type="file">
<input type="submit" value="Enviar Arquivo">
</form>
A _URL_ deve indicar um arquivo PHP. O campo hidden MAX_FILE_SIZE deve vir antes do campo input e seu valor é o limite aceito de tamanho do arquivo. O valor é em bytes.

Atenção

O valor de MAX_FILE_SIZE é um aviso para o browser. É fácil contornar este limite. Então não conte que o browser irá obedecer a sua vontade. O que foi estabelecido para maximum-size no PHP não pode ser enganado.

As variáveis definidas para o upload de arquivos são diferentes dependendo da versão e da configuração. A autoglobal $_FILES existe desde o PHP 4.1.0. A array $HTTP_POST_FILES existe desde o PHP 4.0.0. Estas array irão conter toda a informação do upload do arquivo. Usar $_FILES é preferido. Se a opção register_globals é on, os nomes de variáveis relacionados também existirão. O padrão de register_globals é off desde o PHP 4.2.0.

Os conteúdos de $_FILES do nosso script de exemplo é como segue. Note que isso assume que o nome do upload do arquivo é userfile, como o usado no exemplo acima.

$_FILES['userfile']['name']

O nome original do arquivo no computador do usuário.

$_FILES['userfile']['type']

O tipo mime do arquivo, se o browser deu esta informação. Um exemplo pode ser "image/gif".

$_FILES['userfile']['size']

O tamanho, em bytes, do arquivo.

$_FILES['userfile']['tmp_name']

O nome temporário do arquivo, como foi guardado no servidor.

$_FILES['userfile']['error']

O código de erro associado a este upload de arquivo. ['error'] foi adicionado no PHP 4.2.0

Nota: Em versões anteriores a 4.1.0 o nome era $HTTP_POST_FILES e não é uma variável autoglobal como $_FILES é. PHP 3 não suporta $HTTP_POST_FILES.

Quando register_globals esta em on no php.ini, variáveis adicionais estão disponíveis. Por exemplo, $userfile_name será igual a $_FILES['userfile']['name'], $userfile_type será igual a $_FILES['userfile']['type'], etc. Lembre-se que desde o PHP 4.2.0, o padrão para register_globals é off. É preferrível não depender desta opção.

Os arquivos serão guardados no diretório temporário do servidor, a menos que outro lugar seja especificado com a opção upload_tmp_dir no php.ini. O diretório padrão do servidor pode ser mudado se mudando o valor da variável de ambiente TMPDIR no ambiente onde o PHP esta sendo executado PHP. Mudando-a com putenv() de um script PHP não irá funcionar. Esta variável de ambiente também pode ser usada para se ter certeza que outras operações estão funcionando no arquivo do upload.

Note que deve se definir upload_temp_dir no php.ini ou TMPDIR, não podendo estarem ambos vazios, sendo recomendado no mínimo upload_tmp_dir.

Exemplo 18-2. Validando o upload de arquivos

Veja também as funções is_uploaded_file() e move_uploaded_file() para maiores informações. O seguinte exemplo irá processar o envio de um arquivo que vem de um formulário.

<?php
// Nas versões anteriores a 4.1.0, $HTTP_POST_FILES deve ser usado ao invés de $_FILES.
// Nas versões anteriores a 4.0.3, use copy() e is_uploaded_file() ao invés move_uploaded_file

$uploaddir = '/var/www/uploads/';

print "<pre>";
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploaddir . $_FILES['userfile']['name'])) {
    print "O arquivo é valido e foi carregado com sucesso. Aqui esta alguma informação:\n";
    print_r($_FILES);
} else {
    print "Possivel ataque de upload! Aqui esta alguma informação:\n";
    print_r($_FILES);
}

?>

O script PHP que irá receber o arquivo do upload deve implementar qualquer lógica que for necessária para determinar o que deve ser feito com o arquivo do upload. Você pode, por exemplo, usar a variável $_FILES['userfile']['size'] para descartar qualquer arquivo que seja muito pequeno ou muito grande. Você pode usar a variável $_FILES['userfile']['type'] que não sejam de um certo tipo. Desde o PHP 4.2.0, você pode usar $_FILES['userfile']['error'] e planejar a sua lógica de acordo com os códigos de erro. Qualquer que seja a lógica, você deve excluir o arquivo do diretório temporário ou move-lo para outro lugar.

O arquivo será excluído do diretório temporário ao fim do script se não tiver sido movido ou renomeado.


Explicação das mensagens de erro

Desde o PHP 4.2.0, PHP retorna um código de erro apropriado na array do arquivo. O código de erro pode ser encontrado em ['error'] na array que é criada durante o upload do arquivo. Em outras palavras, o erro deve ser encontrado em $_FILES['userfile']['error'].

UPLOAD_ERR_OK

Valor: 0; não houve erro, o upload foi bem sucedido.

UPLOAD_ERR_INI_SIZE

Valor 1; O arquivo no upload é maior do que o limite definido em upload_max_filesize no php.ini.

UPLOAD_ERR_FORM_SIZE

Valor: 2; O arquivo ultrapassa o limite de tamanho em MAX_FILE_SIZE que foi especificado no formulário html.

UPLOAD_ERR_PARTIAL

Valor: 3; o upload do arquivo foi feito parcialmente.

UPLOAD_ERR_NO_FILE

Valor: 4; Não foi feito o upload do arquivo.

Nota: Estas tornaram-se constantes no PHP 4.3.0


Problemas comuns

O item MAX_FILE_SIZE não pode especificar um tamanho de arquivo com tamanho maior do que o especificado no php.ini em upload_max_filesize. O padrão é 2 Megabytes.

Se o limite de memória esta ativado, um maior memory_limit pode ser necessário. tenha certeza de estabelecer um memory_limit grande o suficiente.

Se max_execution_time for muito pequeno, a execução do script pode ultrapassar o limite de tempo. Tenha certeza de estabelecer um max_execution_time grande o suficiente.

Se post_max_size for muito pequeno, arquivos grandes não poderão ser carregados. Tenha certeza de estabelecer post_max_size grande o suficiente.

Não validar o arquivo que você esta operando pode permitir que os usuários acessem informações sensíveis em outros diretórios.

Por favor note que o CERN httpd aparenta cortar tudo iniciando após o primeiro espaço do header content-type que ele recebe do cliente. Se for este o caso, CERN httpd não irá suportar o upload de arquivos.

Devido ao grande número de estilos de listagem de diretórios nós não podemos garantir que arquivos com nomes exóticos(como que contém espaço) sejam manuseados corretamente.


Carregando múltiplos arquivos

Múltiplos arquivos podem ser carregados usando-se diferentes name para input.

Também é possível carregar vários arquivos simultaneamente e ter a informação organizada automaticamente para você em arrays. Para fazer assim, você precisa usar a mesma sintaxe no formulário HTML que você usa para múltiplos selects e checkboxes:

Nota: O Suporte para carregar múltiplos arquivos foi adicionado na versão 3.0.10.

Exemplo 18-3. Carregando múltiplos arquivos

<form action="file-upload.php" method="post" enctype="multipart/form-data">
  Send these files:<br>
  <input name="userfile[]" type="file"><br>
  <input name="userfile[]" type="file"><br>
  <input type="submit" value="Send files">
</form>

Quando o formulário acima é submetido, as matrizes $_FILES['userfile'], $_FILES['userfile']['name'], e $_FILES['userfile']['size'] serão inicializadas (assim como $HTTP_POST_FILES para versões do PHP anterior a 4.1.0). Quando register_globals esta em on, globals para os arquivos carregados também são inicializadas. Cada um destes será uma array indexada numericamente dos valores apropriados para os arquivos submetidos.

Por exemplo, assuma que os nomes de arquivos tenham sido submetidos /home/test/review.html e /home/test/xwp.out. Neste caso, $_FILES['userfile']['name'][0] deve conter o valor review.html, e $_FILES['userfile']['name'][1] deve conter o valor xwp.out. Similarmente, $_FILES['userfile']['size'][0] deve conter o tamanho de review.html, e assim por diante.

$_FILES['userfile']['name'][0], $_FILES['userfile']['tmp_name'][0], $_FILES['userfile']['size'][0], e $_FILES['userfile']['type'][0] também são definidas.


Suporte ao método PUT

O suporte ao método PUT mudou entre PHP 3 e PHP 4. No PHP 4, deve se usar a entrada padrão para ler os conteúdos de um PUT.

Exemplo 18-4. Salvando arquivos HTTP PUT com o PHP 4

<?php
/* PUT data vem do stdin stream */
$putdata = fopen("php://stdin","r");

/* Abre um arquivo para escrita */
$fp = fopen("myputfile.ext","w");

/* Lê os dados 1KB de cada vez
   e escreve no arquivo */
while ($data = fread($putdata,1024))
  fwrite($fp,$data);

/* Fecha os streams */
fclose($fp);
fclose($putdata);
?>

Nota: Toda a documentação abaixo aplica-se ao PHP 3 somente.

PHP prove suporte para o método HTTP PUT usado por clientes como Netscape Composer e W3C Amaya. Requisições PUT são muito mais simples do que o upload de arquivo e se parecem com isto:

PUT /path/filename.html HTTP/1.1

Isto normalmente indica que o cliente remoto gostaria de salvar o conteúdo que se segue como: /path/filename.html na sua arvore web. É obvio que não é uma boa idéia para o Apache ou o PHP automaticamente permitir que todos possam sobrescrever arquivos na sua arvore web. Então, para manusear este tipo de requisição você tem primeiro que dizer ao seu servidor web que você quer que um certo script PHP cuide da requisição. No apache você faz isto com a diretiva Script. Pode ser colocada praticamente em qualquer lugar do seu arquivo de configuração do Apache. Um lugar comum é dentro de um bloco <Directory> ou talvez dentro de um bloco <Virtualhost>. Uma linha como esta deve fazer o truque:

Script PUT /put.php

Isto diz para o apache enviar todas as requisições PUT que estejam no contexto que você colocou esta linha para o script put.php. Isto assume, é claro, que você tem o PHP ativado para a extensão .php e que o PHP esta ativo.

Dentro do seu arquivo put.php você deve então fazer algo parecido com isto:

<?php copy($PHP_UPLOADED_FILE_NAME,$DOCUMENT_ROOT.$REQUEST_URI); ?>

Isto deve copiar o arquivo para a localização requisitada pelo cliente remoto. Você provavelmente quer fazer alguma checagem e/ou autenticar o usuário antes de fazer esta copia de arquivo. O único truque aqui é que quando o php vê uma requisição com o método PUT ele guarda o arquivo carregado em um arquivo temporário justo como se fosse manuseado pelo método POST. Quando a requisição termina, este arquivo temporário é apagado. Assim seu script de manuseio do PUT tem que copiar este arquivo em outro lugar. O nome deste arquivo temporário esta na variável $PHP_PUT_FILENAME, e você pode ver o nome de arquivo de destino sugerido em $REQUEST_URI (deve variar em servidores diferentes do apache). Este nome do arquivo de destino é o que o cliente remoto especificou. Você não tem que ouvir o cliente. Você pode, por exemplo, copiar todos os arquivos carregados para um diretório especial de uploads.


Capítulo 19. Using remote files

As long as allow_url_fopen is enabled in php.ini, you can use HTTP and FTP URLs with most of the functions that take a filename as a parameter. In addition, URLs can be used with the include(), include_once(), require() and require_once() statements. See Apêndice I for more information about the protocols supported by PHP.

Nota: In PHP 4.0.3 and older, in order to use URL wrappers, you were required to configure PHP using the configure option --enable-url-fopen-wrapper.

Nota: The Windows versions of PHP earlier than PHP 4.3 did not support remote file accessing for the following functions: include(), include_once(), require(), require_once(), and the imagecreatefromXXX functions in the Referência XLI, Image functions extension.

For example, you can use this to open a file on a remote web server, parse the output for the data you want, and then use that data in a database query, or simply to output it in a style matching the rest of your website.

Exemplo 19-1. Getting the title of a remote page

<?php
$file = fopen ("http://www.example.com/", "r");
if (!$file) {
    echo "<p>Unable to open remote file.\n";
    exit;
}
while (!feof ($file)) {
    $line = fgets ($file, 1024);
    /* This only works if the title and its tags are on one line */
    if (eregi ("<title>(.*)</title>", $line, $out)) {
        $title = $out[1];
        break;
    }
}
fclose($file);
?>

You can also write to files on an FTP server (provided that you have connected as a user with the correct access rights). You can only create new files using this method; if you try to overwrite a file that already exists, the fopen() call will fail.

To connect as a user other than 'anonymous', you need to specify the username (and possibly password) within the URL, such as 'ftp://user:password@ftp.example.com/path/to/file'. (You can use the same sort of syntax to access files via HTTP when they require Basic authentication.)

Exemplo 19-2. Storing data on a remote server

<?php
$file = fopen ("ftp://ftp.example.com/incoming/outputfile", "w");
if (!$file) {
    echo "<p>Unable to open remote file for writing.\n";
    exit;
}
/* Write the data here. */
fputs ($file, $_SERVER['HTTP_USER_AGENT'] . "\n");
fclose ($file);
?>

Nota: You might get the idea from the example above that you can use this technique to write to a remote log file. Unfortunately that would not work because the fopen() call will fail if the remote file already exists. To do distributed logging like that, you should take a look at syslog().


Capítulo 20. Connection handling

Nota: The following applies to 3.0.7 and later.

Internally in PHP a connection status is maintained. There are 3 possible states:

  • 0 - NORMAL

  • 1 - ABORTED

  • 2 - TIMEOUT

When a PHP script is running normally the NORMAL state, is active. If the remote client disconnects the ABORTED state flag is turned on. A remote client disconnect is usually caused by the user hitting his STOP button. If the PHP-imposed time limit (see set_time_limit()) is hit, the TIMEOUT state flag is turned on.

You can decide whether or not you want a client disconnect to cause your script to be aborted. Sometimes it is handy to always have your scripts run to completion even if there is no remote browser receiving the output. The default behaviour is however for your script to be aborted when the remote client disconnects. This behaviour can be set via the ignore_user_abort php.ini directive as well as through the corresponding "php_value ignore_user_abort" Apache .conf directive or with the ignore_user_abort() function. If you do not tell PHP to ignore a user abort and the user aborts, your script will terminate. The one exception is if you have registered a shutdown function using register_shutdown_function(). With a shutdown function, when the remote user hits his STOP button, the next time your script tries to output something PHP will detect that the connection has been aborted and the shutdown function is called. This shutdown function will also get called at the end of your script terminating normally, so to do something different in case of a client disconnect you can use the connection_aborted() function. This function will return TRUE if the connection was aborted.

Your script can also be terminated by the built-in script timer. The default timeout is 30 seconds. It can be changed using the max_execution_time php.ini directive or the corresponding "php_value max_execution_time" Apache .conf directive as well as with the set_time_limit() function. When the timer expires the script will be aborted and as with the above client disconnect case, if a shutdown function has been registered it will be called. Within this shutdown function you can check to see if a timeout caused the shutdown function to be called by calling the connection_timeout() function. This function will return TRUE if a timeout caused the shutdown function to be called.

One thing to note is that both the ABORTED and the TIMEOUT states can be active at the same time. This is possible if you tell PHP to ignore user aborts. PHP will still note the fact that a user may have broken the connection, but the script will keep running. If it then hits the time limit it will be aborted and your shutdown function, if any, will be called. At this point you will find that connection_timeout() and connection_aborted() return TRUE. You can also check both states in a single call by using the connection_status(). This function returns a bitfield of the active states. So, if both states are active it would return 3, for example.


Capítulo 21. Persistent Database Connections

Persistent connections are SQL links that do not close when the execution of your script ends. When a persistent connection is requested, PHP checks if there's already an identical persistent connection (that remained open from earlier) - and if it exists, it uses it. If it does not exist, it creates the link. An 'identical' connection is a connection that was opened to the same host, with the same username and the same password (where applicable).

Nota: There are other extensions that provide persistent connections, such as the IMAP extension.

People who aren't thoroughly familiar with the way web servers work and distribute the load may mistake persistent connects for what they're not. In particular, they do not give you an ability to open 'user sessions' on the same SQL link, they do not give you an ability to build up a transaction efficiently, and they don't do a whole lot of other things. In fact, to be extremely clear about the subject, persistent connections don't give you any functionality that wasn't possible with their non-persistent brothers.

Why?

This has to do with the way web servers work. There are three ways in which your web server can utilize PHP to generate web pages.

The first method is to use PHP as a CGI "wrapper". When run this way, an instance of the PHP interpreter is created and destroyed for every page request (for a PHP page) to your web server. Because it is destroyed after every request, any resources that it acquires (such as a link to an SQL database server) are closed when it is destroyed. In this case, you do not gain anything from trying to use persistent connections -- they simply don't persist.

The second, and most popular, method is to run PHP as a module in a multiprocess web server, which currently only includes Apache. A multiprocess server typically has one process (the parent) which coordinates a set of processes (its children) who actually do the work of serving up web pages. When each request comes in from a client, it is handed off to one of the children that is not already serving another client. This means that when the same client makes a second request to the server, it may be serviced by a different child process than the first time. What a persistent connection does for you in this case it make it so each child process only needs to connect to your SQL server the first time that it serves a page that makes use of such a connection. When another page then requires a connection to the SQL server, it can reuse the connection that child established earlier.

The last method is to use PHP as a plug-in for a multithreaded web server. Currently PHP 4 has support for ISAPI, WSAPI, and NSAPI (on Windows), which all allow PHP to be used as a plug-in on multithreaded servers like Netscape FastTrack (iPlanet), Microsoft's Internet Information Server (IIS), and O'Reilly's WebSite Pro. The behavior is essentially the same as for the multiprocess model described before. Note that SAPI support is not available in PHP 3.

If persistent connections don't have any added functionality, what are they good for?

The answer here is extremely simple -- efficiency. Persistent connections are good if the overhead to create a link to your SQL server is high. Whether or not this overhead is really high depends on many factors. Like, what kind of database it is, whether or not it sits on the same computer on which your web server sits, how loaded the machine the SQL server sits on is and so forth. The bottom line is that if that connection overhead is high, persistent connections help you considerably. They cause the child process to simply connect only once for its entire lifespan, instead of every time it processes a page that requires connecting to the SQL server. This means that for every child that opened a persistent connection will have its own open persistent connection to the server. For example, if you had 20 different child processes that ran a script that made a persistent connection to your SQL server, you'd have 20 different connections to the SQL server, one from each child.

Note, however, that this can have some drawbacks if you are using a database with connection limits that are exceeded by persistent child connections. If your database has a limit of 16 simultaneous connections, and in the course of a busy server session, 17 child threads attempt to connect, one will not be able to. If there are bugs in your scripts which do not allow the connections to shut down (such as infinite loops), the database with only 16 connections may be rapidly swamped. Check your database documentation for information on handling abandoned or idle connections.

Atenção

There are a couple of additional caveats to keep in mind when using persistent connections. One is that when using table locking on a persistent connection, if the script for whatever reason cannot release the lock, then subsequent scripts using the same connection will block indefinitely and may require that you either restart the httpd server or the database server. Another is that when using transactions, a transaction block will also carry over to the next script which uses that connection if script execution ends before the transaction block does. In either case, you can use register_shutdown_function() to register a simple cleanup function to unlock your tables or roll back your transactions. Better yet, avoid the problem entirely by not using persistent connections in scripts which use table locks or transactions (you can still use them elsewhere).

An important summary. Persistent connections were designed to have one-to-one mapping to regular connections. That means that you should always be able to replace persistent connections with non-persistent connections, and it won't change the way your script behaves. It may (and probably will) change the efficiency of the script, but not its behavior!

See also fbsql_pconnect(), ibase_pconnect(), ifx_pconnect(), imap_popen(), ingres_pconnect(), msql_pconnect(), mssql_pconnect(), mysql_pconnect(), OCIPLogon(), odbc_pconnect(), Ora_pLogon(), pfsockopen(), pg_pconnect(), and sybase_pconnect().


Capítulo 22. Safe Mode

The PHP safe mode is an attempt to solve the shared-server security problem. It is architecturally incorrect to try to solve this problem at the PHP level, but since the alternatives at the web server and OS levels aren't very realistic, many people, especially ISP's, use safe mode for now.


Security and Safe Mode

Tabela 22-1. Security and Safe Mode Configuration Directives

Name Default Changeable
safe_mode "0" PHP_INI_SYSTEM
safe_mode_gid "0" PHP_INI_SYSTEM
safe_mode_include_dir NULL PHP_INI_SYSTEM
safe_mode_exec_dir "" PHP_INI_SYSTEM
safe_mode_allowed_env_vars PHP_ PHP_INI_SYSTEM
safe_mode_protected_env_vars LD_LIBRARY_PATH PHP_INI_SYSTEM
open_basedir NULL PHP_INI_SYSTEM
disable_functions "" PHP_INI_SYSTEM
For further details and definition of the PHP_INI_* constants see ini_set().

Here is a short explanation of the configuration directives.

safe_mode boolean

Whether to enable PHP's safe mode. Read the Security and chapter for more information.

safe_mode_gid boolean

By default, Safe Mode does a UID compare check when opening files. If you want to relax this to a GID compare, then turn on safe_mode_gid. Whether to use UID (FALSE) or GID (TRUE) checking upon file access.

safe_mode_include_dir string

UID/GID checks are bypassed when including files from this directory and its subdirectories (directory must also be in include_path or full path must including).

As of PHP 4.2.0, this directive can take a semi-colon separated path in a similar fashion to the include_path directive, rather than just a single directory.

The restriction specified is actually a prefix, not a directory name. This means that "safe_mode_include_dir = /dir/incl" also allows access to "/dir/include" and "/dir/incls" if they exist. When you want to restrict access to only the specified directory, end with a slash. For example: "safe_mode_include_dir = /dir/incl/"

safe_mode_exec_dir string

If PHP is used in safe mode, system() and the other functions executing system programs refuse to start programs that are not in this directory.

safe_mode_allowed_env_vars string

Setting certain environment variables may be a potential security breach. This directive contains a comma-delimited list of prefixes. In Safe Mode, the user may only alter environment variables whose names begin with the prefixes supplied here. By default, users will only be able to set environment variables that begin with PHP_ (e.g. PHP_FOO=BAR).

Nota: If this directive is empty, PHP will let the user modify ANY environment variable!

safe_mode_protected_env_vars string

This directive contains a comma-delimited list of environment variables that the end user won't be able to change using putenv(). These variables will be protected even if safe_mode_allowed_env_vars is set to allow to change them.

open_basedir string

Limit the files that can be opened by PHP to the specified directory-tree, including the file itself. This directive is NOT affected by whether Safe Mode is turned On or Off.

When a script tries to open a file with, for example, fopen or gzopen, the location of the file is checked. When the file is outside the specified directory-tree, PHP will refuse to open it. All symbolic links are resolved, so it's not possible to avoid this restriction with a symlink.

The special value . indicates that the directory in which the script is stored will be used as base-directory.

Under Windows, separate the directories with a semicolon. On all other systems, separate the directories with a colon. As an Apache module, open_basedir paths from parent directories are now automatically inherited.

The restriction specified with open_basedir is actually a prefix, not a directory name. This means that "open_basedir = /dir/incl" also allows access to "/dir/include" and "/dir/incls" if they exist. When you want to restrict access to only the specified directory, end with a slash. For example: "open_basedir = /dir/incl/"

Nota: Support for multiple directories was added in 3.0.7.

The default is to allow all files to be opened.

disable_functions string

This directive allows you to disable certain functions for security reasons. It takes on a comma-dilimited list of function names. disable_functions is not affected by Safe Mode.

This directive must be set in php.ini For example, you cannot set this in httpd.conf.

See also: register_globals, display_errors, and log_errors

When safe_mode is on, PHP checks to see if the owner of the current script matches the owner of the file to be operated on by a file function. For example:
-rw-rw-r--    1 rasmus   rasmus       33 Jul  1 19:20 script.php 
-rw-r--r--    1 root     root       1116 May 26 18:01 /etc/passwd
Running this script.php
<?php
 readfile('/etc/passwd'); 
?>
results in this error when safe mode is enabled:
Warning: SAFE MODE Restriction in effect. The script whose uid is 500 is not 
allowed to access /etc/passwd owned by uid 0 in /docroot/script.php on line 2

However, there may be environments where a strict UID check is not appropriate and a relaxed GID check is sufficient. This is supported by means of the safe_mode_gid switch. Setting it to On performs the relaxed GID checking, setting it to Off (the default) performs UID checking.

If instead of safe_mode, you set an open_basedir directory then all file operations will be limited to files under the specified directory For example (Apache httpd.conf example):
<Directory /docroot>
  php_admin_value open_basedir /docroot 
</Directory>
If you run the same script.php with this open_basedir setting then this is the result:
Warning: open_basedir restriction in effect. File is in wrong directory in 
/docroot/script.php on line 2

You can also disable individual functions. Note that the disable_functions directive can not be used outside of the php.ini file which means that you cannot disable functions on a per-virtualhost or per-directory basis in your httpd.conf file. If we add this to our php.ini file:
disable_functions readfile,system
Then we get this output:
Warning: readfile() has been disabled for security reasons in 
/docroot/script.php on line 2


Functions restricted/disabled by safe mode

This is a still probably incomplete and possibly incorrect listing of the functions limited by safe mode.

Tabela 22-2. Safe mode limited functions

Function Limitations
dbmopen() Verifica se o(s) arquivo(s) e/ou diretório(s) que serão afetados por esta operação tem o mesmo UID (proprietário) do script que está sendo executado.
dbase_open() Verifica se o(s) arquivo(s) e/ou diretório(s) que serão afetados por esta operação tem o mesmo UID (proprietário) do script que está sendo executado.
filepro() Verifica se o(s) arquivo(s) e/ou diretório(s) que serão afetados por esta operação tem o mesmo UID (proprietário) do script que está sendo executado.
filepro_rowcount() Verifica se o(s) arquivo(s) e/ou diretório(s) que serão afetados por esta operação tem o mesmo UID (proprietário) do script que está sendo executado.
filepro_retrieve() Verifica se o(s) arquivo(s) e/ou diretório(s) que serão afetados por esta operação tem o mesmo UID (proprietário) do script que está sendo executado.
ifx_*() sql_safe_mode restrictions, (!= safe mode)
ingres_*() sql_safe_mode restrictions, (!= safe mode)
mysql_*() sql_safe_mode restrictions, (!= safe mode)
pg_loimport() Verifica se o(s) arquivo(s) e/ou diretório(s) que serão afetados por esta operação tem o mesmo UID (proprietário) do script que está sendo executado.
posix_mkfifo() Verifica se o diretório que será afetado por esta operação tem o mesmo UID (proprietário) do script qur está sendo executado.
putenv() Obeys the safe_mode_protected_env_vars and safe_mode_allowed_env_vars ini-directives. See also the documentation on putenv()
move_uploaded_file() Verifica se o(s) arquivo(s) e/ou diretório(s) que serão afetados por esta operação tem o mesmo UID (proprietário) do script que está sendo executado.
chdir() Verifica se o diretório que será afetado por esta operação tem o mesmo UID (proprietário) do script qur está sendo executado.
dl() Esta função é desabilitada no safe-mode
backtick operator Esta função é desabilitada no safe-mode
shell_exec() (functional equivalent of backticks) Esta função é desabilitada no safe-mode
exec() You can only execute executables within the safe_mode_exec_dir. For practical reasons it's currently not allowed to have .. components in the path to the executable.
system() You can only execute executables within the safe_mode_exec_dir. For practical reasons it's currently not allowed to have .. components in the path to the executable.
passthru() You can only execute executables within the safe_mode_exec_dir. For practical reasons it's currently not allowed to have .. components in the path to the executable.
popen() You can only execute executables within the safe_mode_exec_dir. For practical reasons it's currently not allowed to have .. components in the path to the executable.
mkdir() Verifica se o diretório que será afetado por esta operação tem o mesmo UID (proprietário) do script qur está sendo executado.
rmdir() Verifica se o(s) arquivo(s) e/ou diretório(s) que serão afetados por esta operação tem o mesmo UID (proprietário) do script que está sendo executado.
rename() Verifica se o(s) arquivo(s) e/ou diretório(s) que serão afetados por esta operação tem o mesmo UID (proprietário) do script que está sendo executado. Verifica se o diretório que será afetado por esta operação tem o mesmo UID (proprietário) do script qur está sendo executado.
unlink() Verifica se o(s) arquivo(s) e/ou diretório(s) que serão afetados por esta operação tem o mesmo UID (proprietário) do script que está sendo executado. Verifica se o diretório que será afetado por esta operação tem o mesmo UID (proprietário) do script qur está sendo executado.
copy() Verifica se o(s) arquivo(s) e/ou diretório(s) que serão afetados por esta operação tem o mesmo UID (proprietário) do script que está sendo executado. Verifica se o diretório que será afetado por esta operação tem o mesmo UID (proprietário) do script qur está sendo executado. (on source and target)
chgrp() Verifica se o(s) arquivo(s) e/ou diretório(s) que serão afetados por esta operação tem o mesmo UID (proprietário) do script que está sendo executado.
chown() Verifica se o(s) arquivo(s) e/ou diretório(s) que serão afetados por esta operação tem o mesmo UID (proprietário) do script que está sendo executado.
chmod() Verifica se o(s) arquivo(s) e/ou diretório(s) que serão afetados por esta operação tem o mesmo UID (proprietário) do script que está sendo executado. In addition, you cannot set the SUID, SGID and sticky bits
touch() Verifica se o(s) arquivo(s) e/ou diretório(s) que serão afetados por esta operação tem o mesmo UID (proprietário) do script que está sendo executado. Verifica se o diretório que será afetado por esta operação tem o mesmo UID (proprietário) do script qur está sendo executado.
symlink() Verifica se o(s) arquivo(s) e/ou diretório(s) que serão afetados por esta operação tem o mesmo UID (proprietário) do script que está sendo executado. Verifica se o diretório que será afetado por esta operação tem o mesmo UID (proprietário) do script qur está sendo executado. (note: only the target is checked)
link() Verifica se o(s) arquivo(s) e/ou diretório(s) que serão afetados por esta operação tem o mesmo UID (proprietário) do script que está sendo executado. Verifica se o diretório que será afetado por esta operação tem o mesmo UID (proprietário) do script qur está sendo executado. (note: only the target is checked)
getallheaders() In safe mode, headers beginning with 'authorization' (case-insensitive) will not be returned. Warning: this is broken with the aol-server implementation of getallheaders()!
header() In safe mode, the uid of the script is added to the realm part of the WWW-Authenticate header if you set this header (used for HTTP Authentication).
PHP_AUTH variables In safe mode, the variables PHP_AUTH_USER, PHP_AUTH_PW, and PHP_AUTH_TYPE are not available in $_SERVER. Regardless, you can still use REMOTE_USER for the USER. (note: only affected since PHP 4.3.0)
highlight_file(), show_source() Verifica se o(s) arquivo(s) e/ou diretório(s) que serão afetados por esta operação tem o mesmo UID (proprietário) do script que está sendo executado. Verifica se o diretório que será afetado por esta operação tem o mesmo UID (proprietário) do script qur está sendo executado. (note: only affected since PHP 4.2.1)
parse_ini_file() Verifica se o(s) arquivo(s) e/ou diretório(s) que serão afetados por esta operação tem o mesmo UID (proprietário) do script que está sendo executado. Verifica se o diretório que será afetado por esta operação tem o mesmo UID (proprietário) do script qur está sendo executado. (note: only affected since PHP 4.2.1)
Any function that uses php4/main/fopen_wrappers.c ??


Capítulo 23. Utilizando o PHP na linha de comando

A partir versão 4.3, o PHP suporta um novo tipo SAPI (Server Application Programming Interface) chamado CLI que significa Command Line Interface. Como o próprio nome indica, essa SAPI tem foco no desenvolvimento de aplicações shell (ou no terminal/linha de comando) com o PHP. As diferenças entre a CLI SAPI e as outras SAPIs são detalhadas neste capítulo.

A CLI SAPI foi liberada primeiramente com o PHP 4.2.0, mas ainda em estágio experimental, sendo necessário ativá-la explicitamente com a opção --enable-cli durante o ./configure. Desde o PHP 4.0.3 a CLI SAPI não mais é experimental e é sempre compilada e instalada como o arquivo php (chamado php.exe no Windows), no formato binário executável.

Diferenças importantes das CLI SAPI comparada com outras SAPIs:

  • Diferentemente da CGI SAPI, nenhum header é impresso na saída.

    A CGI SAPI possui um meio de suprimir os headers HTTP, mas não há uma chave equivalente para ativá-los na CLI SAPI.

    A versão CLI é definida silenciosa por padrão. Mas a chave -q é mantida para compatibilidade, de forma que você possa utilizar scripts CGI antigos.

    Ela não altera o diretório de execução para o do script. (a chave -C também é mantida para compatibilidade).

    Mensagens de erro em texto simples (sem formatação HTML).

  • Estas são as diretivas do php.ini que são sobrescritas pela CLI SAPI porque não fazem sentido no ambiente shell:

    Tabela 23-1. Diretivas php.ini sobrescritas

    Diretiva Valor default CLI SAPI Comentários
    html_errors FALSE Pode ser bem difícil de ler mensagens de erro no seu shell quando elas estão embebidas dentro de tags HTML, por isso essa diretiva tem default para FALSE.
    implicit_flush TRUE Essa diretiva causa que qualquer saída gerada de um print(), echo() e semelhantes sejam imediatamente escritas para o output e não cacheadas em nenhum buffer. Você ainda pode usar o output buffering se você precisa atrasar ou manipular a saída padrão.
    max_execution_time 0 (unlimited) Devido as infinitas possibilidades da utilização do PHP em ambientes shell, tempo máximo de execução foi configurado para ilimitado. Enquanto aplicações escritas para web são geralmente executadas em poucos segundos, aplicações no shell tendem a ter um tempo de execução mais longo.
    register_argc_argv TRUE As variáveis globais do PHP $argc (número de argumentos passados para aplicação) e $argv (array com os argumentos atuais) são sempre presentes e preenchidos com os valores apropriados quando utilizando a CLI SAPI.

    Nota: Estas diretivas não podem ser inicializadas com outros valores do arquivo de configuração php.ini ou um arquivo personalizado (se informado). Esta limitação existe porque estes valores são aplicados depois que todos os arquivos de configuração são analisados. Entretanto, seus valores podem ser modificados durante a execução (o que pode não fazer sentido para todas elas, por exemplo, register_argc_argv).

  • Para facilicar a operação no ambiente shell, as seguintes constantes estão definidas:

    Tabela 23-2. Constantes específicas CLI

    Constante Descrição
    STDIN Um stream já aberto para o stdin. Isto economiza ter de abrí-lo com
    $stdin = fopen('php://stdin', 'r');
    STDOUT Um stream já aberto para o stdout. Isto economiza ter de abrí-lo com
    $stdout = fopen('php://stdout', 'w');
    STDERR Um stream já aberto para o stderr. Isto economiza ter de abrí-lo com
    $stderr = fopen('php://stderr', 'w');

    Considerando isso, você não precisará mais abrí-los, por exemplo o stderr você mesmo, mas simplesmente usar a constante em vez do recurso stream:
    php -r 'fwrite(STDERR, "stderr\n");'
    Você não precissa fechar explicitamente esses streams. Isto é realizado automaticamente pelo PHP.

  • A CLI SAPI não modifica o diretório de execução atual para o diretório onde o script é interpretado!

    Exemplo mostrando a diferença da CGI SAPI:
    <?php
        /* Nossa aplicação de teste */
        echo getcwd(), "\n";
    ?>

    Quando utilizando a versão CGI, a saída é
    $ pwd
    /tmp
    
    $ php-cgi -f outro_diretorio/test.php
    /tmp/outro_diretorio
    Isto mostra como o PHP modifica o diretório atual para aquela onde o script é executado.

    Utilizando a versão CLI SAPI:
    $ pwd
    /tmp
    
    $ php -f outro_diretorio/test.php
    /tmp
    E isto mostra a grande flexibilidade ferramentas shell em PHP.

    Nota: A CGI SAPI suporta o comportamento da CLI SAPI utilizando a chave -C quando de sua execução na linha de comando.

A lista de opções de linha de comando fornecidas pelo binário do PHP pode ser solicitada a qualquer tempo executando o PHP com a opção -h:
Usage: php [options] [-f] <file> [args...]
       php [options] -r <code> [args...]
       php [options] [-- args...]
  -s               Display colour syntax highlighted source.
  -w               Display source with stripped comments and whitespace.
  -f <file>        Parse <file>.
  -v               Version number
  -c <path>|<file> Look for php.ini file in this directory
  -a               Run interactively
  -d foo[=bar]     Define INI entry foo with value 'bar'
  -e               Generate extended information for debugger/profiler
  -z <file>        Load Zend extension <file>.
  -l               Syntax check only (lint)
  -m               Show compiled in modules
  -i               PHP information
  -r <code>        Run PHP <code> without using script tags <?..?>
  -h               This help

  args...          Arguments passed to script. Use -- args when first argument
                   starts with - or script is read from stdin

A CLI SAPI fornecer três maneiras diferentes para você executar seu código PHP:

  1. Chamando o PHP para executar um arquivo determinado.

    php my_script.php
    
    php -f my_script.php
    De ambas maneiras (utilizando ou não a opção -f) o arquivo informado my_script.php é executado. Você pode escolher qualquer arquivo para executar, seus scripts PHP não precisam terminar com a extensão .php, podendo ter qualquer nome ou extensão que você deseje.

  2. Passar o código PHP para execução diretamente a linha de comando.

    php -r 'print_r(get_defined_constants());'
    É preciso ter especial cuidado com a substituição de variáveis shell e delimitação de strings utilizada.

    Nota: Leia o exemplo cuidadosamente, observando que não há tags de abertura ou fechamento! A opção -r simplesmente não precisa delas. Utilizando-as você obterá erros de interpretação.

  3. Fornece código PHP para interpretação via a entrada padrão (stdin).

    Isto mostra a habilidade poderosa de como criar dinamicamente código PHP e fornecê-lo ao binário, como demonstrado neste exemplo (apenas demonstrativo):
    $ alguma_aplicacao | algum_filtro | php | sort -u >final_output.txt

Você não pode combinar nenhum das três maneiras para executar código.

Assim como qualquer aplicação shell, não somente o binário do PHP aceita um certo número de argumentos, mas também seu script PHP também pode recebê-los. O número de argumentos que podem ser passados para seu script não é limitado ao PHP (mas o shell tem um certo limite de tamanho em caracteres que podem ser informados, e não há um padrão para esse limite). Os argumentos passados para seu script são disponibilizados no array global $argv. No índice zero sempre conterá o nome do script (podendo ser - no caso de código PHP estar vindo da entrada padrão ou da opção de linha de comando -r). O segunda variável global $argc contém o número de elementos no array $argv (mas não o número de argumentos passados para seu script.

Os argumentos que você deseja passar para seu script não podem começar com o caracter - e isso não pode ser modificado. Passando argumentos para seu script que comecem com um - causará problemas porque o PHP tentará manuseá-los. Para prevenir isso, utilize o separador de argumentos --. Depois que os argumentos são interpretados pelo PHP, todos os argumentos restantes são repassados intocados para seu script.

# Isto não executará o código fornecido e irá fazer o PHP mostrar sua ajuda
$ php -r 'var_dump($argv);' -h
Usage: php [options] [-f] <file> [args...]
[...]

# Isto passará o argumento '-h' para seu script e prevenirá o PHP de usá-lo
$ php -r 'var_dump($argv);' -- -h
array(2) {
  [0]=>
  string(1) "-"
  [1]=>
  string(2) "-h"
}

Entretanto, há ainda uma outra maneira de se utilizar o PHP no shell. Você pode escrever um script que na primeira linha tenha #!/usr/bin/php e na seqüência tenha código PHP normal, incluindo as tags de início e fim e os atributos de execução do arquivo. Desta maneira ele pode ser executado como um script shell ou PERL normalmente:
#!/usr/bin/php
<?php
    var_dump($argv);
?>
Assumindo que o arquivo foi nomeado como teste e está no diretório atual, nós podemos fazer o seguinte:
$ chmod 755 teste
$ ./test -h -- foo
array(4) {
  [0]=>
  string(6) "./teste"
  [1]=>
  string(2) "-h"
  [2]=>
  string(2) "--"
  [3]=>
  string(3) "foo"
}
Como você viu, dessa forma não há problemas em passar parâmetros para seu script que comecem com o caracter -

Tabela 23-3. Opções de linha de comando

Opção Descrição
-s

Mostra o código fonte com destaque de cores.

Esta opção usa o mecanismo interno para interpretar o arquivo e produzir uma versão HTML do fonte com destaque de cores e a envia para a saída padrão. Note que ele somente gerará blocos de <code> [...] </code>, mas não headers HTML.

Nota: Esta opção não funciona juntamente com a opção -r.

-w

Mostra o fonte sem comentários e espaços em branco.

Nota: Esta opção não funciona juntamente com a opção -r.

-f

Interpreta e executa o arquivo informado com a opção -f Esta diretiva é opcional e pode ser deixada de lado. Informar somente o nome do arquivo para execução é suficiente.

-v

Imprime as versões o PHP, PHP SAPI e Zend para a saída padrão, por exemplo:
$ php -v
PHP 4.3.0-dev (cli), Copyright (c) 1997-2002 The PHP Group
Zend Engine v1.2.1, Copyright (c) 1998-2002 Zend Technologies

-c

Esta opção informa um diretório onde procurar pelo php.ini ou especifica um arquivo INI personalizado diretamente (não presisa ser obrigatoriamente php.ini), por exemplo:
$ php -c /custom/directory/ my_script.php

$ php -c /custom/directory/custom-file.ini my_script.php

-a

Executa o PHP no modo interativo.

-d

Esta opção permite definir um valor personalizado para qualquer diretiva de configuração permitida no php.ini. Sintaxe:
-d diretiva[=valor]

Examples:
# Omitindo a parte do valor irá configurar a diretiva para "1"
$ php -d max_execution_time -r '$foo = ini_get("max_execution_time"); var_dump($foo);'
string(1) "1"

# Passando um valor vazio irá configurar a diretiva para ""
php -d max_execution_time= -r '$foo = ini_get("max_execution_time"); var_dump($foo);'
string(0) ""

# A diretiva de configuração será preenchida com qualquer coisa informada depois do caracter =''
$  php -d max_execution_time=20 -r '$foo = ini_get("max_execution_time"); var_dump($foo);'
string(2) "20"
$  php -d max_execution_time=instonaofazsentido -r '$foo = ini_get("max_execution_time"); var_dump($foo);'
string(15) "instonaofazsentido"

-e

Gera informações estendidas para o debugador/profiler.

-z

Carrega a extensão Zend. Se somente o nome de arquivo é fornecido, o PHP tenta carregar essa extensão do caminho default de bibliotecas do seu sistema (geralmente especificado em /etc/ld.so.conf em sistemas Linux). Passando um nome de arquivo com o caminho absoluto irá evitar a procura no caminho das bibliotecas de sistema. Um nome de arquivo com uma informação de diretório relativa fará com que o PHP apenas tente carregar a extensão no caminho relativo ao diretório atual.

-l

Esta opção fornece uma maneira conveniente apenas realizar uma checagem de sintaxe no código PHP fornecido. No sucesso, o texto No syntax errors detected in <arquivo> é impresso na saída padrão e informado o código de saida de sistema 0. Em caso de erro, o texto Errors parsing <filename> juntamente com o a mensagem do interpretador interno é impressa para a saída padrão e o código de saída de sistema é 255.

Esta opção não procura por erros fatais (como funções não definidas). Use -f se você deseja detectar erros fatais também.

Nota: Esta opção não trabalha com a opção -r

-m

Utilizando essa opção, o PHP imprime os módulos PHP e Zend compilados (e carregados):
$ php -m
[PHP Modules]
xml
tokenizer
standard
session
posix
pcre
overload
mysql
mbstring
ctype

[Zend Modules]

-i Esta opção de linha de comando chama a função phpinfo() e imprime seus resultados. Se o PHP não está funcionando bem, é interessante fazer um php -i para observar qualquer mensagem de erro impressa antes ou dentro das tabelas de informação. Como a saída é em HTML, ela é um pouco grande.
-r

Esta opção permite a execução de código PHP direto da linha de comando. As tags de início e fim do PHP (<?php e ?>) não são necessárias e causarão erros de interpretação.

Nota: Cuidados deverão ser tomados utilizando dessa forma para evitar que haja substituição de variáveis pelo shell.

Exemplo mostrando um erro de interpretação
$ php -r "$foo = get_defined_constants();"
Command line code(1) : Parse error - parse error, unexpected '='
O problema aqui decorre do sh/bash realizar substituições de variáveis sempre quando se utilizam aspas ("). Desde que a variável $foo não deve estar definida, ela é substituída por nada o que faz que o código passado para o PHP para execução seja:
$ php -r " = get_defined_constants();"
A maneira correta é utilizar apóstrofos ('). Variáveis em strings delimitadas por apóstrofos não são substituidas pelo sh/bash.
$ php -r '$foo = get_defined_constants(); var_dump($foo);'
array(370) {
  ["E_ERROR"]=>
  int(1)
  ["E_WARNING"]=>
  int(2)
  ["E_PARSE"]=>
  int(4)
  ["E_NOTICE"]=>
  int(8)
  ["E_CORE_ERROR"]=>
  [...]
Se você estiver utilizando um shell diferente do sh/bash, você pode experimentar comportamentos diferenciados. Sinta-se livre para abrir um aviso de bug ou enviar um e-mail para phpdoc@lists.php.net. Você vai rapidamente conseguir problemas quando tentar obter variáveis do ambiente dentro do código ou quando utilizar barras invertidas para escape. Esteja avisado.

-h Com essa opção, você pode obter informações sobre a lista atual de opções de linha de comando pequenas descrições sobre o que elas fazem.

O PHP executável pode ser utilizando para rodar scripts PHP absolutamente independente de um servidor web. Se você está num sistema Unix, você pode acrescentar uma linha especial na primeira linha de seu script e torná-lo executável, então o sistema operacional saberá que programa deverá rodar o script. Na plataforma Windows, você pode associar php.exe -q com o clique duplo em arquivos .php ou fazer um arquivo batch para rodar seus scripts através do PHP. A primeira linha acrescentada ao script nos Unix não funcionam no Windows, por isso você não pode escrever programas independentes de plataforma desse jeito. Um exemplo simples de como escrever um programa para a linha de comando segue abaixo:

Exemplo 23-1. Um script para rodar na linha de comando (script.php)

#!/usr/bin/php
<?php

if ($argc != 2 || in_array($argv[1], array('--help', '-help', '-h', '-?'))) {
?>

Este é um script de linha de comando com um parâmetro.

  Uso:
  <?php echo $argv[0]; ?> <opcao>

  <opcao> pode ser qualquer palavra que
  você queira imprimir. Com as opções --help, -help, -h
  ou -?, você pode obter essa ajuda.

<?php
} else {
    echo $argv[1];
}
?>

No script acima, nós utilizamos uma primeira linha especial para indicar que este arquivo precisa rodar pelo PHP. Como nós trabalhamos com a versão CLI aqui, não serão impressos headers HTTP. Há duas variáveis que você precisa conhecer para escrever aplicações em linha de comando com o PHP: $argc e $argv. O primeiro é o número de argumentos mais um (o nome do script executando). O segundo é um array contendo os argumentos, começando com o nome do script no índice zero ($argv[0]).

No programa acima é verificado se há apenas um argumento fornecido. Se o argumento for --help, -help, -h ou -?, é impresso uma mensagem de ajuda, imprimindo o nome do script dinamicamente. Qualquer outro argumento é exibido como informado.

Para rodar esse aplicativo nos Unix, basta torná-lo executável e o chamar diretamente como script.php exibaisso ou script.php -h. No Windows, você pode fazer um arquivo batch para esta tarefa:

Exemplo 23-2. Arquivo batch para rodar um script em linha de comando (script.bat)

@c:\php\php.exe script.php %1 %2 %3 %4

Assumindo que você nomeou o programa acima como script.php, e você tem um php.exe em c:\php\php.exe este arquivo batch irá rodar com os seguintes parâmetros: script.bat exibaisso ou script.bat -h.

Veja também a documentação da extensão Readline para mais funções que você pode usar para incrementar suas aplicações para linha de comando em PHP.

IV. Referência das Funções

Índice
I. Apache
II. Funções para manipulação de arrays
III. Aspell functions [deprecated]
IV. BCMath Funções Matemáticas de Precisão Arbitrária
V. Funções de compactação com Bzip2
VI. Calendar functions
VII. CCVS API Functions
VIII. COM support functions for Windows
IX. Classes e Objetos
X. ClibPDF functions
XI. Crack functions
XII. CURL, Client URL Library Functions
XIII. Cybercash payment functions
XIV. Crédit Mutuel CyberMUT functions
XV. Cyrus IMAP administration functions
XVI. Character type functions
XVII. Database (dbm-style) abstraction layer functions
XVIII. Funções data e hora
XIX. dBase functions
XX. DBM Functions [deprecated]
XXI. dbx functions
XXII. DB++ Functions
XXIII. Direct IO functions
XXIV. Diretórios
XXV. DOM XML functions
XXVI. .NET functions
XXVII. Error Handling and Logging Functions
XXVIII. FrontBase Functions
XXIX. filePro functions
XXX. Filesystem (Sistema de arquivos)
XXXI. Forms Data Format functions
XXXII. FriBiDi functions
XXXIII. FTP functions
XXXIV. Function Handling functions
XXXV. Gettext
XXXVI. GMP functions
XXXVII. HTTP functions
XXXVIII. Hyperwave functions
XXXIX. Hyperwave API functions
XL. iconv functions
XLI. Image functions
XLII. IMAP, POP3 and NNTP functions
XLIII. Informix functions
XLIV. InterBase functions
XLV. Ingres II functions
XLVI. IRC Gateway Functions
XLVII. PHP / Java Integration
XLVIII. LDAP functions
XLIX. Funções de E-Mail
L. mailparse functions
LI. Matemática e Trigonometria
LII. Multi-Byte String Functions
LIII. MCAL functions
LIV. Mcrypt Encryption Functions
LV. MCVE Payment Functions
LVI. Mhash - Funções de hash
LVII. Mimetype Functions
LVIII. Funções Microsoft SQL Server
LIX. Ming functions for Flash
LX. Funções de Miscelânea
LXI. mnoGoSearch Functions
LXII. mSQL functions
LXIII. MySQL
LXIV. Mohawk Software session handler functions
LXV. muscat functions
LXVI. Network Functions
LXVII. Ncurses terminal screen control functions
LXVIII. Lotus Notes functions
LXIX. Unified ODBC functions
LXX. Object Aggregation/Composition Functions
LXXI. Oracle 8 functions
LXXII. OpenSSL functions
LXXIII. Oracle functions
LXXIV. Ovrimos SQL functions
LXXV. Output Control Functions
LXXVI. Sobrecarga de propriedades e métodos de objetos
LXXVII. PDF functions
LXXVIII. Verisign Payflow Pro functions
LXXIX. PHP Options&Information
LXXX. POSIX functions
LXXXI. Funções para PostgreSQL
LXXXII. Process Control Functions
LXXXIII. Program Execution functions
LXXXIV. Printer functions
LXXXV. Pspell Functions
LXXXVI. GNU Readline
LXXXVII. GNU Recode functions
LXXXVIII. Regular Expression Functions (Perl-Compatible)
LXXXIX. qtdom functions
XC. Regular Expression Functions (POSIX Extended)
XCI. Semaphore, Shared Memory and IPC Functions
XCII. SESAM database functions
XCIII. Manejo de sessões
XCIV. Shared Memory Functions
XCV. Shockwave Flash functions
XCVI. SNMP functions
XCVII. Socket functions
XCVIII. Stream functions
XCIX. String functions
C. Funções Sybase
CI. Tokenizer functions
CII. Funções URL
CIII. Variable Functions
CIV. vpopmail functions
CV. W32api functions
CVI. WDDX Functions
CVII. XML parser functions
CVIII. XML-RPC functions
CIX. XSLT functions
CX. YAZ functions
CXI. YP/NIS Functions
CXII. Zip File Functions (Read Only Access)
CXIII. Funções de Compressão Zlib

I. Apache

Introdução

Estas funções estão somente disponíveis com o PHP rodando como módulo do Apache 1.x.


Instalação

Para instalar o PHP no Apache 1.x, veja a seção Apache no capítulo de instalação.


Configuração durante execução

O comportamento do módulo PHP sob o Apache é afetado pelas configurações no php.ini. As diretivas de configuração no php.ini podem ser sobrescritas por diretivas php_flag no arquivo de configuração do servidor ou por arquivos .htaccess locais.

Exemplo 1. Desligando a interpretação do PHP em um diretório com o .htaccess

php_flag engine off

Tabela 1. Opções de configuração no Apache

Nome Valor Default Alterabilidade Descrição
engine On PHP_INI_ALL liga ou desliga a interpretação pelo PHP
child_terminate Off PHP_INI_ALL especifica se os scripts PHP podem solicitar a eliminação do processo filho no final da requisição. Detalhes na função apache_child_terminate()
last_modified Off PHP_INI_ALL envia a data de modificação do script PHP como um header Last-Modified:
xbit_hack Off PHP_INI_ALL interpreta arquivos marcados executáveis como scripts PHP, independentemente do final do arquivo

Descrição resumida das diretivas de configuração.

engine boolean

Esta diretiva somente é útil para a versão módulo do Apache do PHP. Ela pode ser usada para ligar ou desligar a interpretação do PHP em nível de diretório ou em nível de servidor virtual. Colocando engine off nos lugares apropriados do arquivo httpd.conf, o PHP pode ser ativado ou desativado.


Tipos Resource

Esta extensão não possui nenhum tipo resource.


Constantes Predefinidas

Esta extensão não possui nenhuma constante.

Índice
apache_child_terminate -- Finaliza o processo Apache depois da requisição
apache_lookup_uri --  Realiza uma requisição parcial para a URI especificada e retorna todas as informações sobre ela
apache_note -- Obtém e seta notas de requisição
apache_request_headers -- Obtem todos os headers HTTP
apache_response_headers --  Obtêm todos os headers da resposta HTTP
apache_setenv -- Configura uma variável no ambiente do sub processo Apache
ascii2ebcdic -- Converte uma string de ASCII para EBCDIC
ebcdic2ascii -- Converte uma string de EBCDIC para ASCII
getallheaders -- Obtem todos os headers HTTP
virtual -- Realiza uma sub-requisição no Apache

apache_child_terminate

(PHP 4 >= 4.0.5)

apache_child_terminate -- Finaliza o processo Apache depois da requisição

Descrição

bool apache_child_terminate ( void)

apache_child_terminate() registrará o processo Apache executando a requisição atual do PHP para finalização quando a execução do código PHP terminar. Isto pode se utilizado para terminar um processo depois que um script que tiver um alto consumo de memória for rodado e quando essa memória normalmente só é liberada internamente, mas não é devolviva para o sistema operacional.

Nota: A disponibilidade desse recurso é controlado pela diretiva php.ini apache.child_terminate, que está definida off por default.

Este recurso não está disponível em versões multi-thread do Apache, como a versão para Windows 32 bits.

Veja também exit().

apache_lookup_uri

(PHP 3>= 3.0.4, PHP 4 )

apache_lookup_uri --  Realiza uma requisição parcial para a URI especificada e retorna todas as informações sobre ela

Descrição

object apache_lookup_uri ( string filename)

Isto realiza uma requisição parcial para uma URI. Trabalha o suficiente para obter todas as informações importantes sobre o recurso dado e retorna esta informação em uma classe. As propriedades da classe retornada são:

status
the_request
status_line
method
content_type
handler
uri
filename
path_info
args
boundary
no_cache
no_local_copy
allowed
send_bodyct
bytes_sent
byterange
clength
unparsed_uri
mtime
request_time

Nota: apache_lookup_uri() somente funciona quando o PHP está instalado como um módulo do Apache.

apache_note

(PHP 3>= 3.0.2, PHP 4 )

apache_note -- Obtém e seta notas de requisição

Descrição

string apache_note ( string note_name [, string note_value])

apache_note() é uma função específica do Apache que obtém e seta valores em uma tabela de notas de requisição. Se for chamada com um argumento, ela retorna o valor atual da nota note_name. Se for chamada com dois argumentos, ela seta o valor da nota note_name para note_value e retorna o valor anterior da nota note_name.

apache_request_headers

(PHP 4 >= 4.3.0)

apache_request_headers -- Obtem todos os headers HTTP

Descrição

array apache_request_headers ( void)

apache_request_headers() retorna um array associativo de todos os headers HTTP da requisição atual. Ela é somente suportada se o PHP roda como um módulo do Apache.

Nota: Antes do PHP 4.3.0, apache_request_headers() era chamado getallheaders(). Depois do PHP 4.3.0, getallheaders() é um sinônimo para apache_request_headers().

Exemplo 1. Exemplo apache_request_headers()

<?php
$headers = apache_request_headers();

foreach ($headers as $header => $value) {
    echo "$header: $value <br />\n";
}
?>

Nota: Você também pode obter o valor das variáveis CGI comuns lendo-as a partir do ambiente, o que funciona caso esteja ou não utilizando o PHP como módulo do Apache. Faça um phpinfo() para ver uma lista dessas variáveis chamadas variáveis ambiente.

apache_response_headers

(PHP 4 >= 4.3.0)

apache_response_headers --  Obtêm todos os headers da resposta HTTP

Descrição

array apache_response_headers ( void)

Retorna um array com todos os headers de resposta do Apache. Esta funcionalidade foi acrescentada a partir do PHP 4.3.0.

Veja também getallheaders() e headers_sent().

apache_setenv

(PHP 4 >= 4.2.0)

apache_setenv -- Configura uma variável no ambiente do sub processo Apache

Descrição

int apache_setenv ( string variable, string value [, bool walk_to_top])

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ascii2ebcdic

(PHP 3>= 3.0.17)

ascii2ebcdic -- Converte uma string de ASCII para EBCDIC

Descrição

int ascii2ebcdic ( string ascii_str)

ascii2ebcdic() é uma função específica do Apache, somente disponível em sistemas operacionais baseados no EBCDIC (OS/390, BS2000). Ela converte a string codificada em ASCII ascii_str em sua representação equivalente em EBCDIC (binary safe), retornando o resultado.

Veja também a função inversa ebcdic2ascii()

ebcdic2ascii

(PHP 3>= 3.0.17)

ebcdic2ascii -- Converte uma string de EBCDIC para ASCII

Description

int ebcdic2ascii ( string ebcdic_str)

ebcdic2ascii() é uma função específica do Apache, somente disponível em sistemas operacionais baseados no EBCDIC (OS/390, BS2000). Ela converte a string codificada em EBCDIC ebcdic_str em sua representação equivalente em ASCII (binary safe), retornando o resultado.

Veja também a função inversa ascii2ebcdic()

getallheaders

(PHP 3, PHP 4 )

getallheaders -- Obtem todos os headers HTTP

Descrição

array getallheaders ( void)

getallheaders() é um sinônimo para apache_request_headers(). Ela retorna um array associativo de todos os headers HTTP da requisição atual. Veja a documentação de apache_request_headers() para mais detalhes do funcionamento dessa função.

Nota: No PHP 4.3.0, getallheaders() se tornou um apelido de apache_request_headers(). Essencialmente, ela foi renomeada. Isto porque a função somente funciona quando o PHP é compilado com um módulo do Apache.

Veja também apache_request_headers().

virtual

(PHP 3, PHP 4 )

virtual -- Realiza uma sub-requisição no Apache

Descrição

int virtual ( string filename)

virtual() é uma função específica do Apache que é equivalente a <!--#include virtual...--> no mod_include. Ela realiza uma sub-requisição do Apache. Ela é útil para incluir scripts de CGI ou arquivos .shtml, ou qualquer outra coisa que você possa analisar através do Apache. Note que para um script CGI, o script precisa gerar um cabeçalho CGI válido. Isto significa que, no mínimo, ele precisa gerar um cabeçalho Content-type. Para arquivos PHP, você precisa usar include() ou require(). virtual() não pode ser usado para incluir um documento que é um arquivo PHP.

Para executar a sub-requisição, todos osbuffer são finalizados e enviados para o browser. Headers pendentes são enviados também.

II. Funções para manipulação de arrays

Introdução

Essas funções permitem a interação e manipulação de arrays de várias formas. Arrays são essenciais para armazenar, gerenciar, operar sobre um conjunto de variáveis.

Arrays simples e multidimensionais (matrizes) são suportados, e podem ser criados pelo usuário ou por outras funções. Existem diversas funções específicas para bancos de dados para preencher arrays com os dados retornados em consultas, e vários outros tipos de funções também retornam arrays.

Por favor, veja a seção Arrays do manual para uma explicação mais detalhada sobre como arrays são implementados e utilizados no PHP.


Requisitos

Nenhuma biblioteca externa é necessária para compilar esta extensão.


Instalação

Não há nenhuma instalação nescessária para utilizar estas funções, elas fazem parte do núcleo do PHP.


Configuração durante execução

Esta extenção não define nenhum parâmetro de configuração no php.ini.


Tipos Resource

Esta extensão não possui nenhum tipo resource.


Constantes Predefinidas

As constantes listadas abaixo estão sempre disponíveis como parte do núcleo do PHP.

CASE_LOWER (integer)

CASE_LOWER é usada com a função array_change_key_case() e é usada em chaves de arrays para torná-las minúsculas. É o valor padrão utilizado em array_change_key_case().

CASE_UPPER (integer)

CASE_UPPER é usada com a função array_change_key_case() e é usada em chaves de arrays para torná-las maiúsculas.

Sinais de ordenação:

SORT_ASC (integer)

SORT_ASC é usada com array_multisort() para ordenar em ordem crescente.

SORT_DESC (integer)

SORT_DESC é usada com array_multisort() para ordenar em ordem descrescente

Sinais de tipos de ordenação: usadas por várias funções de ordenação

SORT_REGULAR (integer)

SORT_REGULAR é usada para comparar itens normalmente.

SORT_NUMERIC (integer)

SORT_NUMERIC é usada para comparar itens numericamente.

SORT_STRING (integer)

SORT_STRING é usada para comparar itens como se fossem strings.


Veja Também

Veja também is_array(), explode(), implode(), split(), preg_split() e join().

Índice
array_change_key_case -- Retorna um array com todas as chaves string em maiúsculo ou minúsculo
array_chunk -- Divide um array em pedaços
array_count_values -- Conta as frequências de cada valor de um array
array_diff_assoc -- Computes the difference of arrays with additional index check
array_diff -- Analisa as diferenças entre arrays
array_fill -- Preenche um array com valores
array_filter --  Filtra os elementos de um array utilizando uma função
array_flip -- Inverte as relações entre chaves e valores
array_intersect_assoc -- Computes the intersection of arrays with additional index check
array_intersect -- Calcula a interseção entre arrays
array_key_exists -- Checa se uma chave ou índice existe em um array
array_keys -- Retorna todas as chaves de um array
array_map --  Aplica uma função em todos os elementos dos arrays dados
array_merge_recursive -- Funde dois ou mais arrays recursivamente
array_merge -- Funde dois ou mais arrays
array_multisort -- Ordena múltiplos arrays ou arrays multi-dimensionais
array_pad --  Expande um array para um certo comprimento utilizando um determinado valor
array_pop -- Retira um elemento do final do array
array_push --  Adiciona um ou mais elementos no final de um array
array_rand --  Retorna um ou mais elementos aleatórios de um array
array_reduce --  Reduz um array para um único valor através de um processo iterativo utilizando uma função.
array_reverse --  Retorna um array com os elementos na ordem inversa
array_search --  Procura por um valor em um array e retorna sua chave correspondente caso seja encontrado
array_shift --  Retira o primeiro elemento de um array
array_slice -- Extrai uma parcela de um array
array_splice --  Remove uma parcela do array e substitui com outros elementos
array_sum --  Calcula a soma dos elementos de um array
array_unique -- Remove o valores duplicados de um array
array_unshift --  Adiciona um ou mais elementos no início de um array
array_values -- Retorna todos os valores de um array
array_walk --  Aplica uma determinada funcão em cada elemento de um array
array --  Cria um array
arsort --  Ordena um array em ordem descrescente mantendo a associação entre índices e valores
asort --  Ordena um array mantendo a associação entre índices e valores
compact --  Cria um array contendo variáveis e seus valores
count -- Conta o número de elementos de uma variável
current -- Retorna o elemento corrente em um array
each --  Retorna o par chave/valor corrente de um array e avança o seu cursor
end --  Faz o ponteiro interno de um array apontar para o seu último elemento
extract --  Importa variáveis para a tabela de símbolos a partir de um array
in_array -- Retorna TRUE se um valor existe no array
key -- Retorna uma chave de um array associativo
krsort -- Ordena um array pelas chaves em ordem descrescente
ksort -- Ordena um array pelas chaves
list --  Cria variáveis como se fossem arrays
natcasesort --  Ordena um array utilizando o algoritmo da "ordem natural" sem diferenciar maiúsculas e minúsculas
natsort --  Ordena um array utilizando o algoritmo da "ordem natural"
next --  Avança o ponteiro interno de um array
pos -- Retorna o elemento atual do array
prev -- Retrocede o ponteiro interno de um array
range --  Cria um array contendo uma faixa de elementos
reset --  Faz o ponteiro interno de um array apontar para o seu primeiro elemento
rsort -- Ordena um array em ordem descrescente
shuffle -- Mistura os elementos de um array
sizeof -- Retorna o número de elementos de uma variável
sort -- Ordena um array
uasort --  Ordena um array utilizando uma função de comparação definida pelo usuário e mantendo as associações entre chaves e valores
uksort --  Ordena um array pelas chaves utilizando uma função de comparação definida pelo usuário.
usort --  Ordena um array pelos valores utilizando uma função de comparação definida pelo usuário

array_change_key_case

(PHP 4 >= 4.2.0)

array_change_key_case -- Retorna um array com todas as chaves string em maiúsculo ou minúsculo

Descrição

array array_change_key_case ( array input [, int case])

array_change_key_case() altera as chaves chaves do array input para maiúsculo ou minúsculo. A mudança depende do último parâmetro (opcional) case. Você pode passar duas constantes para ele, CASE_UPPER e CASE_LOWER. O padrão é CASE_LOWER. Essa função deixará os índices numéricos inalterados.

Exemplo 1. Exemplo de array_change_key_case()

$input_array = array("primeiRo" => 1, "segunDo" => 4);
print_r(array_change_key_case($input_array, CASE_UPPER);

A saída deste programa será:
Array
(
    [PRIMEIRO] => 1
    [SEGUNDO] => 2
)

array_chunk

(PHP 4 >= 4.2.0)

array_chunk -- Divide um array em pedaços

Descrição

array array_chunk ( array input, int size [, bool preserve_keys])

array_chunk() divide um array em diversos arrays tendo como tamanho o valor de size. Você provavelmente terá um array com menos valores no final. Serão gerados arrays como membros de um array multidimensional com índices numéricos começando de 0 (zero).

Passando o valor TRUE para o parâmetro opcional preserve_keys, pode-se forçar a preservação das chaves do array original. Se for passado o valor FALSE, novos índices numéricos serão gerados em cada array resultante começando de 0 (zero). O padrão é FALSE.

Exemplo 1. Exemplo de array_chunk()

$input_array = array('a', 'b', 'c', 'd', 'e');
print_r(array_chunk($input_array, 2));
print_r(array_chunk($input_array, 2, TRUE));

A saída deste programa será:
Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
        )

    [1] => Array
        (
            [0] => c
            [1] => d
        )

    [2] => Array
        (
            [0] => e
        )

)
Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
        )

    [1] => Array
        (
            [2] => c
            [3] => d
        )

    [2] => Array
        (
            [4] => e
        )

)

array_count_values

(PHP 4 )

array_count_values -- Conta as frequências de cada valor de um array

Descrição

array array_count_values ( array input)

array_count_values() retorna um array utilizando os valores do array input como chaves e seus respectivos números de ocorrências como valores.

Exemplo 1. Exemplo de array_count_values()

$array = array (1, "ola", 1, "mundo", "ola");
array_count_values ($array);

Array
(
    [1] => 2
    [ola] => 2
    [mundo] => 1
)

array_diff_assoc

(PHP 4 >= 4.3.0)

array_diff_assoc -- Computes the difference of arrays with additional index check

Description

array array_diff_assoc ( array array1, array array2 [, array ...])

array_diff_assoc() returns an array containing all the values from array1 that are not present in any of the other arguments. Note that the keys are used in the comparison unlike array_diff().

Exemplo 1. array_diff_assoc() example

<?php
$array1 = array ("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array ("a" => "green", "yellow", "red");
$result = array_diff_assoc ($array1, $array2);

/* The result is:
Array
(
    [b] => brown
    [c] => blue
    [0] => red
)
*/
?>

In our example above you see the "a" => "green" pair is present in both arrays and thus it is not in the ouput from the function. Unlike this, the pair 0 => "red" is in the ouput because in the second argument "red" has key which is 1.

Two values from key => value pairs are considered equal only if (string) $elem1 === (string) $elem2 . In other words a strict check takes place so the string representations must be the same.

Nota: Please note that this function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using, for example, array_diff_assoc($array1[0], $array2[0]);.

See also array_diff(), array_intersect(), and array_intersect_assoc().

array_diff

(PHP 4 >= 4.0.1)

array_diff -- Analisa as diferenças entre arrays

Descrição

array array_diff ( array array1, array array2 [, array ...])

array_diff() retorna um array contendo todos os valores de array1 que não estão presentes em nenhum dos outros argumentos. Note que as chaves são preservadas.

Exemplo 1. Exemplo de array_diff()

$array1 = array ("a" => "verde", "vermelho", "azul", "vermelho");
$array2 = array ("b" => "verde", "amarelo", "vermelho");
$result = array_diff ($array1, $array2);

O exemplo acima faz com que $result seja array ("azul");. Ocorrências multiplas em $array1 são tratados da mesma forma.

Nota: Dois elementos são considerados iguais se, e somente se, (string) $elem1 === (string) $elem2. Em palavras: quando a representação em string é a mesma.

Nota: Note que esta função faz compara apenas uma dimensão de um array com dimensão n. Mas, obviamente, você pode comparar outras dimensões usando array_diff($array1[0], $array2[0]);.

Atenção

Não estava funcionando no PHP 4.0.4!

Veja também array_intersect().

array_fill

(PHP 4 >= 4.2.0)

array_fill -- Preenche um array com valores

Descrição

array array_fill ( int start_index, int num, mixed value)

array_fill() preenche um array com o número de entradas igual a num com o valor do parâmetro value, e chaves começando a partir de start_index.

Exemplo 1. Exemplo de array_fill()

$a = array_fill(5, 6, 'banana');

/*
$a agora tem os seguintes valores:

$a[5]  = "banana";
$a[6]  = "banana";
$a[7]  = "banana";
$a[8]  = "banana";
$a[9]  = "banana";
$a[10] = "banana";
*/

array_filter

(PHP 4 >= 4.0.6)

array_filter --  Filtra os elementos de um array utilizando uma função

Descrição

array array_filter ( array input [, mixed callback])

array_filter() retorna um array contendo todos os elementos do array input filtrados de acordo com uma função aplicada. Se o array input for associativo, as chaves são preservadas.

Exemplo 1. Exemplo de array_filter()

function impar($var) {
    return ($var % 2 == 1);
}

function par($var) {
    return ($var % 2 == 0); 
}

$array1 = array ("a" => 1, "b" => 2, "c" => 3, "d" => 4, "e" => 5);
$array2 = array (6, 7, 8, 9, 10, 11, 12);

echo "Impares: \n";
print_r(array_filter($array1, "impar"));
echo "Pares: \n";
print_r(array_filter($array2, "par"));

A saída deste programa seria:
Impares:
Array
(
    [a] => 1
    [c] => 3
    [e] => 5
)
Pares:
Array
(
    [0] => 6
    [2] => 8
    [4] => 10
    [6] => 12
)

As funções utilizadas por array_filter() não devem alterar os valores do array.. Por exemplo, adicionar ou remover um elemento, pode apagar o array ao qual está sendo aplicada array_filter(). Se este array for alterado, o comportamento desta função se torna imprevisvel.

Veja também array_map() e array_reduce().

array_flip

(PHP 4 )

array_flip -- Inverte as relações entre chaves e valores

Descrições

array array_flip ( array trans)

array_flip() retorna um array com com a relação entre suas chaves e valores invertida, ou seja, as chaves de trans passam a ser os valores e os valores de trans passam a ser as chaves.

Note que os valores de trans devem ser chaves válidas, ou seja, eles precisam ser inteiros não negativos ou string. Um aviso será mostrado se um valor é de um tipo inválido para chaves, e o par chave/valor em questão não será invertido.

Se um valor tem várias ocorrências, a última chave será usada como valor, e todos os outros serão perdidos.

array_flip() retorna FALSE se falhar.

Exemplo 1. Exemplo de array_flip()

$trans = array_flip ($trans);
$original = strtr ($str, $trans);

Exemplo 2. Exemplo de array_flip() : colisão

$trans = array ("a" => 1, "b" => 1, "c" => 2);
$trans = array_flip ($trans);
print_r($trans);

Agora $trans é:
Array
(
    [1] => b
    [2] => c
)

array_intersect_assoc

(PHP 4 >= 4.3.0)

array_intersect_assoc -- Computes the intersection of arrays with additional index check

Description

array array_intersect_assoc ( array array1, array array2 [, array ...])

array_intersect_assoc() returns an array containing all the values of array1 that are present in all the arguments. Note that the keys are used in the comparison unlike in array_intersect().

Exemplo 1. array_intersect_assoc() example

<?php
$array1 = array ("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array ("a" => "green", "yellow", "red");
$result_array = array_intersect_assoc ($array1, $array2);

/* $result_array will look like:

Array
(
    [a] => green
)

*/
?>

In our example you see that only the pair "a" => "green" is present in both arrays and thus is returned. The value "red" is not returned because in $array1 it's key is 2 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) $elem2 . In otherwords a strict type check is executed so the string representation must be the same.

See also array_intersect(), array_diff() and array_diff_assoc().

array_intersect

(PHP 4 >= 4.0.1)

array_intersect -- Calcula a interseção entre arrays

Descrição

array array_intersect ( array array1, array array2 [, array ...])

array_intersect() retorna um array contendo todos os valores de array1 que estão presentes nos outros argumentos. Note que as chaves são preservadas.

Exemplo 1. Exemplo de array_intersect()

$array1 = array ("a" => "verde", "vermelho", "azul");
$array2 = array ("b" => "verde", "amarelo", "vermelho");
$result = array_intersect ($array1, $array2);

Isso faz com que $result tenha
Array
(
    [a] => verde
    [0] => vermelho
)

Nota: Dois elementos são considerados iguais se, e somente se, (string) $elem1 === (string) $elem2. Em palavras: quando a representação em string é a mesma.

Atenção

Essa função não funcionava no PHP 4.0.4!

Veja também array_diff().

array_key_exists

(PHP 4 >= 4.1.0)

array_key_exists -- Checa se uma chave ou índice existe em um array

Descrição

bool array_key_exists ( mixed key, array search)

array_key_exists() retorna TRUE se a chave key existe no array. key pode ser qualquer valor possível para uma chave de array.

Exemplo 1. Exemplo de array_key_exists()

$busca_array = array("primeiro" => 1, "segundo" => 4);
if (array_key_exists("primeiro", $busca_array)) {
    echo "O elemento 'primeiro' está no array!";
}

Nota: O nome dessa função é key_exists() no PHP versão 4.0.6.

Veja também isset().

array_keys

(PHP 4 )

array_keys -- Retorna todas as chaves de um array

Descrição

array array_keys ( array input [, mixed search_value])

array_keys() retorna as chaves, numéricas e string, do array input.

Se o parâmetro opcional search_value for especificado, então apenas as chaves para esse valor serão retornadas. Do contrário, todas as chaves de input serão retornadas.

Exemplo 1. Exemplo de array_keys()

$array = array (0 => 100, "cor" => "vermelho");
print_r(array_keys ($array));

$array = array ("azul", "vermelho", "verde", "azul", "azul");
print_r(array_keys ($array, "azul")); 

$array = array ("cor" => array("azul", "vermelho", "verde"), "tamanho" => array("pequeno", "medio", "grande"));
print_r(array_keys ($array));

A saída deste programa seria:
Array
(
    [0] => 0
    [1] => cor
)
Array
(
    [0] => 0
    [1] => 3
    [2] => 4
)
Array
(
    [0] => cor
    [1] => tamanho
)

Nota: Essa função adicionada no PHP 4. Abaixo está uma implementação para aqueles que ainda usam PHP 3.

Exemplo 2. Implementação de array_keys() para usuários do PHP 3

function array_keys ($arr, $term="") {
    $t = array();
    while (list($k,$v) = each($arr)) {
        if ($term && $v != $term) {
            continue;
            $t[] = $k;
        }
        return $t;
    }
}

Veja também array_values().

array_map

(PHP 4 >= 4.0.6)

array_map --  Aplica uma função em todos os elementos dos arrays dados

Descrição

array array_map ( mixed callback, array arr1 [, array arr2...])

array_map() retorna um array contendo todos os elementos de arr1 depois de aplicada uma determinada função em cada um. O número de parâmetros que esta função aceita deve coincidir com o número de arrays passados para a array_map()

Exemplo 1. Exemplo de array_map()

<?php
function cubo($n) {
    return $n*$n*$n;
}

$a = array(1, 2, 3, 4, 5);
$b = array_map("cubo", $a);
print_r($b);
?>

E programa acima faz com que $b tenha:
Array
(
    [0] => 1
    [1] => 8
    [2] => 27
    [3] => 64
    [4] => 125
)

Exemplo 2. array_map() - usando mais de um array

<?php
function mostrar_Espanhol($n, $m) {
    return "O número $n é chamado de $m na Espanha";
}

function map_Espanhol($n, $m) {
    return array ($n => $m);
}

$a = array(1, 2, 3, 4, 5);
$b = array("uno", "dos", "tres", "cuatro", "cinco");

$c = array_map("mostrar_Espanhol", $a, $b);
print_r($c);

$d = array_map("map_Espanhol", $a , $b);
print_r($d);
?>

Resultará em:
// Saída de $c
Array
(
    [0] => O número 1 é chamado de uno na Espanha
    [1] => O número 2 é chamado de dos na Espanha
    [2] => O número 3 é chamado de tres na Espanha
    [3] => O número 4 é chamado de cuatro na Espanha
    [4] => O número 5 é chamado de cinco na Espanha
)

// Saída de $d
Array
(
    [0] => Array
        (
            [1] => uno
        )

    [1] => Array
        (
            [2] => dos
        )

    [2] => Array
        (
            [3] => tres
        )

    [3] => Array
        (
            [4] => cuatro
        )

    [4] => Array
        (
            [5] => cinco
        )

)

Normalmente quando se usa dois ou mais arrays, eles devem ter o mesmo tamanho porque a função callback é aplicada paralelamente nos elementos correpondentes. Se os arrays tem tamanhos diferentes, o menor array será extendido com elementos vazios.

Uma forma interessante de se usar esta função é na construção de um array de arrays, o que pode ser facilmente feito usando NULL como o nome da função callback.

Exemplo 3. Criando um array de arrays

<?php
$a = array(1, 2, 3, 4, 5);
$b = array("um", "dois", "tres", "quatro", "cinco");
$c = array("uno", "dos", "tres", "cuatro", "cinco");

$d = array_map(null, $a, $b, $c);
print_r($d);
?>

A saída do programa acima seria:
Array
(
    [0] => Array
        (
            [0] => 1
            [1] => one
            [2] => uno
        )

    [1] => Array
        (
            [0] => 2
            [1] => two
            [2] => dos
        )

    [2] => Array
        (
            [0] => 3
            [1] => three
            [2] => tres
        )

    [3] => Array
        (
            [0] => 4
            [1] => four
            [2] => cuatro
        )

    [4] => Array
        (
            [0] => 5
            [1] => five
            [2] => cinco
        )

)

Veja também array_filter(), array_reduce() e array_walk().

array_merge_recursive

(PHP 4 >= 4.0.1)

array_merge_recursive -- Funde dois ou mais arrays recursivamente

Descrição

array array_merge_recursive ( array array1, array array2 [, array ...])

array_merge_recursive() funde os elementos de dois ou mais arrays de forma que os elementos de um são colocados no final do array anterior. Retorna o array resultante da fusão.

Se os arrays dados tem as mesmas chaves string, então os valores para uma chave são fundidos em um array, e isso é feito recursivamente, sendo que, se um dos valores for um array também, este função irá fundi-lo com os valores correspondentes no array resultante também. Se, no entanto, os arrays tem as mesmas chaves numéricas, o último valor para uma chave não sobrescreverá o valor original, e sim adicionado ao array resultante.

Exemplo 1. Exemplo de array_merge_recursive()

$ar1 = array ("cor" => array ("favorita" => "vermelho"), 5);
$ar2 = array (10, "cor" => array ("favorita" => "verde", "azul"));
$result = array_merge_recursive ($ar1, $ar2);

Neste caso $result será:
Array
(
    [color] => Array
        (
            [favorita] => Array
                (
                    [0] => vermelho
                    [1] => verde
                )

            [0] => azul
        )

    [0] => 5
    [1] => 10
)

Veja também array_merge().

array_merge

(PHP 4 )

array_merge -- Funde dois ou mais arrays

Descrição

array array_merge ( array array1, array array2 [, array ...])

array_merge() funde os elementos dois ou mais arrays de forma que os elementos de um são colocados no final do array anterior. Retorna o array resultante da fusão.

Se os arrays dados têm as mesmas chaves string, então o último valor para uma chave irá sobrescrever o valor anterior. Se, no entanto, os arrays tem as mesmas chaves numéricas, o último valor para uma chave não sobrescreverá o valor original, e sim adicionado ao array resultante.

Exemplo 1. Exemplo de array_merge()

$array1 = array ("cor" => "vermelho", 2, 4);
$array2 = array ("a", "b", "cor" => "verde", "forma" => "trapezoide", 4);
$result = array_merge ($array1, $array2);

Neste caso $result será:
Array
(
    [cor] => verde
    [0] => 2
    [1] => 4
    [2] => a
    [3] => b
    [forma] => trapezoide
    [4] => 4
)

Exemplo 2. Exemplo simples de array_merge()

$array1 = array();
$array2 = array(1 => "data");
$result = array_merge($array1, $array2);

Não esqueça que as chaves numéricas serão reordenadas!
Array
(
    [0] => data
)

Se você quer preservar os arrays e apenas concatená-los, o operador +:
$array1 = array();
$array2 = array(1 => "data");
$result = $array1 + $array2;
As chaves numéricas serão preservadas e as associações originais permanecem.
Array
(
    [1] => data
)

Nota: Chaves coincidentes serão sobrescritas usando as regras de primeira ocorrência.

Veja também array_merge_recursive().

array_multisort

(PHP 4 )

array_multisort -- Ordena múltiplos arrays ou arrays multi-dimensionais

Descrição

bool array_multisort ( array ar1 [, mixed arg [, mixed ... [, array ...]]])

array_multisort() pode ser usada para ordenar vários arrays de uma vez ou apenas um array multi-dimensional de acordo com uma das dimensões. A associação entre chaves e valores é mantida.

Os arrays dados são tratados como colunas de uma tabela a ser classificada pelas linhas - isso lembra a funcionalidade da cláusula ORDER BY da SQL. O primeiro array é o principal na ordenação. As linhas (valores) no primeiro array serve de base para a ordenação do próximo, e assim por diante.

A estrutura de argumentos dessa função não é muito normal, mas bastante flexível. O primeiro argumento de todos deve ser um array. Subsequentemente, cada argumento pode ser um array ou um dos sinais de classificação da lista a seguir.

Sinais de ordem de classificação:

  • SORT_ASC - classifica na ordem crescente

  • SORT_DESC - classifica na ordem descrescente

Sinais de tipos de ordenação:

  • SORT_REGULAR - compara os elementos normalmente

  • SORT_NUMERIC - compara os elementos como itens numéricos

  • SORT_STRING - compara os elementos como strings

Não podem existir dois sinais de ordenação do mesmo tipo especificados para um mesmo array. Os sinais de ordenação especificados depois de um array se aplicam apenas para esse array - a eles são atribuídos por padrão os valores SORT_ASC e SORT_REGULAR depois de cada novo argumento do tipo array.

Retorna TRUE em caso de sucesso ou FALSE em falhas.

Exemplo 1. Ordenando múltiplos arrays

$ar1 = array ("10", 100, 100, "a");
$ar2 = array (1, 3, "2", 1);
array_multisort ($ar1, $ar2);

Nesse exemplo, depois da ordenação, o primeiro array terá 10, "a", 100, 100. O segundo conterá 1, 1, "2", 3. Os elementos do segundo array que correpondem aos do primeiro (100 e 100) também foram ordenados.

Exemplo 2. Ordenando um array multi-dimensional

$ar = array (array ("10", 100, 100, "a"), array (1, 3, "2", 1));
array_multisort ($ar[0], SORT_ASC, SORT_STRING, 
                 $ar[1], SORT_NUMERIC, SORT_DESC);

Nesse exemplo, depois da ordenação, o primeiro array terá 10, 100, 100, "a" (foi ordenado como strings em ordem crescente), e o segundo conterá 1, 3, "2", 1 (classificado como números, em ordem descrescente).

array_pad

(PHP 4 )

array_pad --  Expande um array para um certo comprimento utilizando um determinado valor

Descrição

array array_pad ( array input, int pad_size, mixed pad_value)

array_pad() retorna uma cópia de input expandido para o comprimento especificado por pad_size com o valor pad_value. Se pad_size for positivo então o array é expandido pela direita, se for negativo, pela esquerda. Se o valor absoluto de pad_size for menor ou igual ao comprimento de input, então ele permanece inalterado.

Exemplo 1. Exemplo de array_pad()

$input = array (12, 10, 9);

$result = array_pad ($input, 5, 0);
// $result é array (12, 10, 9, 0, 0)

$result = array_pad ($input, -7, -1);
// $result é array (-1, -1, -1, -1, 12, 10, 9)

$result = array_pad ($input, 2, "noop");
// Não será expandido

array_pop

(PHP 4 )

array_pop -- Retira um elemento do final do array

Descrição

mixed array_pop ( array array)

array_pop() retira e retorna o último elemento de array, diminuindo array em um elemento. Se array estiver vazio (ou se não for um array), o valor NULL é retornado.

Exemplo 1. Exemplo de array_pop()

$cesta = array ("laranja", "banana", "melancia", "morango");
$fruta = array_pop ($cesta);

Depois disso, $cesta terá 3 elementos:
Array
(
    [0] => laranja
    [1] => banana
    [2] => melancia
)
e morango será passado para $fruta.

Atenção

Esta função pode retornar o booleano FALSE, mas também pode retornar um valor não-booleano que pode ser avaliado como FALSE, como 0 ou "". Leia a seção em Booleanos para maiores informações. Utilize o operador === para testar o valor retornado por esta função.

Veja também array_push(), array_shift(), e array_unshift().

array_push

(PHP 4 )

array_push --  Adiciona um ou mais elementos no final de um array

Descrição

int array_push ( array array, mixed var [, mixed ...])

array_push() trata array como uma pilha, e adiciona as variáveis passadas como argumentos no final de array. O comprimento de array aumenta de acordo com o número de variáveis adicionadas. Tem o mesmo efeito de:
$array[] = $var;
repetido para cada argumento var.

Retorna o novo número de elementos do array.

Exemplo 1. Exemplo de array_push()

$cesta = array ("laranja", "morango");
array_push ($cesta, "melancia", "batata");

Neste caso $stack teria os seguintes elementos:
Array
(
    [0] => laranja
    [1] => morango
    [2] => melancia
    [3] => batata
)

Veja também: array_pop(), array_shift(), e array_unshift().

array_rand

(PHP 4 )

array_rand --  Retorna um ou mais elementos aleatórios de um array

Descrição

mixed array_rand ( array input [, int num_req])

array_rand() é bastante útil quando se quer conseguir aleatoriamente um ou mais elementos de um array. Ela recebe o array input e outro argumento opcional num_req o qual especifica quantos elementos se quer conseguir - se não for especificado, o padrão é 1.

Se estiver pegando apenas um elemento, array_rand() retorna a chave para este elemento aleatório. De outra forma, ele retorna um array com as chaves desses elementos aleatórios. Assim é possível conseguir chaves e valores aleatórios a partir da mesma função.

Não esqueça de chamar a função srand() para disparar o gerador de números aleatórios.

Exemplo 1. Exemplo de array_rand()

srand ((float) microtime() * 10000000);
$input = array ("Neo", "Morpheus", "Trinity", "Cypher", "Tank");
$rand_keys = array_rand ($input, 2);
print $input[$rand_keys[0]]."\n";
print $input[$rand_keys[1]]."\n";

array_reduce

(PHP 4 >= 4.0.5)

array_reduce --  Reduz um array para um único valor através de um processo iterativo utilizando uma função.

Descrição

mixed array_reduce ( array input, mixed callback [, int initial])

array_reduce() aplica iterativamente a função definida em callback nos elementos de input, de forma a reduzi-lo a um único valor. Se o argumento opcional initial for passado, ele será utilizado no início do processo, ou como um resultado final se o array estiver vazio.

Exemplo 1. Exemplo de array_reduce()

function soma($v, $w) {
    $v += $w;
    return $v;
}

function multiplicacao($v, $w) {
    $v *= $w;
    return $v;
}

$a = array(1, 2, 3, 4, 5);
$x = array();
$b = array_reduce($a, "soma");
$c = array_reduce($a, "multiplicacao", 10);
$d = array_reduce($x, "soma", 1);

Isso resultará em $b contendo 15, $c contendo 1200 (= 1*2*3*4*5*10), e $d contendo 1.

Veja também array_filter(), array_map().

array_reverse

(PHP 4 )

array_reverse --  Retorna um array com os elementos na ordem inversa

Descrição

array array_reverse ( array array [, bool preserve_keys])

array_reverse() recebe o argumento array e retorna um novo array com a ordem dos elementos invertida, preservando as chaves se o argumento preserve_keys for TRUE.

Exemplo 1. Exemplo de array_reverse()

$input = array ("php", 4.0, array ("verde", "vermelho"));
$result = array_reverse ($input);
$result_keyed = array_reverse ($input, TRUE);

O programa acima fará com que $result e $result_keyed tenham os mesmos elementos, mas note a diferença entre as chaves. A saída de $result e $result_keyed será:
Array
(
    [0] => Array
        (
            [0] => verde
            [1] => vermelho
        )

    [1] => 4
    [2] => php
)
Array
(
    [2] => Array
        (
            [0] => verde
            [1] => vermelho
        )

    [1] => 4
    [0] => php
)

Nota: O segundo argumento foi adicionado no PHP 4.0.3.

array_search

(PHP 4 >= 4.0.5)

array_search --  Procura por um valor em um array e retorna sua chave correspondente caso seja encontrado

Descrição

mixed array_search ( mixed needle, array haystack [, bool strict])

Procura em haystack pelo valor needle e retorna sua chave se for encontrado no array, e FALSE em caso contrário.

Nota: A partir do PHP 4.2.0, array_search() retorna NULL em caso de falha ao invés de FALSE.

Se o terceiro parâmetro opcional strict for passado como TRUE então array_search() também fará uma checagem de tipos de needle em haystack.

Atenção

Esta função pode retornar o booleano FALSE, mas também pode retornar um valor não-booleano que pode ser avaliado como FALSE, como 0 ou "". Leia a seção em Booleanos para maiores informações. Utilize o operador === para testar o valor retornado por esta função.

Veja também array_keys() e in_array().

array_shift

(PHP 4 )

array_shift --  Retira o primeiro elemento de um array

Descrição

mixed array_shift ( array array)

array_shift() retira o primeiro elemento de array e o retorna, diminuindo array em um elemento e movendo todos os outros elementos para trás. Todas as chaves numéricas alteradas para começar a contar a de 0 (zero), enquanto chaves string permanecerão inalteradas. Se array estiver vazio (ou se não for um array), o valor NULL é retornado.

Exemplo 1. Exemplo de array_shift()

$cesta = array ("laranja", "banana", "melancia", "morango");
$fruta = array_shift ($cesta);

O programa acima resultaria em $stack tendo 3 elementos:
Array
(
    [0] => banana
    [1] => melancia
    [2] => morango
)
e laranja seria passado para $fruta.

Veja também array_unshift(), array_push() e array_pop().

array_slice

(PHP 4 )

array_slice -- Extrai uma parcela de um array

Descrição

array array_slice ( array array, int offset [, int length])

array_slice() retorna a sequência de elementos de array especificada pelos parâmetros offset e length.

Se offset for positivo, a sequência começará do início de array. Se offset for negativo, a sequência começará dessa distância do final de array.

Se length for especificado e positivo, então a sequência terá essa quantidade de elementos. Se length for especificado e negativo então a sequência pará dessa quantidade elementos a partir do final do array. Se for omitido, então a sequência terá todos os elementos a partir de offset até o final de array.

Note que array_slice() ignorará chaves e irá calcular os inícios e comprimentos dos intervalos baseada na posição absoluta dos elementos no array.

Exemplo 1. Exemplos de array_slice()

$input = array ("a", "b", "c", "d", "e");

$output = array_slice ($input, 2);      // retorna "c", "d", e "e"
$output = array_slice ($input, 2, -1);  // retorna "c", "d"
$output = array_slice ($input, -2, 1);  // retorna "d"
$output = array_slice ($input, 0, 3);   // retorna "a", "b", e "c"

Veja também array_splice().

array_splice

(PHP 4 )

array_splice --  Remove uma parcela do array e substitui com outros elementos

Descrição

array array_splice ( array input, int offset [, int length [, array replacement]])

array_splice() remove a sequência de elementos do array input especificados por offset e length, e os substitui com os elementos do array replacement, se for especificado. Retorna um array contendo os elementos removidos.

Se offset for positivo então o começo da região a ser removida será nessa posição a partir do início do array input. Se offset for negativo então o ínicio será dessa distância do final de input.

Se length for omitido, todos os elementos a partir de offset até o final do array serão removidos. Se length for especificado e positivo, então essa quantidade de elementos será removida. Se length for especificado e negativo então o final da região a ser removida será dessa quantidade de elementos a partir do final do array. Dica: para remover todos elementos a partir de offset até o final do array quando replacement também é especificado, use count($input) para o argumento length.

Se o array replacement for especificado, então os elementos removidos serão substituidos pelo elementos desse array. Se offset e length são dados de forma que nada será removido, então os elementos de replacement serão inseridos no lugar especificado por offset. Dica: se a substituição for de apenas um elemento então não será necessário colocar array() para ele, a não ser que elementos seja um array.

As seguintes equivalências abaixo são válidas:
array_push ($input, $x, $y)     array_splice ($input, count ($input), 0, 
                                             array ($x, $y))
array_pop ($input)              array_splice ($input, -1)
array_shift ($input)            array_splice ($input, 0, 1)
array_unshift ($input, $x, $y)  array_splice ($input, 0, 0, array ($x, $y))
$input[$x] = $y                 array_splice ($input, $x, 1, $y)

Retorna um array contendo os elementos removidos.

Exemplo 1. Exemplos de array_splice()

$input = array ("vermelho", "verde", "azul", "amarelo");
array_splice ($input, 2);      
// $input será agora array ("vermelho", "verde")

$input = array ("vermelho", "verde", "azul", "amarelo");
array_splice ($input, 1, -1);  
// $input será agora array ("vermelho", "amarelo")

$input = array ("vermelho", "verde", "azul", "amarelo");
array_splice ($input, 1, count($input), "laranja");  
// $input será agora array ("vermelho", "laranja")

$input = array ("vermelho", "verde", "azul", "amarelo");
array_splice ($input, -1, 1, array("preto", "marrom")); 
// $input será agora array ("vermelho", "verde", "azul", "preto", "marrom")

Veja também array_slice().

array_sum

(PHP 4 >= 4.0.4)

array_sum --  Calcula a soma dos elementos de um array

Descrição

mixed array_sum ( array arr)

array_sum() retorna a soma dos valores de um array como inteiro ou real.

Exemplo 1. Exemplos de array_sum()

$a = array(2, 4, 6, 8);
echo "soma(a) = ".array_sum($a)."\n";

$b = array("a" => 1.2, "b" => 2.3, "c" => 3.4);
echo "soma(b) = ".array_sum($b)."\n";

A saída do programa acima seria:
soma(a) = 20
soma(b) = 6.9

Nota: Até a versão 4.0.6 do PHP, o array em si é modificado e converte strings para valores numéricos (as quais na maioria das vezes é convertida para zero a depender dos seus valores).

array_unique

(PHP 4 >= 4.0.1)

array_unique -- Remove o valores duplicados de um array

Descrição

array array_unique ( array array)

array_unique() recebe o argumento array e retorna um novo array sem valores duplicados.

Note que as chaves são preservadas. array_unique() ordena inicialmente os valores como strings mantendo a primeira chave encontrada para cada valor, e ignorando as chaves encontradas posteriormente. Isso não significa que a chave do primeiro valor do array ainda desordenado será mantido.

Nota: Dois elementos são considerados iguais se, e somente se, (string) $elem1 === (string) $elem2. Em palavras: quando a represetação em string é a mesma.

O primeiro será usado.

Atenção

Essa função não funcionava no PHP 4.0.4!

Exemplo 1. Exemplo de array_unique()

$input = array ("a" => "verde", "vermelho", "b" => "verde", "azul", "vermelho");
$result = array_unique ($input);
print_r($result);

A saída seria:
Array
(
    [b] => verde
    [1] => azul
    [2] => vermelho
)

Exemplo 2. array_unique() e tipos

$input = array (4, "4", "3", 4, 3, "3");
$result = array_unique ($input);
var_dump($result);

A saída do programa acima seria (PHP 4.0.6):
array(2) {
  [3]=> 
  int(4)
  [4]=> 
  int(3)
}

array_unshift

(PHP 4 )

array_unshift --  Adiciona um ou mais elementos no início de um array

Descrição

int array_unshift ( array array, mixed var [, mixed ...])

array_unshift() adiciona os elementos passados como argumentos no início de array. Note que a lista de elementos é adicionada como um todo, de forma que eles ficam na mesma ordem. Todas as chaves numéricas serão modificadas para começar a contar de 0 (zero) enquanto chaves strings permanecerão inalteradas.

Retorna o novo número de elementos de array.

Exemplo 1. Exemplo de array_unshift()

$cesta = array ("laranja", "banana");
array_unshift ($cesta, "melancia", "morango");

O programa acima resultaria em $queue contendo os seguintes elementos:
Array
(
    [0] => melancia
    [1] => morango
    [2] => laranja
    [3] => banana
)

Veja também array_shift(), array_push() e array_pop().

array_values

(PHP 4 )

array_values -- Retorna todos os valores de um array

Descrição

array array_values ( array input)

array_values() retorna todos os valores do array input.

Exemplo 1. Exemplo de array_values()

$array = array ("tamanho" => "G", "cor" => "dourado");
print_r(array_values ($array));

A saída seria:
Array
(
    [0] => G
    [1] => dourado
)

Nota: Essa função foi adicionada no PHP 4, abaixo segue uma implementação para aqueles que ainda usam PHP 3.

Exemplo 2. Implementação de array_values() para PHP 3 users

function array_values ($arr) {
    $t = array();
    while (list($k, $v) = each ($arr)) {
        $t[] = $v;
    }
    return $t;
}

Veja também array_keys().

array_walk

(PHP 3>= 3.0.3, PHP 4 )

array_walk --  Aplica uma determinada funcão em cada elemento de um array

Descrição

int array_walk ( array arr, string func [, mixed userdata])

Aplica uma função definida pelo usuário nomeada pelo argumento func em cada elemento de arr. Normalmente, func recebe dois argumentos: o primeiro é o valor do elemento e o segundo, sua chave. Se userdata for especificado, ele será usado como terceiro argumento da função do usuário.

Se func necessita de mais argumentos do que o que está sendo passado para ela, um erro do nível E_WARNING será gerado a cada vez que array_walk() executar func. Esses avisos podem ser suprimidos adicionando o operador @ à chamada da função array_walk(), ou usando error_reporting().

Nota: Se func precisar alterar realmente os valores do array, especifique que o primeiro parâmetro de func deve ser passado por referência. Então qualquer mudança feita nesses elementos serão feitas no próprio array também.

Nota: A passagem das chaves e do terceiro argumento para func foi adicionada no PHP 4.0.0.

array_walk() não é afetada pelo ponteiro interno do array arr. array_walk() irá percorrer todo o array independente da posição atual do ponteiro interno. Para reiniciar o ponteiro, use reset(). No PHP 3, array_walk() reinicia o ponteiro.

Usuários não podem alterar o array a partir da função definida para ser usada. Por exemplo, adicionar/remover elementos, removerá o array no qual array_walk() está sendo aplicada. Se o array for alterado, o comportamento desta função se torna imprevisível.

Exemplo 1. Exemplo de array_walk()

<?php
$frutas = array ("d" => "limao", "a" => "laranja", "b" => "banana", "c" => "melancia");

function test_alter (&$item1, $key, $prefix) {
    $item1 = "$prefix: $item1";
}

function test_print ($item2, $key) {
    echo "$key. $item2<br>\n";
}

echo "Antes ...:\n";
array_walk ($frutas, 'test_print');

array_walk ($frutas, 'test_alter', 'fruta');
echo "... e depois:\n";

array_walk ($frutas, 'test_print');
?>

A saída do programa acima seria:
Antes ...:
d. limao
a. laranja
b. banana
c. melancia
... e depois:
d. fruit: limao
a. fruit: laranja
b. fruit: banana
c. fruit: melancia

Veja também array_map(), list(), foreach, each() e call_user_func_array().

array

(PHP 3, PHP 4 )

array --  Cria um array

Descrição

array array ( [mixed ...])

Retorna um array a partir dos valores fornecidos. Índices podem ser atribuidos aos valores através do operador =>.

Nota: array() é uma estrutura utilizada para representar literais de arrays, e não uma função.

A sintaxe "index => values", separados por vírgulas, definem índice e valores respectivamente. O índice por de ser do tipo string ou numérico. Quando o índice é omitido, um índice numérico inteiro é automaticamente gerado, começando do 0. Se o índice é um inteiro, o próximo índice a ser gerado será igual ao maior índice inteiro + 1. Note que quando dois índices idênticos são definidos, o último sobrescreve o primeiro.

O exemplo a seguir demonstra como criar um array com duas dimensões, como especificar chaves em arrays associativos, e como definir índices numéricos em arrays normais.

Exemplo 1. Exemplo de array()

$frutas = array (
    "frutas"  => array ("a"=>"laranja", "b"=>"banana", "c"=>"melancia"),
    "numeros" => array (1, 2, 3, 4, 5, 6),
    "buracos"   => array ("primeiro", 5 => "segundo", "terceiro")
);

Exemplo 2. Indexação automática com array()

$array = array( 1, 1, 1, 1,  1, 8 => 1,  4 => 1, 19, 3 => 13);
print_r($array);

vai mostrar :
Array 
(
    [0] => 1
    [1] => 1
    [2] => 1
    [3] => 13
    [4] => 1
    [8] => 1
    [9] => 19
)

Note que o índice 3 é definido duas vezes, e retêm seu último valor 13. O índice 4 é definido depois do índice 8, e o índice gerado depois dele foi 9, uma vez que o maior índice era 8.

Esse exemplo cria um array com o índices a partir do 1.

Exemplo 3. Array com índices a partir do 1 com array()

$trimestre  = array(1 => 'Janeiro', 'Fevereiro', 'Marco');
print_r($trimestre);

vai mostrar :
Array 
(
    [1] => 'Janeiro'
    [2] => 'Fevereiro'
    [3] => 'Marco'
)

Veja também array_pad(), list() e range().

arsort

(PHP 3, PHP 4 )

arsort --  Ordena um array em ordem descrescente mantendo a associação entre índices e valores

Descrição

void arsort ( array array [, int sort_flags])

Esta função ordena um array de forma que a correlação entre índices e valores é mantida. É usada principalmente para ordenar arrays associativos onde a ordem dos elementos é um fator importante.

Exemplo 1. Exemplo de arsort()

$frutas = array ("d" => "limao", "a" => "laranja", "b" => "banana", "c" => "melancia");
arsort ($frutas);
reset ($frutas);
while (list ($chave, $valor) = each ($frutas)) {
    echo "$chave = $valor\n";
}

A saída deste exemplo seria:
c = melancia
d = limao
a = laranja
b = banana

As frutas foram ordenadas na ordem alfabética inversa, e os índices associados a cada valor foram mantidos.

Você pode modificar o comportamento da ordenação usando o parâmetro opcional sort_flags, para mais detalhes veja sort().

Veja também: asort(), rsort(), ksort() e sort().

asort

(PHP 3, PHP 4 )

asort --  Ordena um array mantendo a associação entre índices e valores

Descrição

void asort ( array array [, int sort_flags])

Essa função ordena um array de forma que a correlação entre índices e valores é mantida. É usada principalmente para ordenar arrays associativos onde a ordem dos elementos é um fator importante.

Exemplo 1. Exemplo de asort()

$frutas = array ("d" => "limao", "a" => "laranja", "b" => "banana", "c" => "melancia");
asort ($frutas);
reset ($frutas);
while (list ($chave, $valor) = each ($frutas)) {
    echo "$chave = $valor\n";
}

A saída desse programa seria:
b = banana
a = laranja
d = limao
c = melancia

As frutas foram ordenadas na ordem alfabética, e os índices associados a cada valor foram mantidos.

Você pode modificar o comportamento da ordenação usando o parâmetro opcional sort_flags, para mais detalhes veja sort().

veja também arsort(), rsort(), ksort() e sort().

compact

(PHP 4 )

compact --  Cria um array contendo variáveis e seus valores

Descrição

array compact ( mixed varname [, mixed ...])

compact() recebe um número variável de parâmetros. Cada parâmetro pode ser tanto uma string contendo o nome da variável, como um array com nomes de variáveis. Sendo um array, ele pode conter outros arrays de nomes de variáveis; compact() trata isso recursivamente.

Para cada um dos parâmetros passados, compact() procura uma variável com o nome especificado na tabela de símbolos e a adiciona no array de saída de forma que o nome da variável será a chave e o seu conteúdo será o valor para esta chave. Em resumo, ela faz o oposto de extract(). Retorna um array de saída com todas as variáveis adicionadas a ele.

Qualquer string com nome de uma variável que não exista será simplesmente ignorada.

Exemplo 1. Exemplo de compact()

$cidade = "Sao Paulo";
$estado = "SP";
$evento = "SIGGRAPH";

$localidade = array ("cidade", "estado");

$result = compact ("evento", "nada_aqui", $localidade);

Depois disso, $result será:
Array
(
    [evento] => SIGGRAPH
    [cidade] => Sao Paulo
    [estado] => SP
)

Veja também extract().

count

(PHP 3, PHP 4 )

count -- Conta o número de elementos de uma variável

Descrição

int count ( mixed var)

Retorna o número de elementos de var, que normalmente é um array (uma vez que qualquer outra coisa terá apenas um elemento).

Se var não for um array, 1 será retornado (excessão: count(NULL) retorna 0).

Atenção

count() pode retornar 0 para uma variável que não existe, mas também pode retornar 0 para uma variável que tenha sido inicializada como um array vazio. Use isset() para checar se a variável existe.

Por favor, veja a sessão Arrays do manual para uma explicação mais detalhada sobre como os arrays são implementados e utilizados no PHP.

Exemplo 1. Exemplo de count()

$a[0] = 1; 
$a[1] = 3; 
$a[2] = 5; 
$result = count ($a);
// $result == 3

$b[0] = 7;
$b[5] = 9;
$b[10] = 11;
$result = count ($b);
// $result == 3;

Nota: A função sizeof() é um alias para count().

Veja também is_array(), isset() e strlen().

current

(PHP 3, PHP 4 )

current -- Retorna o elemento corrente em um array

Descrição

mixed current ( array array)

Todo array tem um ponteiro interno para o elemento "atual", o qual é inicializado para apontar para o primeiro elemento inserido em um array.

A função current() simplesmente retorna o elemento do array para o qual esse ponteiro interno está apontando. Não move o ponteiro de forma alguma. Se o ponteiro interno estiver apontando para além do final da lista de elementos, current() retorna FALSE.

Atenção

Se o array contêm elementos vazios (0 ou "", uma string vazia) então esta função retorna FALSE para esses elementos. Isso faz com que seja impossível determinar se você está realmente no final da lista de elementos de um array usando current(). Para percorrer devidamente um array que pode conter elementos vazios, use a função each().

Veja também end(), next(), prev() e reset().

each

(PHP 3, PHP 4 )

each --  Retorna o par chave/valor corrente de um array e avança o seu cursor

Descrição

array each ( array array)

Retorna o par chave/valor corrente de array e avança o seu cursor. Esse par é retornado num array de quatro elementos, com as chaves 0, 1, key, e value. Os elementos 0 e key contêm o nome da chave do elemento do array, e 1 e value contêm o valor.

Se o cursor interno do array estiver apontando para além do final do array, each() retorna FALSE.

Exemplo 1. Exemplos de each()

$foo = array ("bob", "fred", "jussi", "jouni", "egon", "marliese");
$bar = each ($foo);

$bar agora contém os seguintes pares de chaves e valores:

  • 0 => 0
  • 1 => 'bob'
  • key => 0
  • value => 'bob'
$foo = array ("Robert" => "Bob", "Seppo" => "Sepi");
$bar = each ($foo);

$bar agora contém os seguintes pares de chaves e valores:

  • 0 => 'Robert'
  • 1 => 'Bob'
  • key => 'Robert'
  • value => 'Bob'

each() é tipicamente usada em conjunto com list() para percorrer um array; por exemplo, $_POST:

Exemplo 2. Percorrendo $HTTP_POST_VARS usando each()

echo "Valores submetidos pelo método POST:<br>";
reset ($_POST);
while (list ($chave, $valor) = each ($_POST)) {
    echo "$chave => $valor<br>";
}

Depois da execução de each(), o cursor interno do array vai apontar para o prócimo elemento do array, ou no último elemento se ele chegar ao final do array. Você deve usar reset() se quiser percorrer o array novamente.

Veja também key(), list(), current(), reset(), next(), prev() e foreach.

end

(PHP 3, PHP 4 )

end --  Faz o ponteiro interno de um array apontar para o seu último elemento

Descrição

mixed end ( array array)

end() avança o ponteiro interno de array até o seu último elemento, e retorna esse elemento.

Exemplo 1. Exemplo simples de end()

<?php

  $frutas = array('melancia','banana','morango');
    
  print end($frutas); // morango
?>

Veja também current(), each(), end(), next() e reset().

extract

(PHP 3>= 3.0.7, PHP 4 )

extract --  Importa variáveis para a tabela de símbolos a partir de um array

Descrição

int extract ( array var_array [, int extract_type [, string prefix]])

Essa função é usada para importar variáveis a partir de um array para a tabela de símbolos corrente. Recebe o array associativo var_array e trata as suas chaves como os nomes das variáveis e os valores como valores das variáveis. Para cada par chave/valor ele criará uma variável na tabela de símbolos corrente, seguindo os parâmetros extract_type e prefix.

Nota: Desde a versão 4.0.5, essa função retorna o número de variáveis extraídas.

Nota: EXTR_IF_EXISTS e EXTR_PREFIX_IF_EXISTS foram adicionadas na versão 4.2.0.

Nota: EXTR_REFS foi adicionada na versão 4.3.0.

extract() checa se cada chave do array constitui um nome de variável válido e por colisões com as variáveis já existentes na tabela de símbolos. O modo com que chaves inválidas ou númericas e colisões são tratadas é determinado pelo argumento extract_type. Esse argumento pode receber os seguintes valores:

EXTR_OVERWRITE

Se houver uma colisão, sobrescreve a variável existente.

EXTR_SKIP

Se houver uma colisão, não sobrescreve a variável existente.

EXTR_PREFIX_SAME

Se houver uma colisão, adiciona um prefixo ao nome da variável definido pelo argumento prefix.

EXTR_PREFIX_ALL

Adiciona um prefixo ao nome de todas as variáveis definido por prefix. Desde o PHP 4.0.5 estão incluídos nomes numéricos.

EXTR_PREFIX_INVALID

Adiciona um prefixo definido por prefix apenas para variáveis como nomes inválidos ou numéricos. Essa opção foi adicionada no PHP 4.0.5.

EXTR_IF_EXISTS

Só sobrescreve a variável se ela já existe na tabela de símbolos corrente, caso contrário, não faz nada. Isso é útil quando se quer definir uma lista de variáveis válidas e então extrair só as que foram definidas em $_REQUEST, por exemplo. Essa opção foi adicionada no PHP 4.2.0.

EXTR_PREFIX_IF_EXISTS

Só cria nomes de variáveis usando o prefixo se na tabela de símbolos já existe uma variável com o nome sem esse prefixo. Essa opção foi adicionada no PHP 4.2.0.

EXTR_REFS

Extrai variáveis como referências, ou seja, os valores das variáveis importadas ainda estarão referenciando os valores do parâmetro var_array. Essa opção pode ser usada sozinha ou em conjunto com as outras usando o operador 'ou' em extract_type. Essa opação foi adicionada no PHP 4.3.0.

Se extract_type não for especificado, é assumido o valor EXTR_OVERWRITE por padrão.

Note que prefix só é necessário se extract_type for EXTR_PREFIX_SAME, EXTR_PREFIX_ALL, ou EXTR_PREFIX_INVALID, EXTR_PREFIX_INVALID ou EXTR_IF_EXISTS. Se o nome com o prefixo não for um nome de variável válido, ela não será importada para a tabela de símbolos.

extract() retorna o número de variáveis importadas com sucesso para a tabela de símbolos.

Uma possível utilização de extract() e na importação de variáveis contidas num array associativo retornado pela função wddx_deserialize().

Exemplo 1. Exemplo de extract()

<?php

/* Suponha que $var_array é um array retornado pela função
   wddx_deserialize */

$tamanho = "grande";
$var_array = array ("cor" => "azul",
                    "tamanho"  => "medio",
                    "forma" => "esfera");
extract ($var_array, EXTR_PREFIX_SAME, "wddx");

print "$cor, $tamanho, $forma, $wddx_tamanho\n";

?>

O exemplo acima produziria:
azul, grande, esfera, medio

O $tamanho não foi sobrescrito, porque nós especificamos EXTR_PREFIX_SAME, o que resultou na criação da variável $wddx_tamanho. Se EXTR_SKIP fosse utilizado, então $wddx_tamanho não seria criada. EXTR_OVERWRITE teria feito com que $tamanho tivesse o valor "medio", e EXTR_PREFIX_ALL resultaria em novas variáveis com os nomes $wddx_cor, $wddx_tamanho, e $wddx_forma.

Você deve usar um array associativo, um array indexado numericamente não produzirá resultados.

Veja também compact().

in_array

(PHP 4 )

in_array -- Retorna TRUE se um valor existe no array

Descrição

bool in_array ( mixed needle, array haystack [, bool strict])

Procura em haystack pelo valor needle e retorna TRUE se este valor for encontrado no array, e FALSE em caso contrário.

Se o terceiro parâmetro strict for TRUE então in_array() também irá checar os tipos de needle em haystack.

Nota: Se needle for uma string, a comparação é feita diferenciando caracteres maiúsculos e minúsculos.

Nota: Em versões do PHP mais antigas que 4.2.0 needle não pode ser um array.

Exemplo 1. Exemplo de in_array()

$os = array ("Mac", "NT", "Irix", "Linux");
if (in_array ("Irix", $os)) {
    print "Tem Irix";
}
if (in_array ("mac", $os)) {
    print "Tem mac";
}

A segunda condicional falha pois in_array() diferencia letras minúsculas e maiúsculas. Então, a saída seria:
Tem Irix

Exemplo 2. in_array() com checagem de tipos

<?php
$a = array('1.10', 12.4, 1.13);

if (in_array('12.4', $a, TRUE))
    echo "'12.4' encontrado com checagem de tipo\n";
if (in_array(1.13, $a, TRUE))
    echo "1.13 encontrado com checagem de tipo\n";
?>

A saída seria:
1.13 encontrado com checagem de tipo

Exemplo 3. Exemplo de in_array() passando um array para needle

<?php
$a = array(array('p', 'h'), array('p', 'r'), 'o');

if (in_array(array ('p', 'h'), $a))
    echo "'ph' foi encontrado\n";
if (in_array(array ('f', 'i'), $a))
    echo "'fi' foi encontrado\n";
if (in_array('o', $a))
    echo "'o' foi encontrado\n";
?>

A saída seria:
'ph' foi encontrado 
'o' foi encontrado

Veja também array_search().

key

(PHP 3, PHP 4 )

key -- Retorna uma chave de um array associativo

Descrição

mixed key ( array array)

key() retorna a chave da posição corrente de um array.

Veja também current() e next().

krsort

(PHP 3>= 3.0.13, PHP 4 )

krsort -- Ordena um array pelas chaves em ordem descrescente

Descrição

int krsort ( array array [, int sort_flags])

Ordena um array pelas chaves em ordem descrescente, mantendo a correlação entre entre as chaves e os valores. Essa função é bastante útil em arrays associativos.

Exemplo 1. Exemplo de krsort()

$frutas = array ("d" => "limao", "a" => "laranja", "b" => "banana", "c" => "melancia");
krsort ($frutas);
reset ($frutas);
while (list ($chave, $valor) = each ($frutas)) {
    echo "$chave = $valor\n";
}

A saída deste programa seria:

d = limao
c = melancia
b = banana
a = laranja

Você pode alterar o comportamento da ordenação utilizando o parâmetro opcional sort_flags, para mais detalhes veja sort().

Veja também asort(), arsort(), ksort() sort(), natsort() e rsort().

ksort

(PHP 3, PHP 4 )

ksort -- Ordena um array pelas chaves

Descrição

int ksort ( array array [, int sort_flags])

Ordena um array pelas chaves, mantendo a correlação entre as chaves e os valores. Essa função é bastante útil principalmente para arrays associativos.

Exemplo 1. Exemplo de ksort()

$frutas = array ("d" => "limao", "a" => "laranja", "b" => "banana", "c" => "melancia");
ksort ($frutas);
reset ($frutas);
while (list ($chave, $valor) = each ($frutas)) {
    echo "$chave = $valor\n";
}

O programa acima mostraria:

a = laranja
b = banana
c = melancia
d = limao

Você pode modificar o comportamento da ordenação através do parâmetro opcional sort_flags, para mais detalhes veja sort().

Veja também asort(), arsort(), krsort(), uksort(), sort(), natsort() e rsort().

Nota: O segundo parâmetro foi adicionado a partir do PHP 4.

list

(PHP 3, PHP 4 )

list --  Cria variáveis como se fossem arrays

Descrição

void list ( mixed ...)

Assim como array(), não é exatamente uma função, e sim uma construção da própria linguagem. list() é usada para criar uma lista de variáveis em apenas um operação.

Nota: list() só funciona em arrays com índices numéricos e assume que esses índices começam de 0 (zero).

Exemplo 1. Exemplo de list()

<?php

$info = array('Café', 'marrom', 'cafeína');

// Listando todas as variáveis
list($bebida, $cor, $substancia) = $info;
print "$bebida is $cor e $substancia a faz especial.\n";

// Listando apenas alguns deles
list($bebida, , $substanciar) = $info;
print "$bebida tem $substancia.\n";

// Ou ignoramos os primeiros valores para conseguir apenas o último 
list( , , $substancia) = $info;
print "I need $substancia!\n";

?>

Exemplo 2. Exemplo de list()

<table>
 <tr>
  <th>Lista de empregados</th>
  <th>Salário</th>
 </tr>

<?php

$result = mysql_query ("SELECT id, nome, salario FROM empregados", $conn);
while (list ($id, $nome, $salario) = mysql_fetch_row ($result)) {
    print (" <tr>\n".
           "  <td><a href=\"info.php?id=$id\">$nome</a></td>\n".
           "  <td>$salario</td>\n".
           " </tr>\n");
}

?>

</table>

Atenção

A função list() assinala os valores começando pelos parâmetros da direita. Se você está usando variáveis normais, então não precisa se preocupar com esse detalhe. Mas se você está usando arrays com índices você normalmente iria esperar que a ordem dos índices no array fosse da esquerda para a direita, mas não é isso que acontece. O índice é criado na ordem reversa.

Exemplo 3. Usando list() com índices de array

<?php

$info = array('café', 'marrom', 'cafeína');

list($a[0], $a[1], $a[2]) = $info;

var_dump($a);

?>
O retorno desse script é o seguinte (note a ordem dos elementos em comparação com o array original):
array(3) {
  [2]=>
  string(8) "cafeína"
  [1]=>
  string(5) "marrom"
  [0]=>
  string(6) "café"
}

Veja também each(), array() e extract().

natcasesort

(PHP 4 )

natcasesort --  Ordena um array utilizando o algoritmo da "ordem natural" sem diferenciar maiúsculas e minúsculas

Descrição

void natcasesort ( array array)

Essa função implementa o algoritmo de ordenação que ordena strings alfanuméricas da forma que os humanos fariam. Essa forma de ordenação é denominada "ordenação natural".

natcasesort() é uma versão de natsort() que não diferencia letras maiúsculas e minúsculas. Veja natsort() para saber a diferença entre esse algoritmo e os algoritmos utlizados normalmente para ordenação de strings.

Para mais informações veja: Martin Pool's Natural Order String Comparison page.

Veja também sort(), natsort(), strnatcmp() e strnatcasecmp().

natsort

(PHP 4 )

natsort --  Ordena um array utilizando o algoritmo da "ordem natural"

Descrição

void natsort ( array array)

Essa função é um implementação do algoritmo que ordena strings alfanuméricas da forma como um ser humano faria. Isso é chamado de "ordenação natural". Um exemplo da diferença entre esse algoritmo e o algoritmo com o qual o computador classifica strings (usado em sort()) pode ser visto abaixo:

Exemplo 1. Exemplo de natsort()

$array1 = $array2 = array ("img12.png", "img10.png", "img2.png", "img1.png");
 
sort($array1);
echo "Classificação normal\n";
print_r($array1);

natsort($array2);
echo "\nClassificação da \"ordem natural\"\n";
print_r($array2);

O código acima geraria a seguinte saída:

Classificação normal
Array
(
    [0] => img1.png
    [1] => img10.png
    [2] => img12.png
    [3] => img2.png
)

Classificação da "ordem natural"
Array
(
    [3] => img1.png
    [2] => img2.png
    [1] => img10.png
    [0] => img12.png
)

Para mais informações veja: Martin Pool's Natural Order String Comparison page.

Nota: Se quiser manter a correlação entre chaves e valores, considere a possibilidade de utilizar usort($arr, 'strnatcmp').

Veja também natcasesort(), strnatcmp() e strnatcasecmp().

next

(PHP 3, PHP 4 )

next --  Avança o ponteiro interno de um array

Descrição

mixed next ( array array)

Retorna o elemento do array que está na próxima posição que é apontada pelo ponteiro interno do array, ou FALSE caso não existam mais elementos.

next() funciona de forma semelhante a current(), com uma diferença. Ele avança o ponteiro interno do array em uma posição antes de retornar o elemento. Isso significa que ela retorna o próximo elemento do array avançando o ponteiro interno em uma posição. Se o ponteiro interno apontar para além do final da lista de elementos , next() retorna FALSE.

Atenção

Se o array contiver elementos vazios, ou se elementos tiverem chaves com 0 como valor então essa função retorna FALSE para esses elementos. Para percorrer um array que pode conter elementos vazios ou elementos que tenham chaves com 0 como valor veja a função each().

Veja também current(), end(), prev() e reset().

pos

(PHP 3, PHP 4 )

pos -- Retorna o elemento atual do array

Descrição

mixed pos ( array array)

Essa função é um alias para current().

Veja também end(), next(), prev() e reset().

prev

(PHP 3, PHP 4 )

prev -- Retrocede o ponteiro interno de um array

Descrição

mixed prev ( array array)

Retorna o elemento do array que está na posição anterior a posição apontada pelo ponteiro interno, ou FALSE se houver mais elementos.

Atenção

Se o array contiver elementos vazios então essa função retornará FALSE para esses elementos. Para percorrer corretamente arrays que podem conter elementos vazios veja a função each().

prev() funciona da mesma forma que next(), com a única diferença sendo de que a primeira retrocede o ponteiro interno em uma posição ao invés de avançá-lo.

Veja também current(), end(), next() e reset().

range

(PHP 3>= 3.0.8, PHP 4 )

range --  Cria um array contendo uma faixa de elementos

Descrição

array range ( mixed low, mixed high [, int step])

range() retorna um array com elementos de low até high, com intervalo fechado. Se low > high, será de high até low.

Se o parâmetro step for especificado, será usado como o incremento entre os elementos da sequência. step deve ser um inteiro positivo. Se não for especificado, step terá valor igual a 1.

Exemplo 1. Exemplos de range()

foreach(range(0, 9) as $numero) {
    echo $numero;
}
foreach(range(0, 100, 10) as $numero) {
    echo $numero;
}
foreach(range('a', 'z') as $letra) {
    echo $letra;
}
foreach(range('z', 'a') as $letra) {
    echo $letra;
}

Nota: Até a versão 4.1.0, a função range() só gerava arrays de inteiros em ordem crescente. O suporte para sequências de caracteres e arrays descrescentes foi adicionado no PHP 4.1.0. O parâmetro step foi adicionado na versão 5.0.0.

Exemplo 2. Simulando faixas decrescentes e sequências de caracteres

# array_reverse pode ser usada para inverter a ordem da faixa de valores 
foreach(array_reverse(range(0,9)) as $numero) {
    echo $numero;
}

# array_map() pode ser usada para transformar inteiros em caracteres usando chr()
foreach(array_map('chr', range(ord('a'),ord('z'))) as $caracter) {
    echo $caracter;
}

Veja shuffle() para outro exemplo de utilização dessa função.

reset

(PHP 3, PHP 4 )

reset --  Faz o ponteiro interno de um array apontar para o seu primeiro elemento

Descrição

mixed reset ( array array)

reset() retrocede o ponteiro interno de array para o primeiro elemento.

reset() retorna o valor do primeiro elemento do array.

Veja também current(), each(), next(), e prev().

rsort

(PHP 3, PHP 4 )

rsort -- Ordena um array em ordem descrescente

Descrição

void rsort ( array array [, int sort_flags])

Essa função ordena um array em ordem descrescente (do maior para o menor).

Exemplo 1. Exemplo de rsort()

$frutas = array ("limao", "laranja", "banana", "melancia");
rsort ($frutas);
reset ($frutas);
while (list ($chave, $valor) = each ($frutas)) {
    echo "$chave = $valor\n";
}

Esse exemplo mostraria:

0 = melancia
1 = limao
2 = laranja
3 = banana

As frutas foram ordenadas em ordem alfabética decrescente.

Você pode alterar o comportamento da ordenação utilizando o parâmetro opcional sort_flags, para mais detalhes veja sort().

Veja também arsort(), asort(), ksort(), sort() e usort().

shuffle

(PHP 3>= 3.0.8, PHP 4 )

shuffle -- Mistura os elementos de um array

Descrição

void shuffle ( array array)

Essa função mistura de forma aleatória os elementos de um array. Você deve usar essa função em conjunto com srand().

Exemplo 1. Exemplo de shuffle()

$numeros = range (1,20);
srand ((float)microtime()*1000000);
shuffle ($numeros);
while (list (, $numero) = each ($numeros)) {
    echo "$numero ";
}

Veja também arsort(), asort(), ksort(), rsort(), sort() e usort().

sizeof

(PHP 3, PHP 4 )

sizeof -- Retorna o número de elementos de uma variável

Descrição

int sizeof ( mixed var)

A função sizeof() é um alias para count().

Veja também count().

sort

(PHP 3, PHP 4 )

sort -- Ordena um array

Descrição

void sort ( array array [, int sort_flags])

Essa função ordena um array. Os elementos serão ordenados do menor para o maior ao final da execução dessa função.

Exemplo 1. Exemplo de sort()

<?php

$frutas = array ("limao", "laranja", "banana", "melancia");
sort ($frutas);
reset ($frutas);
while (list ($chave, $valor) = each ($frutas)) {
    echo "frutas[".$chave."] = ".$valor."\n";
}
 
?>

A saída desse programa seria:

fruits[0] = banana
fruits[1] = laranja
fruits[2] = limao
fruits[3] = melancia

As frutas foram classificadas em ordem alfabética.

O segundo argumento opcional sort_flags pode ser usado para modificar o comportamento da ordenação podendo receber os seguintes valores:

Sinais de tipo de ordenação:

  • SORT_REGULAR - compara os itens normalmente

  • SORT_NUMERIC - compara os itens como valores numéricos

  • SORT_STRING - compara os itens como strings

Veja também arsort(), asort(), ksort(), natsort(), natcasesort(), rsort(), usort(), array_multisort() e uksort().

Nota: O segundo parâmetro foi adicionado a partir do PHP 4.

uasort

(PHP 3>= 3.0.4, PHP 4 )

uasort --  Ordena um array utilizando uma função de comparação definida pelo usuário e mantendo as associações entre chaves e valores

Descrição

void uasort ( array array, function cmp_function)

Essa função ordena um array de forma que a correlação entre chaves e valores é mantida. Esta função é usada principalmente para classificar arrays associativos onde a ordem dos elementos é um fator importante. A função de comparacão é definida pelo usuário.

Nota: Por favor, veja usort() e uksort() para exemplos de funções de comparação definidas pelo usuário.

Veja também usort(), uksort(), sort(), asort(), arsort(), ksort() e rsort().

uksort

(PHP 3>= 3.0.4, PHP 4 )

uksort --  Ordena um array pelas chaves utilizando uma função de comparação definida pelo usuário.

Descrição

void uksort ( array array, function cmp_function)

Essa função irá ordenar as chaves de um array usando uma função de comparação definida pelo usuário. Se o array precisa ser classificado utilizando um critério não trivial, você deve usar essa função.

Exemplo 1. Exemplo de uksort()

function cmp ($a, $b) {   
    if ($a == $b) return 0;
    return ($a > $b) ? -1 : 1;
}

$a = array (4 => "quatro", 3 => "tres", 20 => "vinte", 10 => "dez");

uksort ($a, "cmp");

while (list ($chave, $valor) = each ($a)) {
    echo "$chave: $valor\n";
}

Esse exemplo mostraria:

20: vinte
10: dez
4: quatro
3: tres

Veja também usort(), uasort(), sort(), asort(), arsort(), ksort(), natsort() e rsort().

usort

(PHP 3>= 3.0.3, PHP 4 )

usort --  Ordena um array pelos valores utilizando uma função de comparação definida pelo usuário

Descrição

void usort ( array array, string cmp_function)

Essa função irá ordenar um array pelos valores usando uma função de classificação definida pelo usuário. Se o array precisar ser ordenado utilizando um critério não trivial, você deve usar essa função.

A função de comparação deve retornar um inteiro menor, igual ou maior que zero se o primeiro argumento for considerado respectivamente menor, igual, ou maior que o segundo.

Nota: Se dois elementos são considerados iguais, a ordem deles fica indefinida no array resultante. Até o PHP 4.0.6 as funções definidas pelo usuário manteriam a ordem original desses elementos, mas com o novo algoritmo de ordenação introduzido no 4.1.0 esse não é o caso, pois não existe solução para fazer isso de modo eficiente.

Exemplo 1. Exemplo de usort()

function cmp ($a, $b) {   
    if ($a == $b) return 0;
    return ($a > $b) ? -1 : 1;
}

$a = array (3, 2, 5, 6, 1);

usort ($a, "cmp");

while (list ($chave, $valor) = each ($a)) {
    echo "$chave: $valor\n";
}

Esse exemplo mostraria:

0: 6
1: 5
2: 3
3: 2
4: 1

Nota: Obviamente que nesse caso trivial a função rsort() seria mais apropriada.

Exemplo 2. Exemplo de usort() usando um array multi-dimensional

function cmp ($a, $b) {
    return strcmp($a["fruta"], $b["fruta"]);
} 

$frutas[0]["fruta"] = "limoes";
$frutas[1]["fruta"] = "abacaxis";
$frutas[2]["fruta"] = "goiabas";

usort($frutas, "cmp"); 

while (list ($chave, $valor) = each ($frutas)) {
    echo "\$frutas[$chave]: " . $valor["fruta"] . "\n";
}

Na ordenação de um array multi-dimensional, $a e $b contêm referências para o primeiro índice do array.

Esse exemplo mostraria:

$fruits[0]: abacaxis
$fruits[1]: goiabas
$fruits[2]: limoes

Nota: Ao invés de um nome de função, um array contendo uma referência de objeto e ao nome de método também pode ser fornecidos.

Exemplo 3. Exemplo de usort() usando uma função membro de um objeto

class TestObj {
    var $name;

    function TestObj($name)
    {
        $this->name = $name;
    }

    /* Essa é a função estática de comparação */
    function cmp_obj($a, $b)
    {
        $al = strtolower($a->name);
        $bl = strtolower($b->name);
        if ($al == $bl) return 0;
        return ($al > $bl) ? +1 : -1;
    }
}

$a[] = new TestObj("c");
$a[] = new TestObj("b");
$a[] = new TestObj("d");

uasort($a, array ("TestObj", "cmp_obj"));

foreach ($a as $item) {
    print $item->name."\n";
}

Esse exemplo mostraria:

b
c
d

Veja também uasort(), uksort(), sort(), asort(), arsort(),ksort(), natsort(), e rsort().

III. Aspell functions [deprecated]

Introdução

The aspell() functions allows you to check the spelling on a word and offer suggestions.


Requisitos

aspell works only with very old (up to .27.* or so) versions of aspell library. Neither this module, nor those versions of aspell library are supported any longer. If you want to use spell-checking capabilities in PHP, use pspell instead. It uses pspell library and works with newer versions of aspell.


Instalação

You need the aspell library, available from: http://aspell.sourceforge.net/.


Veja Também

See also pspell.

Índice
aspell_check_raw --  Check a word without changing its case or trying to trim it [deprecated]
aspell_check -- Check a word [deprecated]
aspell_new -- Load a new dictionary [deprecated]
aspell_suggest -- Suggest spellings of a word [deprecated]

aspell_check_raw

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

aspell_check_raw --  Check a word without changing its case or trying to trim it [deprecated]

Description

bool aspell_check_raw ( int dictionary_link, string word)

aspell_check_raw() checks the spelling of a word, without changing its case or trying to trim it in any way and returns TRUE if the spelling is correct, FALSE if not.

Exemplo 1. aspell_check_raw()

$aspell_link = aspell_new("english");

if (aspell_check_raw($aspell_link, "test")) {
    echo "This is a valid spelling";
} else {
    echo "Sorry, wrong spelling";
}

aspell_check

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

aspell_check -- Check a word [deprecated]

Description

bool aspell_check ( int dictionary_link, string word)

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

Exemplo 1. aspell_check()

$aspell_link = aspell_new("english");

if (aspell_check($aspell_link, "testt")) {
    echo "This is a valid spelling";
} else {
    echo "Sorry, wrong spelling";
}

aspell_new

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

aspell_new -- Load a new dictionary [deprecated]

Description

int aspell_new ( string master [, string personal])

aspell_new() opens up a new dictionary and returns the dictionary link identifier for use in other aspell functions. Returns FALSE on error.

Exemplo 1. aspell_new()

$aspell_link = aspell_new("english");

aspell_suggest

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

aspell_suggest -- Suggest spellings of a word [deprecated]

Description

array aspell_suggest ( int dictionary_link, string word)

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

Exemplo 1. aspell_suggest()

$aspell_link = aspell_new("english");

if (!aspell_check($aspell_link, "test")) {
    $suggestions = aspell_suggest($aspell_link, "test");

    foreach ($suggestions as $suggestion) {
        echo "Possible spelling: $suggestion<br>\n"; 
    }
}

IV. BCMath Funções Matemáticas de Precisão Arbitrária

Introdução

Para matemática de precisão arbitrária, o PHP oferece a Calculadora Binária com suporte a números de qualquer tamanho e precisão, representados como strings.


Requisitos

Desde o PHP 4.0.4, a libbcmath é distribuída junto com o PHP. Você não precisa de nenhuma biblioteca externa para esta estensão.


Instalação

No PHP 4, estas funções somente serão disponíveis se PHP foi configurado com --enable-bcmath. No PHP 3, estas funções somente serão disponíveis se PHP não foi configurado com --disable-bcmath.


Configuração durante execução

O comportamento dessas funções podem ser modificado pelas configurações do php.ini.

Tabela 1. Opções de configuração da BC Math

Nome Padrão Alterável
bcmath.scale 0 PHP_INI_ALL
Para mais detalhes e definições para as constantes PHP_INI_* veja a função ini_set().

Segue uma breve descrição das diretivas de configuração.

bcmath.scale integer

Número de casas decimais para todas as funções BC Math.


Tipos Resource

Esta extensão não possui nenhum tipo resource.


Constantes Predefinidas

Esta extensão não possui nenhuma constante.

Índice
bcadd -- Adicionar dois números de precisão arbitrária
bccomp -- Comparar dois números de precisão arbitrária
bcdiv -- Dividir dois números de precisão arbitrária
bcmod --  Obter o módulo de um número com precisão arbitrária
bcmul -- Multiplicar dois números de precisão arbitrária
bcpow --  Elevar um número de precisão arbitrária a outro
bcpowmod --  Raise an arbitrary precision number to another, reduced by a specified modulus.
bcscale --  Configura o paramentro escala para todas as funções bc
bcsqrt --  Obter a raiz quadrada de um número de precisão arbitrária
bcsub --  Subtrair um número de precisão arbitrária de outro

bcadd

(PHP 3, PHP 4 )

bcadd -- Adicionar dois números de precisão arbitrária

Descrição

string bcadd ( string operador_da_esquerda, string operador_da_direita [, int escala])

Adiciona o operador_da_esquerda ao operador_da_direita e retorna a soma em uma string. O parametro opcional escala é usado para configurar o número de digitos depois do ponto decimal a ser usados no resultado.

Veja também bcsub().

bccomp

(PHP 3, PHP 4 )

bccomp -- Comparar dois números de precisão arbitrária

Descrição

int bccomp ( string operador_da_esquerda, string operador_da_direita [, int escala])

Compara o operador_da_esquerda com o operador_da_direita e retorna o resultado como um inteiro. O parametro opcional escala é usado para configurar o número de digitos depois do ponto decimal que serão utilizados na comparação. O valor retornado será 0 se os operadores são iguais. Se o operador_da_esquerda for maior do que o operador_da_direita o valor a ser retornado será +1 e se o operador_da_esquerda é menor do que o operador_da_direita o valor retornado é -1.

bcdiv

(PHP 3, PHP 4 )

bcdiv -- Dividir dois números de precisão arbitrária

Descrição

string bcdiv ( string operador_da_esquerda, string operador_da_direita [, int escala])

Divide o operador_da_esquerda pelo operador_da_direita e retorna o resultado. O parametro opcional escala é usado para configurar o número de dígitos depois do ponto decimal que serão mostrados no resultado.

Veja também bcmul().

bcmod

(PHP 3, PHP 4 )

bcmod --  Obter o módulo de um número com precisão arbitrária

Descrição

string bcmod ( string operador_da_esquerda, string modulo)

Obter o módulo do operador_da_esquerda usando modulo.

Veja também bcdiv().

bcmul

(PHP 3, PHP 4 )

bcmul -- Multiplicar dois números de precisão arbitrária

Descrição

string bcmul ( string operador_da_esquerda, string operador_da_direita [, int escala])

Multipica o operador_da_esquerda pelo operador_da_direita e retorna o resultado. O parametro opcional escala configura o número de dígitos depois do ponto decimal que serão mostrados no resultado.

Veja também bcdiv().

bcpow

(PHP 3, PHP 4 )

bcpow --  Elevar um número de precisão arbitrária a outro

Description

string bcpow ( string x, string y [, int escala])

Elevar x a potência de y. O parametro opcional escala configura o número de dígitos depois do ponto decimal que serão mostrados no resultado.

Veja também bcsqrt().

bcpowmod

(PHP 5 CVS only)

bcpowmod --  Raise an arbitrary precision number to another, reduced by a specified modulus.

Description

string bcpowmod ( string x, string y, string modulus [, int scale])

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 after the decimal place in the result.

The following two statements are functionally identical. The bcpowmod() version however, executes in less time and can accept larger parameters.

<?php
$a = bcpowmod($x,$y,$mod);

$b = bcmod(bcpow($x,$y),$mod);

/* $a and $b are equal to each other. */
?>

Nota: Because this method uses the modulus operation, non-natural numbers may give unexpected results. A natural number is any positive non-zero integer.

See also bcpow(), and bcmod().

bcscale

(PHP 3, PHP 4 )

bcscale --  Configura o paramentro escala para todas as funções bc

Descrição

string bcscale ( int escala)

Esta função configura o padrão (default) para o parametro escala de todas as chamadas as funções bc math subsequentes. Este valor será utilizado caso o parametro escala não seja especificado em chamadas as bcmath subsequentes.

bcsqrt

(PHP 3, PHP 4 )

bcsqrt --  Obter a raiz quadrada de um número de precisão arbitrária

Descrição

string bcsqrt ( string operador [, int scale])

Retorna a raiz quadrada do operador. O parametro opcional escala configura o número de digitos depois do ponto decimal que serão mostrados no resultado.

See also bcpow().

bcsub

(PHP 3, PHP 4 )

bcsub --  Subtrair um número de precisão arbitrária de outro

Descrição

string bcsub ( string operador_da_esquerda, string operador_da_direita [, int escala])

Subtrair o operador_da_direita do operador_da_esquerda e retorna o resultado em uma string. O parametro opcional escala é usado para configurar o número de digitos depois do ponto decimal que serão mostrados no resultado.

Veja também bcadd().

V. Funções de compactação com Bzip2

Introdução

As funções para bzip2 são usadas para ler e escrever, de forma transparente, arquivos compactados do tipo bzip2 (.bz2).


Requisitos

Este módulo utiliza as funções da biblioteca bzip2 desenvolvida por Julian Seward


Instalação

O suporte às funções para Bzip2 no PHP não é habilitado por padrão. Você precisa usar a opção de configuração --with-bz2 quando for compilar o PHP para habilitar o suporte a bzip2. Este módulo requer bzip2/libbzip2, versão >= 1.0.x.


Configuração durante execução

Esta extenção não define nenhum parâmetro de configuração no php.ini.


Tipos Resource

Esta extensão define um tipo de recurso (resource): um ponteiro para arquivo que identifica o arquivo bzip2 que está sendo usado.


Constantes Predefinidas

Esta extensão não possui nenhuma constante.


Exemplos

Este exemplo abre um arquivo temporário e escreve uma string de test nele, e então mostra o conteúdo do arquivo.

Exemplo 1. Um exemplo simples de bzip2

<?php

$arquivo = "/tmp/testfile.bz2";
$str = "This is a test string.\n";

// abre o arquivo para escrita
$bz = bzopen($arquivo, "w");

// escreve a string no arquivo
bzwrite($bz, $str);

// fecha o arquivo
bzclose($bz);

// abre o arquivo para leitura
$bz = bzopen($arquivo, "r");

// lê 10 caracteres
print bzread($bz, 10);

// imprime até o final do arquivo (ou os próximos 1024 caracteres)  
print bzread($bz);

// fecha o arquivo
bzclose($bz);

?>
Índice
bzclose -- Fecha um ponteiro de arquivo bzip2
bzcompress -- Comprime uma string em dados no formato bzip2
bzdecompress -- Descomprime dados no formato bzip2
bzerrno -- Retorna um número de erro do bzip2
bzerror -- Retorna o número e string de erro do bzip2 como um array
bzerrstr -- Retorna a string de erro do bzip2
bzflush -- Força a escrita de todos os dados que estão no buffer
bzopen -- Abre um arquivo comprimido com bzip2
bzread -- Leitura binary-safe de um arquivo bzip2
bzwrite -- Escrita binary-safe em um arquivo bzip2

bzclose

(PHP 4 >= 4.0.4)

bzclose -- Fecha um ponteiro de arquivo bzip2

Descrição

int bzclose ( resource bz)

Fecha o arquivo bzip2 referenciado pelo ponteiro bz.

Retorna TRUE em caso de sucesso ou FALSE em falhas.

O ponteiro de arquivo deve ser válido, e deve apontar para um arquivo aberto com sucesso com bzopen().

Veja também bzopen().

bzcompress

(PHP 4 >= 4.0.4)

bzcompress -- Comprime uma string em dados no formato bzip2

Descrição

string bzcompress ( string source [, int blocksize [, int workfactor]])

bzcompress() comprime a string source e a retorna no formato de dados codificados com bzip2.

O parâmetro opcional blocksize especifica o tamanho do bloco utilizado no momento de compressão e deve ser um número de 1 a 9, com 9 sendo a melhor taxa de compressão, mas usando mais recursos para fazê-lo. O valor padrão de blocksize é 4.

O parâmetro opcional workfactor controla como a fase de compressão irá se comportar quando ocorrer o pior caso: a entrada de dados muito repetitivos. O seu valor pode ser de 0 até 250, com 0 sendo um caso especial, e 30 o valor padrão. Independente do valor de workfactor, a saída gerada será a mesma.

Exemplo 1. Exemplo de bzcompress()

<?php
$str = "demonstracao de dados comprimidos";
$bzstr = bzcompress($str, 9);
print($bzstr);
?>

Veja também bzdecompress().

bzdecompress

(PHP 4 >= 4.0.4)

bzdecompress -- Descomprime dados no formato bzip2

Descrição

string bzdecompress ( string source [, int small])

bzdecompress() descomprime a string source string contendo dados no formato bzip2 e retorna o seu valor. Se o parâmetro opcional small for TRUE, um algoritmo alternativo de descompressão, com a utilização de menos memória (a máxima quantidade de memória requerida é em torno de 2300K), será usado mas funciona com a metade da velocidade. Veja a documentação do bzip2 para mais informações sobre essa característica.

Exemplo 1. bzdecompress()

<?php
$start_str = "Esse cara é legal?";
$bzstr = bzcompress($start_str);

print( "String comprimida: " );
print( $bzstr );
print( "\n<br>\n" );

$str = bzdecompress($bzstr);
print( "String descomprimida: " );
print( $str );
print( "\n<br>\n" );
?>

Veja também bzcompress().

bzerrno

(PHP 4 >= 4.0.4)

bzerrno -- Retorna um número de erro do bzip2

Descrição

int bzerrno ( resource bz)

Retorna o número do erro de qualquer erro do bzip2 retornado pelo ponteiro de arquivo bz.

Veja também bzerror() e bzerrstr().

bzerror

(PHP 4 >= 4.0.4)

bzerror -- Retorna o número e string de erro do bzip2 como um array

Descrição

array bzerror ( resource bz)

Retorna o número e string do erro, em um array associativo, de qualquer erro retornado pelo ponteiro de arquivo bz.

Exemplo 1. Exemplo de bzerror()

<?php
$error = bzerror($bz);

echo $error["errno"];
echo $error["errstr"];
?>

Veja também bzerrno() e bzerrstr().

bzerrstr

(PHP 4 >= 4.0.4)

bzerrstr -- Retorna a string de erro do bzip2

Descrição

string bzerrstr ( resource bz)

Retorna a string de erro de qualquer erro retornado pelo ponteiro de arquivo bz.

Veja também bzerrno() e bzerror().

bzflush

(PHP 4 >= 4.0.4)

bzflush -- Força a escrita de todos os dados que estão no buffer

Descrição

int bzflush ( resource bz)

Força a escrita de todos os dados do bzip2 que estão em buffer para o ponteiro de arquivo bz.

Retorna TRUE em caso de sucesso ou FALSE em falhas.

Veja também bzread() e bzwrite().

bzopen

(PHP 4 >= 4.0.4)

bzopen -- Abre um arquivo comprimido com bzip2

Descrição

resource bzopen ( string filename, string mode)

Abre um arquivo bzip2 (.bz2) para leitura ou escrita. O parâmetro filename é o nome do arquivo a ser aberto. mode é similar ao da função fopen() (`r' para leitura, `w' para escrita, etc.).

Se esta função falhar, retorna FALSE, do contrário retorna um ponteiro de arquivo aberto.

Exemplo 1. Exemplo de bzopen()

<?php
$bz = bzopen("/tmp/foo.bz2", "r");
$arquivo_descomprimido = bzread($bz, filesize("/tmp/foo.bz2"));
bzclose($bz);

print( "O conteúdo de /tmp/foo.bz2 é: " );
print( "\n<br>\n" );
print( $arquivo_descomprimido );
?>

Veja também bzclose().

bzread

(PHP 4 >= 4.0.4)

bzread -- Leitura binary-safe de um arquivo bzip2

Descrição

string bzread ( resource bz [, int length])

bzread() lê o número de bytes equivalente a length do ponteiro de arquivo bzip2 referenciado por bz. A leitura pára quando a a quantidade de bytes referenciados por length (descomprimidos) foram lidos ou EOF foi alcançado, o que acontecer primeiro. Se o parâmetro opcional length não for especificado, bzread() irá ler 1024 bytes (descomprimidos) de cada vez.

Exemplo 1. Exemplo de bzread()

<?php
$bz = bzopen("/tmp/foo.bz2", "r");
$str = bzread($bz, 2048);
print( $str );
?>

Veja também bzwrite() e bzopen().

bzwrite

(PHP 4 >= 4.0.4)

bzwrite -- Escrita binary-safe em um arquivo bzip2

Descrição

int bzwrite ( resource bz, string data [, int length])

bzwrite() escreve o conteúdo da string data no arquivo referenciado pelo ponteiro de arquivo bzip2 bz. Se o parâmetro opcional length for passado, a escrita irá parar depois deste número de bytes (descomprimidos) foram escritos ou se o final da string foi alcançado, o que acontecer primeiro.

Exemplo 1. Exemplo de bzwrite()

<?php
$str = "dados descomprimidos";
$bz = bzopen("/tmp/foo.bz2", "w");
bzwrite($bz, $str, strlen($str));
bzclose($bz);
?>

Veja também bzread() e bzopen().

VI. Calendar functions

Introdução

The calendar extension presents a series of functions to simplify converting between different calendar formats. The intermediary or standard it is based on is the Julian Day Count. The Julian Day Count is a count of days starting from January 1st, 4713 B.C. To convert between calendar systems, you must first convert to Julian Day Count, then to the calendar system of your choice. Julian Day Count is very different from the Julian Calendar! For more information on Julian Day Count, visit http://serendipity.magnet.ch/hermetic/cal_stud/jdn.htm. For more information on calendar systems visit http://genealogy.org/~scottlee/cal-overview.html. Excerpts from this page are included in these instructions, and are in quotes.


Instalação

To get these functions to work, you have to compile PHP with --enable-calendar.

The windows version of PHP has built in support for this extension. You do not need to load any additional extension in order to use these functions.


Configuração durante execução

Esta extenção não define nenhum parâmetro de configuração no php.ini.


Tipos Resource

Esta extensão não possui nenhum tipo resource.


Constantes Predefinidas

As contantes abaixo são definidas por esta extensão e somente estarão disponíveis quando a extensão foi compilada com o PHP ou carregada dinamicamente durante a execução.

CAL_GREGORIAN (integer)

CAL_JULIAN (integer)

CAL_JEWISH (integer)

CAL_FRENCH (integer)

CAL_NUM_CALS (integer)

CAL_DOW_DAYNO (integer)

CAL_DOW_SHORT (integer)

CAL_DOW_LONG (integer)

CAL_MONTH_GREGORIAN_SHORT (integer)

CAL_MONTH_GREGORIAN_LONG (integer)

CAL_MONTH_JULIAN_SHORT (integer)

CAL_MONTH_JULIAN_LONG (integer)

CAL_MONTH_JEWISH (integer)

CAL_MONTH_FRENCH (integer)

The following constants are available since PHP 4.3.0 :

CAL_EASTER_DEFAULT (integer)

CAL_EASTER_ROMAN (integer)

CAL_EASTER_ALWAYS_GREGORIAN (integer)

CAL_EASTER_ALWAYS_JULIAN (integer)

Índice
cal_days_in_month -- Return the number of days in a month for a given year and calendar
cal_from_jd -- Converts from Julian Day Count to a supported calendar and return extended information
cal_info -- Returns information about a particular calendar
cal_to_jd -- Converts from a supported calendar to Julian Day Count
easter_date --  Get UNIX timestamp for midnight on Easter of a given year
easter_days --  Get number of days after March 21 on which Easter falls for a given year
FrenchToJD --  Converts a date from the French Republican Calendar to a Julian Day Count
GregorianToJD --  Converts a Gregorian date to Julian Day Count
JDDayOfWeek -- Returns the day of the week
JDMonthName -- Returns a month name
JDToFrench --  Converts a Julian Day Count to the French Republican Calendar
JDToGregorian -- Converts Julian Day Count to Gregorian date
JDToJewish --  Converts a Julian Day Count to the Jewish Calendar
JDToJulian --  Converts a Julian Day Count to a Julian Calendar Date
jdtounix -- Convert Julian Day to UNIX timestamp
JewishToJD --  Converts a date in the Jewish Calendar to Julian Day Count
JulianToJD --  Converts a Julian Calendar date to Julian Day Count
unixtojd -- Convert UNIX timestamp to Julian Day

cal_days_in_month

(PHP 4 >= 4.1.0)

cal_days_in_month -- Return the number of days in a month for a given year and calendar

Description

int cal_days_in_month ( int calendar, int month, int year)

This function will return the number of days in the month of year for the specified calendar.

See also jdtounix().

cal_from_jd

(PHP 4 >= 4.1.0)

cal_from_jd -- Converts from Julian Day Count to a supported calendar and return extended information

Description

array cal_from_jd ( int jd, int calendar)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

cal_info

(PHP 4 >= 4.1.0)

cal_info -- Returns information about a particular calendar

Description

array cal_info ( int calendar)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

cal_to_jd

(PHP 4 >= 4.1.0)

cal_to_jd -- Converts from a supported calendar to Julian Day Count

Description

int cal_to_jd ( int calendar, int month, int day, int year)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

easter_date

(PHP 3>= 3.0.9, PHP 4 )

easter_date --  Get UNIX timestamp for midnight on Easter of a given year

Description

int easter_date ( [int year])

Returns the UNIX timestamp corresponding to midnight on Easter of the given year.

Since PHP 4.3.0, the year parameter is optional and defaults to the current year according to the localtime if ommited.

Warning: This function will generate a warning if the year is outside of the range for UNIX timestamps (i.e. before 1970 or after 2037).

Exemplo 1. easter_date() example

echo date ("M-d-Y", easter_date(1999));        /* "Apr-04-1999" */
echo date ("M-d-Y", easter_date(2000));        /* "Apr-23-2000" */
echo date ("M-d-Y", easter_date(2001));        /* "Apr-15-2001" */

The date of Easter Day was defined by the Council of Nicaea in AD325 as the Sunday after the first full moon which falls on or after the Spring Equinox. The Equinox is assumed to always fall on 21st March, so the calculation reduces to determining the date of the full moon and the date of the following Sunday. The algorithm used here was introduced around the year 532 by Dionysius Exiguus. Under the Julian Calendar (for years before 1753) a simple 19-year cycle is used to track the phases of the Moon. Under the Gregorian Calendar (for years after 1753 - devised by Clavius and Lilius, and introduced by Pope Gregory XIII in October 1582, and into Britain and its then colonies in September 1752) two correction factors are added to make the cycle more accurate.

(The code is based on a C program by Simon Kershaw, <webmaster@ely.anglican.org>)

See easter_days() for calculating Easter before 1970 or after 2037.

easter_days

(PHP 3>= 3.0.9, PHP 4 )

easter_days --  Get number of days after March 21 on which Easter falls for a given year

Description

int easter_days ( [int year [, int method]])

Returns the number of days after March 21 on which Easter falls for a given year. If no year is specified, the current year is assumed.

Since PHP 4.3.0, the year parameter is optional and defaults to the current year according to the localtime if ommited.

The method parameter was also introduced in PHP 4.3.0 and allows to calculate easter dates based on the Gregorian calendar during the years 1582 - 1752 when set to CAL_EASTER_ROMAN. See the calendar constants for more valid constants.

This function can be used instead of easter_date() to calculate Easter for years which fall outside the range of UNIX timestamps (i.e. before 1970 or after 2037).

Exemplo 1. easter_days() example

echo easter_days (1999);        /* 14, i.e. April 4   */
echo easter_days (1492);        /* 32, i.e. April 22  */
echo easter_days (1913);        /*  2, i.e. March 23  */

The date of Easter Day was defined by the Council of Nicaea in AD325 as the Sunday after the first full moon which falls on or after the Spring Equinox. The Equinox is assumed to always fall on 21st March, so the calculation reduces to determining the date of the full moon and the date of the following Sunday. The algorithm used here was introduced around the year 532 by Dionysius Exiguus. Under the Julian Calendar (for years before 1753) a simple 19-year cycle is used to track the phases of the Moon. Under the Gregorian Calendar (for years after 1753 - devised by Clavius and Lilius, and introduced by Pope Gregory XIII in October 1582, and into Britain and its then colonies in September 1752) two correction factors are added to make the cycle more accurate.

(The code is based on a C program by Simon Kershaw, <webmaster@ely.anglican.org>)

See also easter_date().

FrenchToJD

(PHP 3, PHP 4 )

FrenchToJD --  Converts a date from the French Republican Calendar to a Julian Day Count

Description

int frenchtojd ( int month, int day, int year)

Converts a date from the French Republican Calendar to a Julian Day Count.

These routines only convert dates in years 1 through 14 (Gregorian dates 22 September 1792 through 22 September 1806). This more than covers the period when the calendar was in use.

GregorianToJD

(PHP 3, PHP 4 )

GregorianToJD --  Converts a Gregorian date to Julian Day Count

Description

int gregoriantojd ( int month, int day, int year)

Valid Range for Gregorian Calendar 4714 B.C. to 9999 A.D.

Although this function can handle dates all the way back to 4714 B.C., such use may not be meaningful. The Gregorian calendar was not instituted until October 15, 1582 (or October 5, 1582 in the Julian calendar). Some countries did not accept it until much later. For example, Britain converted in 1752, The USSR in 1918 and Greece in 1923. Most European countries used the Julian calendar prior to the Gregorian.

Exemplo 1. Calendar functions

<?php
$jd = GregorianToJD (10,11,1970);
echo "$jd\n";
$gregorian = JDToGregorian ($jd);
echo "$gregorian\n";
?>

JDDayOfWeek

(PHP 3, PHP 4 )

JDDayOfWeek -- Returns the day of the week

Description

mixed jddayofweek ( int julianday, int mode)

Returns the day of the week. Can return a string or an integer depending on the mode.

Tabela 1. Calendar week modes

Mode Meaning
0 Returns the day number as an int (0=sunday, 1=monday, etc)
1 Returns string containing the day of week (english-gregorian)
2 Returns a string containing the abbreviated day of week (english-gregorian)

JDMonthName

(PHP 3, PHP 4 )

JDMonthName -- Returns a month name

Description

string jdmonthname ( int julianday, int mode)

Returns a string containing a month name. mode tells this function which calendar to convert the Julian Day Count to, and what type of month names are to be returned.

Tabela 1. Calendar modes

Mode Meaning Values
0 Gregorian - abbreviated Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec
1 Gregorian January, February, March, April, May, June, July, August, September, October, November, December
2 Julian - abbreviated Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec
3 Julian January, February, March, April, May, June, July, August, September, October, November, December
4 Jewish Tishri, Heshvan, Kislev, Tevet, Shevat, AdarI, AdarII, Nisan, Iyyar, Sivan, Tammuz, Av, Elul
5 French Republican Vendemiaire, Brumaire, Frimaire, Nivose, Pluviose, Ventose, Germinal, Floreal, Prairial, Messidor, Thermidor, Fructidor, Extra

JDToFrench

(PHP 3, PHP 4 )

JDToFrench --  Converts a Julian Day Count to the French Republican Calendar

Description

string jdtofrench ( int juliandaycount)

Converts a Julian Day Count to the French Republican Calendar.

JDToGregorian

(PHP 3, PHP 4 )

JDToGregorian -- Converts Julian Day Count to Gregorian date

Description

string jdtogregorian ( int julianday)

Converts Julian Day Count to a string containing the Gregorian date in the format of "month/day/year".

JDToJewish

(PHP 3, PHP 4 )

JDToJewish --  Converts a Julian Day Count to the Jewish Calendar

Description

string jdtojewish ( int julianday)

Converts a Julian Day Count the the Jewish Calendar.

JDToJulian

(PHP 3, PHP 4 )

JDToJulian --  Converts a Julian Day Count to a Julian Calendar Date

Description

string jdtojulian ( int julianday)

Converts Julian Day Count to a string containing the Julian Calendar Date in the format of "month/day/year".

jdtounix

(PHP 4 )

jdtounix -- Convert Julian Day to UNIX timestamp

Description

int jdtounix ( int jday)

This function will return a UNIX timestamp corresponding to the Julian Day given in jday or FALSE if jday is not inside the UNIX epoch (Gregorian years between 1970 and 2037 or 2440588 <= jday <= 2465342 ). The time returned is localtime (and not GMT).

See also unixtojd().

JewishToJD

(PHP 3, PHP 4 )

JewishToJD --  Converts a date in the Jewish Calendar to Julian Day Count

Description

int jewishtojd ( int month, int day, int year)

Although this function can handle dates all the way back to the year 1 (3761 B.C.), such use may not be meaningful. The Jewish calendar has been in use for several thousand years, but in the early days there was no formula to determine the start of a month. A new month was started when the new moon was first observed.

JulianToJD

(PHP 3, PHP 4 )

JulianToJD --  Converts a Julian Calendar date to Julian Day Count

Description

int juliantojd ( int month, int day, int year)

Valid Range for Julian Calendar 4713 B.C. to 9999 A.D.

Although this function can handle dates all the way back to 4713 B.C., such use may not be meaningful. The calendar was created in 46 B.C., but the details did not stabilize until at least 8 A.D., and perhaps as late at the 4th century. Also, the beginning of a year varied from one culture to another - not all accepted January as the first month.

Cuidado

Remember, the current calendar system being used worldwide is the Gregorian calendar. gregoriantojd() can be used to convert such dates to their Julian Day count.

unixtojd

(PHP 4 )

unixtojd -- Convert UNIX timestamp to Julian Day

Description

int unixtojd ( [int timestamp])

Return the Julian Day for a UNIX timestamp (seconds since 1.1.1970), or for the current day if no timestamp is given.

See also jdtounix().

VII. CCVS API Functions

Introdução

These functions interface the CCVS API, allowing you to work directly with CCVS from your PHP scripts. CCVS is RedHat's solution to the "middle-man" in credit card processing. It lets you directly address the credit card clearing houses via your *nix box and a modem. Using the CCVS module for PHP, you can process credit cards directly through CCVS via your PHP Scripts. The following references will outline the process.

Nota: CCVS has been discontinued by Red Hat and there are no plans to issue further keys or support contracts. Those looking for a replacement can consider MCVE by Main Street Softworks as a potential replacement. It is similar in design and has documented PHP support!


Instalação

To enable CCVS Support in PHP, first verify your CCVS installation directory. You will then need to configure PHP with the --with-ccvs option. If you use this option without specifying the path to your CCVS installation, PHP will attempt to look in the default CCVS Install location (/usr/local/ccvs). If CCVS is in a non-standard location, run configure with: --with-ccvs=$ccvs_path, where $ccvs_path is the path to your CCVS installation. Please note that CCVS support requires that $ccvs_path/lib and $ccvs_path/include exist, and include cv_api.h under the include directory and libccvs.a under the lib directory.

Additionally, a ccvsd process will need to be running for the configurations you intend to use in your PHP scripts. You will also need to make sure the PHP Processes are running under the same user as your CCVS was installed as (e.g. if you installed CCVS as user 'ccvs', your PHP processes must run as 'ccvs' as well.)


Veja Também

Additional information about CCVS can be found at http://www.redhat.com/products/ccvs. RedHat maintains slightly outdated but still useful documentation at http://www.redhat.com/products/ccvs/support/CCVS3.3docs/ProgPHP.html.

Índice
ccvs_add -- Add data to a transaction
ccvs_auth --  Perform credit authorization test on a transaction
ccvs_command --  Performs a command which is peculiar to a single protocol, and thus is not available in the general CCVS API
ccvs_count --  Find out how many transactions of a given type are stored in the system
ccvs_delete -- Delete a transaction
ccvs_done -- Terminate CCVS engine and do cleanup work
ccvs_init -- Initialize CCVS for use
ccvs_lookup --  Look up an item of a particular type in the database #
ccvs_new -- Create a new, blank transaction
ccvs_report -- Return the status of the background communication process
ccvs_return --  Transfer funds from the merchant to the credit card holder
ccvs_reverse --  Perform a full reversal on an already-processed authorization
ccvs_sale --  Transfer funds from the credit card holder to the merchant
ccvs_status -- Check the status of an invoice
ccvs_textvalue -- Get text return value for previous function call
ccvs_void --  Perform a full reversal on a completed transaction

ccvs_add

(4.0.2 - 4.2.3 only)

ccvs_add -- Add data to a transaction

Description

string ccvs_add ( string session, string invoice, string argtype, string argval)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ccvs_auth

(4.0.2 - 4.2.3 only)

ccvs_auth --  Perform credit authorization test on a transaction

Description

string ccvs_auth ( string session, string invoice)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ccvs_command

(4.0.2 - 4.2.3 only)

ccvs_command --  Performs a command which is peculiar to a single protocol, and thus is not available in the general CCVS API

Description

string ccvs_command ( string session, string type, string argval)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ccvs_count

(4.0.2 - 4.2.3 only)

ccvs_count --  Find out how many transactions of a given type are stored in the system

Description

int ccvs_count ( string session, string type)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ccvs_delete

(4.0.2 - 4.2.3 only)

ccvs_delete -- Delete a transaction

Description

string ccvs_delete ( string session, string invoice)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ccvs_done

(4.0.2 - 4.2.3 only)

ccvs_done -- Terminate CCVS engine and do cleanup work

Description

string ccvs_done ( string sess)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ccvs_init

(4.0.2 - 4.2.3 only)

ccvs_init -- Initialize CCVS for use

Description

string ccvs_init ( string name)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ccvs_lookup

(4.0.2 - 4.2.3 only)

ccvs_lookup --  Look up an item of a particular type in the database #

Description

string ccvs_lookup ( string session, string invoice, int inum)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ccvs_new

(4.0.2 - 4.2.3 only)

ccvs_new -- Create a new, blank transaction

Description

string ccvs_new ( string session, string invoice)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ccvs_report

(4.0.2 - 4.2.3 only)

ccvs_report -- Return the status of the background communication process

Description

string ccvs_report ( string session, string type)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ccvs_return

(4.0.2 - 4.2.3 only)

ccvs_return --  Transfer funds from the merchant to the credit card holder

Description

string ccvs_return ( string session, string invoice)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ccvs_reverse

(4.0.2 - 4.2.3 only)

ccvs_reverse --  Perform a full reversal on an already-processed authorization

Description

string ccvs_reverse ( string session, string invoice)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ccvs_sale

(4.0.2 - 4.2.3 only)

ccvs_sale --  Transfer funds from the credit card holder to the merchant

Description

string ccvs_sale ( string session, string invoice)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ccvs_status

(4.0.2 - 4.2.3 only)

ccvs_status -- Check the status of an invoice

Description

string ccvs_status ( string session, string invoice)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ccvs_textvalue

(4.0.2 - 4.2.3 only)

ccvs_textvalue -- Get text return value for previous function call

Description

string ccvs_textvalue ( string session)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ccvs_void

(4.0.2 - 4.2.3 only)

ccvs_void --  Perform a full reversal on a completed transaction

Description

string ccvs_void ( string session, string invoice)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

VIII. COM support functions for Windows

Introdução

COM is a technology which allows the reuse of code written in any language (by any language) using a standard calling convention and hiding behind APIs the implementation details such as what machine the Component is stored on and the executable which houses it. It can be thought of as a super Remote Procedure Call (RPC) mechanism with some basic object roots. It separates implementation from interface.

COM encourages versioning, separation of implementation from interface and hiding the implementation details such as executable location and the language it was written in.


Requisitos

COM functions are only available on the Windows version of PHP.


Instalação

Não há nenhuma instalação nescessária para utilizar estas funções, elas fazem parte do núcleo do PHP.

The windows version of PHP has built in support for this extension. You do not need to load any additional extension in order to use these functions.


Configuração durante execução

O comportamento dessas funções podem ser modificado pelas configurações do php.ini.

Tabela 1. Com configuration options

Name Default Changeable
com.allow_dcom "0" PHP_INI_SYSTEM
com.autoregister_typelib "0" PHP_INI_SYSTEM
com.autoregister_verbose "0" PHP_INI_SYSTEM
com.autoregister_casesensitive "1" PHP_INI_SYSTEM
com.typelib_file "" PHP_INI_SYSTEM
For further details and definition of the PHP_INI_* constants see ini_set().


Constantes Predefinidas

As contantes abaixo são definidas por esta extensão e somente estarão disponíveis quando a extensão foi compilada com o PHP ou carregada dinamicamente durante a execução.

CLSCTX_INPROC_SERVER (integer)

CLSCTX_INPROC_HANDLER (integer)

CLSCTX_LOCAL_SERVER (integer)

CLSCTX_REMOTE_SERVER (integer)

CLSCTX_SERVER (integer)

CLSCTX_ALL (integer)

VT_NULL (integer)

VT_EMPTY (integer)

VT_UI1 (integer)

VT_I2 (integer)

VT_I4 (integer)

VT_R4 (integer)

VT_R8 (integer)

VT_BOOL (integer)

VT_ERROR (integer)

VT_CY (integer)

VT_DATE (integer)

VT_BSTR (integer)

VT_DECIMAL (integer)

VT_UNKNOWN (integer)

VT_DISPATCH (integer)

VT_VARIANT (integer)

VT_I1 (integer)

VT_UI2 (integer)

VT_UI4 (integer)

VT_INT (integer)

VT_UINT (integer)

VT_ARRAY (integer)

VT_BYREF (integer)

CP_ACP (integer)

CP_MACCP (integer)

CP_OEMCP (integer)

CP_UTF7 (integer)

CP_UTF8 (integer)

CP_SYMBOL (integer)

CP_THREAD_ACP (integer)


Veja Também

For further information on COM read the COM specification or perhaps take a look at Don Box's Yet Another COM Library (YACL)

Índice
COM -- COM class
VARIANT -- VARIANT class
com_addref --  Increases the components reference counter.
com_get --  Gets the value of a COM Component's property
com_invoke --  Calls a COM component's method.
com_isenum -- Grabs an IEnumVariant
com_load_typelib -- Loads a Typelib
com_load --  Creates a new reference to a COM component
com_propget --  Gets the value of a COM Component's property
com_propput --  Assigns a value to a COM component's property
com_propset --  Assigns a value to a COM component's property
com_release --  Decreases the components reference counter.
com_set --  Assigns a value to a COM component's property

COM

(no version information, might be only in CVS)

COM -- COM class

Sinopse

$obj = new COM("server.object")

Description

The COM class provides a framework to integrate (D)COM components into your php scripts.

Methods

string COM::COM ( string module_name [, string server_name [, int codepage]])

COM class constructor. Parameters:

module_name

name or class-id of the requested component.

server_name

name of the DCOM server from which the component should be fetched. If NULL, localhost is assumed. To allow DCOM com.allow_dcom has to be set to TRUE in php.ini.

codepage

specifies the codepage that is used to convert php-strings to unicode-strings and vice versa. Possible values are CP_ACP, CP_MACCP, CP_OEMCP, CP_SYMBOL, CP_THREAD_ACP, CP_UTF7 and CP_UTF8.

Exemplo 1. COM example (1)

// starting word
$word = new COM("word.application") or die("Unable to instanciate Word");
print "Loaded Word, version {$word->Version}\n";

//bring it to front
$word->Visible = 1;

//open an empty document
$word->Documents->Add();

//do some weird stuff
$word->Selection->TypeText("This is a test...");
$word->Documents[1]->SaveAs("Useless test.doc");

//closing word
$word->Quit();

//free the object
$word->Release();
$word = null;

Exemplo 2. COM example (2)

$conn = new COM("ADODB.Connection") or die("Cannot start ADO");
$conn->Open("Provider=SQLOLEDB; Data Source=localhost;
Initial Catalog=database; User ID=user; Password=password");

$rs = $conn->Execute("SELECT * FROM sometable");    // Recordset

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

for ($i=0; $i < $num_columns; $i++)
{
    $fld[$i] = $rs->Fields($i);
}

$rowcount = 0;
while (!$rs->EOF)
{
    for ($i=0; $i < $num_columns; $i++)
    {
        echo $fld[$i]->value . "\t";
    }
    echo "\n";
    $rowcount++;            // increments rowcount
    $rs->MoveNext();
}

$rs->Close();
$conn->Close();

$rs->Release();
$conn->Release();

$rs = null;
$conn = null;

VARIANT

(no version information, might be only in CVS)

VARIANT -- VARIANT class

Sinopse

$vVar = new VARIANT($var)

Description

A simple container to wrap variables into VARIANT structures.

Methods

string VARIANT::VARIANT ( [mixed value [, int type [, int codepage]]])

VARIANT class constructor. Parameters:

value

initial value. if omitted an VT_EMPTY object is created.

type

specifies the content type of the VARIANT object. Possible values are VT_UI1, VT_UI2, VT_UI4, VT_I1, VT_I2, VT_I4, VT_R4, VT_R8, VT_INT, VT_UINT, VT_BOOL, VT_ERROR, VT_CY, VT_DATE, VT_BSTR, VT_DECIMAL, VT_UNKNOWN, VT_DISPATCH and VT_VARIANT. These values are mutual exclusive, but they can be combined with VT_BYREF to specify being a value. If omitted, the type of value is used. Consult the msdn library for additional information.

codepage

specifies the codepage that is used to convert php-strings to unicode-strings and vice versa. Possible values are CP_ACP, CP_MACCP, CP_OEMCP, CP_SYMBOL, CP_THREAD_ACP, CP_UTF7 and CP_UTF8.

com_addref

(4.1.0 - 4.3.0 only)

com_addref --  Increases the components reference counter.

Description

void com_addref ( void)

Increases the components reference counter.

com_get

(PHP 3>= 3.0.3, 4.0.5 - 4.3.0 only)

com_get --  Gets the value of a COM Component's property

Description

mixed com_get ( resource com_object, string property)

Returns the value of the property of the COM component referenced by com_object. Returns FALSE on error.

com_invoke

(PHP 3>= 3.0.3)

com_invoke --  Calls a COM component's method.

Description

mixed com_invoke ( resource com_object, string function_name [, mixed function parameters, ...])

com_invoke() invokes a method of the COM component referenced by com_object. Returns FALSE on error, returns the function_name's return value on success.

com_isenum

(4.1.0 - 4.3.0 only)

com_isenum -- Grabs an IEnumVariant

Description

void com_isenum ( object com_module)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

com_load_typelib

(4.1.0 - 4.3.0 only)

com_load_typelib -- Loads a Typelib

Description

void com_load_typelib ( string typelib_name [, int case_insensitive])

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

com_load

(PHP 3>= 3.0.3)

com_load --  Creates a new reference to a COM component

Description

string com_load ( string module name [, string server name [, int codepage]])

com_load() creates a new COM component and returns a reference to it. Returns FALSE on failure. Possible values for codepage are CP_ACP, CP_MACCP, CP_OEMCP, CP_SYMBOL, CP_THREAD_ACP, CP_UTF7 and CP_UTF8.

com_propget

(PHP 3>= 3.0.3, 4.0.5 - 4.3.0 only)

com_propget --  Gets the value of a COM Component's property

Description

mixed com_propget ( resource com_object, string property)

This function is an alias for com_get().

com_propput

(PHP 3>= 3.0.3, 4.0.5 - 4.3.0 only)

com_propput --  Assigns a value to a COM component's property

Description

void com_propput ( resource com_object, string property, mixed value)

This function is an alias for com_set().

com_propset

(PHP 3>= 3.0.3, 4.0.5 - 4.3.0 only)

com_propset --  Assigns a value to a COM component's property

Description

void com_propset ( resource com_object, string property, mixed value)

This function is an alias for com_set().

com_release

(4.1.0 - 4.3.0 only)

com_release --  Decreases the components reference counter.

Description

void com_release ( void)

Decreases the components reference counter.

com_set

(PHP 3>= 3.0.3, 4.0.5 - 4.3.0 only)

com_set --  Assigns a value to a COM component's property

Description

void com_set ( resource com_object, string property, mixed value)

Sets the value of the property of the COM component referenced by com_object. Returns the newly set value if succeeded, FALSE on error.

IX. Classes e Objetos

Introdução

Estas funções permitem obter informações sobre classes e instâncias de objetos. Você pode obter o nome da classe ao qual um objeto pertence, bem como suas propriedades e métodos. Usando estas funções, você pode descobrir não apenas a classe de um objeto, mas também seu parentesco (no caso, de qual objeto de classe ele extende).


Exemplos

Neste exemplo, nós primeiramente definiremos uma classe base e uma extensão da classe. A classe base descreve um vegetal comum, que é comestível ou não e que tem sua cor. A sub-classe Espinafre adiciona um método para cozinhá-lo e outro para descobrir se ele está cozido.

Exemplo 1. classes.inc

<?php

// base class with member properties and methods
class Vegetable {

    var $edible;
    var $color;

    function Vegetable( $edible, $color="green" ) {
        $this->edible = $edible;
        $this->color = $color;
    }

    function is_edible() {
        return $this->edible;
    }

    function what_color() {
        return $this->color;
    }
    
} // end of class Vegetable

// extends the base class
class Spinach extends Vegetable {

    var $cooked = false;

    function Spinach() {
        $this->Vegetable( true, "green" );
    }

    function cook_it() {
        $this->cooked = true;
    }

    function is_cooked() {
        return $this->cooked;
    }
    
} // end of class Spinach

?>

Nós instânciamos 2 objetos destas classes e exibimos informações sobre elas, incluindo o parentesco de suas classes. Nós também definimos algumas funções úteis, principalmente ter uma boa saída de variáveis.

Exemplo 2. test_script.php

<pre>
<?php

include "classes.inc";

// utility functions

function print_vars($obj) {
    $arr = get_object_vars($obj);
    while (list($prop, $val) = each($arr))
        echo "\t$prop = $val\n";
}

function print_methods($obj) {
    $arr = get_class_methods(get_class($obj));
    foreach ($arr as $method)
        echo "\tfunction $method()\n";
}

function class_parentage($obj, $class) {
    global $$obj;
    if (is_subclass_of($$obj, $class)) {
        echo "Object $obj belongs to class ".get_class($$obj);
        echo " a subclass of $class\n";
    } else {
        echo "Object $obj does not belong to a subclass of $class\n";
    }
}

// instantiate 2 objects

$veggie = new Vegetable(true,"blue");
$leafy = new Spinach();

// print out information about objects
echo "veggie: CLASS ".get_class($veggie)."\n";
echo "leafy: CLASS ".get_class($leafy);
echo ", PARENT ".get_parent_class($leafy)."\n";

// show veggie properties
echo "\nveggie: Properties\n";
print_vars($veggie);

// and leafy methods
echo "\nleafy: Methods\n";
print_methods($leafy);

echo "\nParentage:\n";
class_parentage("leafy", "Spinach");
class_parentage("leafy", "Vegetable");
?>
</pre>

Uma coisa importante para notar no exemplo acima é que o objeto $leafy é uma instância da classe Espinafre que é uma subclasse de Vegetal, então a última parte do script acima retornará:

[...]
Parentage:
Object leafy does not belong to a subclass of Spinach
Object leafy belongs to class spinach a subclass of Vegetable

Índice
call_user_method_array --  Chama métodos de usuário dado uma matriz de parâmetros [obsoleto]
call_user_method --  Chama um método de usuário num objeto específico [obsoleto]
class_exists -- Checa se uma classe foi definida
get_class_methods -- Retorna uma matriz associativa com nomes de métodos da classe
get_class_vars --  Retorna uma matriz das propriedades padrão da classe
get_class -- Retorna o nome da classe de um objeto
get_declared_classes -- Retorna uma matriz com os nomes das classes definidas
get_object_vars -- Retorna uma matriz associativa com as propriedades do objeto
get_parent_class -- Devolve o nome da classe pai para o objeto ou classe
is_a --  Retorna TRUE se o objeto é desta classe ou tem esta classe como uma de suas classes pai.
is_subclass_of --  Retorna TRUE se o objeto tem esta classe como uma de suas classes pai
method_exists -- Checa se o método da classe existe

call_user_method_array

(PHP 4 >= 4.0.5)

call_user_method_array --  Chama métodos de usuário dado uma matriz de parâmetros [obsoleto]

Descrição

mixed call_user_method_array ( string method_name, object obj [, array paramarr])

Atenção

A funçãocall_user_method_array() é obselta a partir do PHP 4.1.0. Utilize a variante call_user_func_array() com a sintaxe array(&$obj, "method_name").

Chama o método method_name do objeto de usuáro obj, usando os parâmetros em paramarr.

Veja também call_user_func_array(), call_user_func() e call_user_method().

Nota: Esta função foi adicionada no código CVS antes da liberaçao do PHP 4.0.4pl1

call_user_method

(PHP 3>= 3.0.3, PHP 4 )

call_user_method --  Chama um método de usuário num objeto específico [obsoleto]

Descrição

mixed call_user_method ( string method_name, object obj [, mixed parameter [, mixed ...]])

Atenção

A função call_user_method() é obsoleta desde o PHP 4.1.0, portanto utilize a variante call_user_func() com a sintaxe array(&$obj, "method_name").

Chama o método method_name do objeto de usuário obj. Um exemplo de seu uso segue abaixo, onde nós definimos uma classe, instanciamos um objeto e usamos call_user_method() para chamar indiretamente seu método print_info.

<?php
class Country {
    var $NAME;
    var $TLD;

    function Country($name, $tld) {
        $this->NAME = $name;
        $this->TLD = $tld;
    }

    function print_info($prestr="") {
        echo $prestr."Country: ".$this->NAME."\n";
        echo $prestr."Top Level Domain: ".$this->TLD."\n";
    }
}

$cntry = new Country("Peru","pe");

echo "* Chamando o método diretamente\n";
$cntry->print_info();

echo "\n* Chamando o método indiretamente\n";
call_user_method ("print_info", $cntry, "\t");
?>

Veja também call_user_func_array(), call_user_func() e call_user_method_array().

class_exists

(PHP 4 )

class_exists -- Checa se uma classe foi definida

Descrição

bool class_exists ( string class_name)

Esta função retorna TRUE se a classe dada por class_name foi definida, caso contrário retorna FALSE.

get_class_methods

(PHP 4 )

get_class_methods -- Retorna uma matriz associativa com nomes de métodos da classe

Descrição

array get_class_methods ( mixed class_name)

Esta função retorna uma matriz com nomes dos métodos definidos para a classe especificada por class_name.

Nota: A partir do PHP 4.0.6, você pode especificar o próprio objeto em vez no nome da classe em class_name. Por exemplo:

$class_methods = get_class_methods($my_class); // veja um exemplo completo abaixo

Exemplo 1. Exemploget_class_methods()

<?php

class myclass {
    // constructor
    function myclass() {
        return(TRUE);
    }

    // method 1
    function myfunc1() {
        return(TRUE);
    }

    // method 2
    function myfunc2() {
        return(TRUE);
    }
}

$my_object = new myclass();

$class_methods = get_class_methods(get_class($my_object));

foreach ($class_methods as $method_name) {
    echo "$method_name\n";
}

?>

Produzirá:

myclass
myfunc1
myfunc2

Veja também get_class_vars() e get_object_vars().

get_class_vars

(PHP 4 )

get_class_vars --  Retorna uma matriz das propriedades padrão da classe

Descrição

array get_class_vars ( string class_name)

Esta função retornará uma matriz associativa com as propriedades padrão da classe. Os elementos resultantes da matriz estão na forma nome_variavel => valor.

Nota: Variáveis de classe não iniciadas não serão exibidos por get_class_vars().

Exemplo 1. Exemplo get_class_vars()

<?php

class myclass {

    var $var1; // esta não tem valor default...
    var $var2 = "xyz";
    var $var3 = 100;

    // construtor
    function myclass() {
        return(TRUE);
    }

}

$my_class = new myclass();

$class_vars = get_class_vars(get_class($my_class));

foreach ($class_vars as $name => $value) {
    echo "$name : $value\n";
}

?>

Produzirá:

var2 : xyz
var3 : 100

Veja também get_class_methods() e get_object_vars()

get_class

(PHP 4 )

get_class -- Retorna o nome da classe de um objeto

Descrição

string get_class ( object obj)

Esta função retorna o nome da classe da qual o objeto obj é instância. Retorna FALSE se obj não é um objeto.

Nota: get_class() retorna um nome de uma classe definida pelo usuário em minúsculas. Uma classe definida em uma extensão do PHP é retornada em sua notação original.

Veja também get_parent_class(), gettype() e is_subclass_of().

get_declared_classes

(PHP 4 )

get_declared_classes -- Retorna uma matriz com os nomes das classes definidas

Descrição

array get_declared_classes ( void)

Esta função retorna uma matriz com os nomes das classes declaradas no script em execução.

Nota: A partir do PHP 4.0.1pl2, três classes extras são retornadas no início da matriz: stdClass (definida em Zend/zend.c), OverloadedTestClass (definida em ext/standard/basic_functions.c) e Directory (definida em ext/standard/dir.c).

Note também que, dependendo de quais bibliotecas você tenha compilado no PHP, classes adicionais poderão estar presentes. Isto significa que você não será capaz de distinguir suas próprias classes usando estes nomes. Há uma lista de classes predefinidas na seção Classes Predefinidas dos apêndices.

get_object_vars

(PHP 4 )

get_object_vars -- Retorna uma matriz associativa com as propriedades do objeto

Descrição

array get_object_vars ( object obj)

Esta função retorna uma matriz associativa com as propriedades definidas do objeto informado em obj. Se variáveis declaradas na classe de qual obj é uma instância e que não tenham valores assimilados, esses não serão retornados na matriz.

Exemplo 1. Uso de get_object_vars()

<?php
class Point2D {
    var $x, $y;
    var $label;

    function Point2D($x, $y) {
        $this->x = $x;
        $this->y = $y;
    }

    function setLabel($label) {
        $this->label = $label;
    }

    function getPoint() {
        return array("x" => $this->x,
                     "y" => $this->y,
                     "label" => $this->label);
    }
}

// "$label" is declared but not defined
$p1 = new Point2D(1.233, 3.445);
print_r(get_object_vars($p1));

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

?>
A saída do programa acima será:
Array
 (
     [x] => 1.233
     [y] => 3.445
 )

 Array
 (
     [x] => 1.233
     [y] => 3.445
     [label] => point #1
 )

Veja também get_class_methods() e get_class_vars()!

get_parent_class

(PHP 4 )

get_parent_class -- Devolve o nome da classe pai para o objeto ou classe

Descrição

string get_parent_class ( mixed obj)

Se obj é um objeto, retorna o nome da classe pai da classe da qual o obj é uma instância.

Seobj é uma string, retorna o nome da classe pai da classe com aquele nome. Esta funcionalidade foi adicionada no PHP 4.0.5.

Veja também get_class() e is_subclass_of()

is_a

(PHP 4 >= 4.2.0)

is_a --  Retorna TRUE se o objeto é desta classe ou tem esta classe como uma de suas classes pai.

Descrição

bool is_a ( object object, string class_name)

Esta função retorna TRUE se o objeto é desta classe ou tem esta classe como uma de suas classes pai, caso contrário retorna FALSE.

Veja também get_class(), get_parent_class(), e is_subclass_of().

is_subclass_of

(PHP 4 )

is_subclass_of --  Retorna TRUE se o objeto tem esta classe como uma de suas classes pai

Descrição

bool is_subclass_of ( object object, string class_name)

Esta função retorna TRUE se o objeto object, pertence a uma classe que é uma sub-classe de class_name, caso contrário retorna FALSE.

Veja também get_class(), get_parent_class() e is_a().

method_exists

(PHP 4 )

method_exists -- Checa se o método da classe existe

Descrição

bool method_exists ( object object, string method_name)

Esta função retorma TRUE se o método dado pelo method_name foi definido para o dado object, caso contrário FALSE.

X. ClibPDF functions

Introdução

ClibPDF lets you create PDF documents with PHP. ClibPDF functionality and API are similar to PDFlib. This documentation should be read alongside the ClibPDF manual since it explains the library in much greater detail.

Many functions in the native ClibPDF and the PHP module, as well as in PDFlib, have the same name. All functions except for cpdf_open() take the handle for the document as their first parameter.

Currently this handle is not used internally since ClibPDF does not support the creation of several PDF documents at the same time. Actually, you should not even try it, the results are unpredictable. I can't oversee what the consequences in a multi threaded environment are. According to the author of ClibPDF this will change in one of the next releases (current version when this was written is 1.10). If you need this functionality use the pdflib module.

A nice feature of ClibPDF (and PDFlib) is the ability to create the pdf document completely in memory without using temporary files. It also provides the ability to pass coordinates in a predefined unit length. (This feature can also be simulated by pdf_translate() when using the PDFlib functions.)

Another nice feature of ClibPDF is the fact that any page can be modified at any time even if a new page has been already opened. The function cpdf_set_current_page() allows to leave the current page and presume modifying an other page.

Most of the functions are fairly easy to use. The most difficult part is probably creating a very simple PDF document at all. The following example should help you to get started. It creates a document with one page. The page contains the text "Times-Roman" in an outlined 30pt font. The text is underlined.


Requisitos

In order to use the ClibPDF functions you need to install the ClibPDF package. It is available for download from FastIO, but requires that you purchase a license for commercial use. PHP requires that you use cpdflib >= 2.


Instalação

To get these functions to work, you have to compile PHP with --with-cpdflib[=DIR]. DIR is the cpdflib install directory, defaults to /usr. In addition you can specify the jpeg library and the tiff library for ClibPDF to use. To do so add to your configure line the options --with-jpeg-dir[=DIR] --with-tiff-dir[=DIR].


Configuração durante execução

Esta extenção não define nenhum parâmetro de configuração no php.ini.


Constantes Predefinidas

As contantes abaixo são definidas por esta extensão e somente estarão disponíveis quando a extensão foi compilada com o PHP ou carregada dinamicamente durante a execução.

CPDF_PM_NONE (integer)

CPDF_PM_OUTLINES (integer)

CPDF_PM_THUMBS (integer)

CPDF_PM_FULLSCREEN (integer)

CPDF_PL_SINGLE (integer)

CPDF_PL_1COLUMN (integer)

CPDF_PL_2LCOLUMN (integer)

CPDF_PL_2RCOLUMN (integer)


Exemplos

Exemplo 1. Simple ClibPDF Example

<?php
$cpdf = cpdf_open(0);
cpdf_page_init($cpdf, 1, 0, 595, 842, 1.0);
cpdf_add_outline($cpdf, 0, 0, 0, 1, "Page 1");
cpdf_begin_text($cpdf);
cpdf_set_font($cpdf, "Times-Roman", 30, "WinAnsiEncoding");
cpdf_set_text_rendering($cpdf, 1);
cpdf_text($cpdf, "Times Roman outlined", 50, 750);
cpdf_end_text($cpdf);
cpdf_moveto($cpdf, 50, 740);
cpdf_lineto($cpdf, 330, 740);
cpdf_stroke($cpdf);
cpdf_finalize($cpdf);
Header("Content-type: application/pdf");
cpdf_output_buffer($cpdf);
cpdf_close($cpdf);
?>

The pdflib distribution contains a more complex example which creates a series of pages with an analog clock. Here is that example converted into PHP using the ClibPDF extension:

Exemplo 2. pdfclock example from pdflib 2.0 distribution

<?php
$radius = 200;
$margin = 20;
$pagecount = 40;

$pdf = cpdf_open(0);
cpdf_set_creator($pdf, "pdf_clock.php3");
cpdf_set_title($pdf, "Analog Clock");
  
while($pagecount-- > 0) {
  cpdf_page_init($pdf, $pagecount+1, 0, 2 * ($radius + $margin), 2 * ($radius + $margin), 1.0);
  
  cpdf_set_page_animation($pdf, 4, 0.5, 0, 0, 0);  /* wipe */
  
  cpdf_translate($pdf, $radius + $margin, $radius + $margin);
  cpdf_save($pdf);
  cpdf_setrgbcolor($pdf, 0.0, 0.0, 1.0);
  
  /* minute strokes */
  cpdf_setlinewidth($pdf, 2.0);
  for ($alpha = 0; $alpha < 360; $alpha += 6)
    {
    cpdf_rotate($pdf, 6.0);
    cpdf_moveto($pdf, $radius, 0.0);
    cpdf_lineto($pdf, $radius-$margin/3, 0.0);
    cpdf_stroke($pdf);
    }
  
  cpdf_restore($pdf);
  cpdf_save($pdf);
 
  /* 5 minute strokes */
  cpdf_setlinewidth($pdf, 3.0);
  for ($alpha = 0; $alpha < 360; $alpha += 30)
  {
    cpdf_rotate($pdf, 30.0);
    cpdf_moveto($pdf, $radius, 0.0);
    cpdf_lineto($pdf, $radius-$margin, 0.0);
    cpdf_stroke($pdf);
  }

  $ltime = getdate();

  /* draw hour hand */
  cpdf_save($pdf);
  cpdf_rotate($pdf, -(($ltime['minutes']/60.0) + $ltime['hours'] - 3.0) * 30.0);
  cpdf_moveto($pdf, -$radius/10, -$radius/20);
  cpdf_lineto($pdf, $radius/2, 0.0);
  cpdf_lineto($pdf, -$radius/10, $radius/20);
  cpdf_closepath($pdf);
  cpdf_fill($pdf);
  cpdf_restore($pdf);

  /* draw minute hand */
  cpdf_save($pdf);
  cpdf_rotate($pdf, -(($ltime['seconds']/60.0) + $ltime['minutes'] - 15.0) * 6.0);
  cpdf_moveto($pdf, -$radius/10, -$radius/20);
  cpdf_lineto($pdf, $radius * 0.8, 0.0);
  cpdf_lineto($pdf, -$radius/10, $radius/20);
  cpdf_closepath($pdf);
  cpdf_fill($pdf);
  cpdf_restore($pdf);

  /* draw second hand */
  cpdf_setrgbcolor($pdf, 1.0, 0.0, 0.0);
  cpdf_setlinewidth($pdf, 2);
  cpdf_save($pdf);
  cpdf_rotate($pdf, -(($ltime['seconds'] - 15.0) * 6.0));
  cpdf_moveto($pdf, -$radius/5, 0.0);
  cpdf_lineto($pdf, $radius, 0.0);
  cpdf_stroke($pdf);
  cpdf_restore($pdf);

  /* draw little circle at center */
  cpdf_circle($pdf, 0, 0, $radius/30);
  cpdf_fill($pdf);

  cpdf_restore($pdf);

  cpdf_finalize_page($pdf, $pagecount+1);
}

cpdf_finalize($pdf);
Header("Content-type: application/pdf");
cpdf_output_buffer($pdf);
cpdf_close($pdf);
?>

Veja Também

See also the PDFlib extension documentation.

Índice
cpdf_add_annotation -- Adds annotation
cpdf_add_outline -- Adds bookmark for current page
cpdf_arc -- Draws an arc
cpdf_begin_text -- Starts text section
cpdf_circle -- Draw a circle
cpdf_clip -- Clips to current path
cpdf_close -- Closes the pdf document
cpdf_closepath_fill_stroke -- Close, fill and stroke current path
cpdf_closepath_stroke -- Close path and draw line along path
cpdf_closepath -- Close path
cpdf_continue_text -- Output text in next line
cpdf_curveto -- Draws a curve
cpdf_end_text -- Ends text section
cpdf_fill_stroke -- Fill and stroke current path
cpdf_fill -- Fill current path
cpdf_finalize_page -- Ends page
cpdf_finalize -- Ends document
cpdf_global_set_document_limits -- Sets document limits for any pdf document
cpdf_import_jpeg -- Opens a JPEG image
cpdf_lineto -- Draws a line
cpdf_moveto -- Sets current point
cpdf_newpath -- Starts a new path
cpdf_open -- Opens a new pdf document
cpdf_output_buffer -- Outputs the pdf document in memory buffer
cpdf_page_init -- Starts new page
cpdf_place_inline_image -- Places an image on the page
cpdf_rect -- Draw a rectangle
cpdf_restore -- Restores formerly saved environment
cpdf_rlineto -- Draws a line
cpdf_rmoveto -- Sets current point
cpdf_rotate_text --  Sets text rotation angle
cpdf_rotate -- Sets rotation
cpdf_save_to_file -- Writes the pdf document into a file
cpdf_save -- Saves current environment
cpdf_scale -- Sets scaling
cpdf_set_action_url --  Sets hyperlink
cpdf_set_char_spacing -- Sets character spacing
cpdf_set_creator -- Sets the creator field in the pdf document
cpdf_set_current_page -- Sets current page
cpdf_set_font_directories --  Sets directories to search when using external fonts
cpdf_set_font_map_file --  Sets fontname to filename translation map when using external fonts
cpdf_set_font -- Select the current font face and size
cpdf_set_horiz_scaling -- Sets horizontal scaling of text
cpdf_set_keywords -- Sets the keywords field of the pdf document
cpdf_set_leading -- Sets distance between text lines
cpdf_set_page_animation -- Sets duration between pages
cpdf_set_subject -- Sets the subject field of the pdf document
cpdf_set_text_matrix -- Sets the text matrix
cpdf_set_text_pos -- Sets text position
cpdf_set_text_rendering -- Determines how text is rendered
cpdf_set_text_rise -- Sets the text rise
cpdf_set_title -- Sets the title field of the pdf document
cpdf_set_viewer_preferences --  How to show the document in the viewer
cpdf_set_word_spacing -- Sets spacing between words
cpdf_setdash -- Sets dash pattern
cpdf_setflat -- Sets flatness
cpdf_setgray_fill -- Sets filling color to gray value
cpdf_setgray_stroke -- Sets drawing color to gray value
cpdf_setgray -- Sets drawing and filling color to gray value
cpdf_setlinecap -- Sets linecap parameter
cpdf_setlinejoin -- Sets linejoin parameter
cpdf_setlinewidth -- Sets line width
cpdf_setmiterlimit -- Sets miter limit
cpdf_setrgbcolor_fill -- Sets filling color to rgb color value
cpdf_setrgbcolor_stroke -- Sets drawing color to rgb color value
cpdf_setrgbcolor -- Sets drawing and filling color to rgb color value
cpdf_show_xy -- Output text at position
cpdf_show -- Output text at current position
cpdf_stringwidth -- Returns width of text in current font
cpdf_stroke -- Draw line along path
cpdf_text -- Output text with parameters
cpdf_translate -- Sets origin of coordinate system

cpdf_add_annotation

(PHP 3>= 3.0.12, PHP 4 )

cpdf_add_annotation -- Adds annotation

Description

void cpdf_add_annotation ( int pdf document, float llx, float lly, float urx, float ury, string title, string content [, int mode])

The cpdf_add_annotation() adds a note with the lower left corner at (llx, lly) and the upper right corner at (urx, ury).

The optional parameter mode determines the unit length. If it's 0 or omitted the default unit as specified for the page is used. Otherwise the coordinates are measured in postscript points disregarding the current unit.

cpdf_add_outline

(PHP 3>= 3.0.9, PHP 4 )

cpdf_add_outline -- Adds bookmark for current page

Description

void cpdf_add_outline ( int pdf document, string text)

The cpdf_add_outline() function adds a bookmark with text text that points to the current page.

Exemplo 1. Adding a page outline

<?php
$cpdf = cpdf_open(0);
cpdf_page_init($cpdf, 1, 0, 595, 842);
cpdf_add_outline($cpdf, 0, 0, 0, 1, "Page 1");
// ...
// some drawing
// ...
cpdf_finalize($cpdf);
Header("Content-type: application/pdf");
cpdf_output_buffer($cpdf);
cpdf_close($cpdf);
?>

cpdf_arc

(PHP 3>= 3.0.8, PHP 4 )

cpdf_arc -- Draws an arc

Description

void cpdf_arc ( int pdf document, float x-coor, float y-coor, float radius, float start, float end [, int mode])

The cpdf_arc() function draws an arc with center at point (x-coor, y-coor) and radius radius, starting at angle start and ending at angle end.

The optional parameter mode determines the unit length. If it's 0 or omitted the default unit as specified for the page is used. Otherwise the coordinates are measured in postscript points disregarding the current unit.

See also cpdf_circle().

cpdf_begin_text

(PHP 3>= 3.0.8, PHP 4 )

cpdf_begin_text -- Starts text section

Description

void cpdf_begin_text ( int pdf document)

The cpdf_begin_text() function starts a text section. It must be ended with cpdf_end_text().

Exemplo 1. Text output

<?php
cpdf_begin_text($pdf);
cpdf_set_font($pdf, 16, "Helvetica", "WinAnsiEncoding");
cpdf_text($pdf, 100, 100, "Some text");
cpdf_end_text($pdf)
?>

See also cpdf_end_text().

cpdf_circle

(PHP 3>= 3.0.8, PHP 4 )

cpdf_circle -- Draw a circle

Description

void cpdf_circle ( int pdf document, float x-coor, float y-coor, float radius [, int mode])

The cpdf_circle() function draws a circle with center at point (x-coor, y-coor) and radius radius.

The optional parameter mode determines the unit length. If it's 0 or omitted the default unit as specified for the page is used. Otherwise the coordinates are measured in postscript points disregarding the current unit.

See also cpdf_arc().

cpdf_clip

(PHP 3>= 3.0.8, PHP 4 )

cpdf_clip -- Clips to current path

Description

void cpdf_clip ( int pdf document)

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

cpdf_close

(PHP 3>= 3.0.8, PHP 4 )

cpdf_close -- Closes the pdf document

Description

void cpdf_close ( int pdf document)

The cpdf_close() function closes the pdf document. This should be the last function even after cpdf_finalize(), cpdf_output_buffer() and cpdf_save_to_file().

See also cpdf_open().

cpdf_closepath_fill_stroke

(PHP 3>= 3.0.8, PHP 4 )

cpdf_closepath_fill_stroke -- Close, fill and stroke current path

Description

void cpdf_closepath_fill_stroke ( int pdf document)

The cpdf_closepath_fill_stroke() function closes, fills the interior of the current path with the current fill color and draws current path.

See also cpdf_closepath(), cpdf_stroke(), cpdf_fill(), cpdf_setgray_fill(), cpdf_setgray(), cpdf_setrgbcolor_fill(), cpdf_setrgbcolor().

cpdf_closepath_stroke

(PHP 3>= 3.0.8, PHP 4 )

cpdf_closepath_stroke -- Close path and draw line along path

Description

void cpdf_closepath_stroke ( int pdf document)

The cpdf_closepath_stroke() function is a combination of cpdf_closepath() and cpdf_stroke(). Then clears the path.

See also cpdf_closepath(), cpdf_stroke().

cpdf_closepath

(PHP 3>= 3.0.8, PHP 4 )

cpdf_closepath -- Close path

Description

void cpdf_closepath ( int pdf document)

The cpdf_closepath() function closes the current path.

cpdf_continue_text

(PHP 3>= 3.0.8, PHP 4 )

cpdf_continue_text -- Output text in next line

Description

void cpdf_continue_text ( int pdf document, string text)

The cpdf_continue_text() function outputs the string in text in the next line.

See also cpdf_show_xy(), cpdf_text(), cpdf_set_leading(), cpdf_set_text_pos().

cpdf_curveto

(PHP 3>= 3.0.8, PHP 4 )

cpdf_curveto -- Draws a curve

Description

void cpdf_curveto ( int pdf document, float x1, float y1, float x2, float y2, float x3, float y3 [, int mode])

The cpdf_curveto() function draws a Bezier curve from the current point to the point (x3, y3) using (x1, y1) and (x2, y2) as control points.

The optional parameter mode determines the unit length. If it's 0 or omitted the default unit as specified for the page is used. Otherwise the coordinates are measured in postscript points disregarding the current unit.

See also cpdf_moveto(), cpdf_rmoveto(), cpdf_rlineto(), cpdf_lineto().

cpdf_end_text

(PHP 3>= 3.0.8, PHP 4 )

cpdf_end_text -- Ends text section

Description

void cpdf_end_text ( int pdf document)

The cpdf_end_text() function ends a text section which was started with cpdf_begin_text().

Exemplo 1. Text output

<?php
cpdf_begin_text($pdf);
cpdf_set_font($pdf, 16, "Helvetica", "WinAnsiEncoding");
cpdf_text($pdf, 100, 100, "Some text");
cpdf_end_text($pdf)
?>

See also cpdf_begin_text().

cpdf_fill_stroke

(PHP 3>= 3.0.8, PHP 4 )

cpdf_fill_stroke -- Fill and stroke current path

Description

void cpdf_fill_stroke ( int pdf document)

The cpdf_fill_stroke() function fills the interior of the current path with the current fill color and draws current path.

See also cpdf_closepath(), cpdf_stroke(), cpdf_fill(), cpdf_setgray_fill(), cpdf_setgray(), cpdf_setrgbcolor_fill(), cpdf_setrgbcolor().

cpdf_fill

(PHP 3>= 3.0.8, PHP 4 )

cpdf_fill -- Fill current path

Description

void cpdf_fill ( int pdf document)

The cpdf_fill() function fills the interior of the current path with the current fill color.

See also cpdf_closepath(), cpdf_stroke(), cpdf_setgray_fill(), cpdf_setgray(), cpdf_setrgbcolor_fill(), cpdf_setrgbcolor().

cpdf_finalize_page

(PHP 3>= 3.0.10, PHP 4 )

cpdf_finalize_page -- Ends page

Description

void cpdf_finalize_page ( int pdf document, int page number)

The cpdf_finalize_page() function ends the page with page number page number.

This function is only for saving memory. A finalized page takes less memory but cannot be modified anymore.

See also cpdf_page_init().

cpdf_finalize

(PHP 3>= 3.0.8, PHP 4 )

cpdf_finalize -- Ends document

Description

void cpdf_finalize ( int pdf document)

The cpdf_finalize() function ends the document. You still have to call cpdf_close()

See also cpdf_close().

cpdf_global_set_document_limits

(PHP 4 )

cpdf_global_set_document_limits -- Sets document limits for any pdf document

Description

void cpdf_global_set_document_limits ( int maxpages, int maxfonts, int maximages, int maxannotations, int maxobjects)

The cpdf_global_set_document_limits() function sets several document limits. This function has to be called before cpdf_open() to take effect. It sets the limits for any document open afterwards.

See also cpdf_open().

cpdf_import_jpeg

(PHP 3>= 3.0.9, PHP 4 )

cpdf_import_jpeg -- Opens a JPEG image

Description

int cpdf_import_jpeg ( int pdf document, string file name, float x-coor, float y-coor, float angle, float width, float height, float x-scale, float y-scale [, int mode])

The cpdf_import_jpeg() function opens an image stored in the file with the name file name. The format of the image has to be jpeg. The image is placed on the current page at position (x-coor, y-coor). The image is rotated by angle degrees.

The optional parameter mode determines the unit length. If it's 0 or omitted the default unit as specified for the page is used. Otherwise the coordinates are measured in postscript points disregarding the current unit.

See also cpdf_place_inline_image().

cpdf_lineto

(PHP 3>= 3.0.8, PHP 4 )

cpdf_lineto -- Draws a line

Description

void cpdf_lineto ( int pdf document, float x-coor, float y-coor [, int mode])

The cpdf_lineto() function draws a line from the current point to the point with coordinates (x-coor, y-coor).

The optional parameter mode determines the unit length. If it's 0 or omitted the default unit as specified for the page is used. Otherwise the coordinates are measured in postscript points disregarding the current unit.

See also cpdf_moveto(), cpdf_rmoveto(), cpdf_curveto().

cpdf_moveto

(PHP 3>= 3.0.8, PHP 4 )

cpdf_moveto -- Sets current point

Description

void cpdf_moveto ( int pdf document, float x-coor, float y-coor [, int mode])

The cpdf_moveto() function set the current point to the coordinates x-coor and y-coor.

The optional parameter mode determines the unit length. If it's 0 or omitted the default unit as specified for the page is used. Otherwise the coordinates are measured in postscript points disregarding the current unit.

cpdf_newpath

(PHP 3>= 3.0.9, PHP 4 )

cpdf_newpath -- Starts a new path

Description

void cpdf_newpath ( int pdf document)

The cpdf_newpath() starts a new path on the document given by the pdf document parameter.

cpdf_open

(PHP 3>= 3.0.8, PHP 4 )

cpdf_open -- Opens a new pdf document

Description

int cpdf_open ( int compression [, string filename])

The cpdf_open() function opens a new pdf document. The first parameter turns document compression on if it is unequal to 0. The second optional parameter sets the file in which the document is written. If it is omitted the document is created in memory and can either be written into a file with the cpdf_save_to_file() or written to standard output with cpdf_output_buffer().

Nota: The return value will be needed in further versions of ClibPDF as the first parameter in all other functions which are writing to the pdf document.

The ClibPDF library takes the filename "-" as a synonym for stdout. If PHP is compiled as an apache module this will not work because the way ClibPDF outputs to stdout does not work with apache. You can solve this problem by skipping the filename and using cpdf_output_buffer() to output the pdf document.

See also cpdf_close(), cpdf_output_buffer().

cpdf_output_buffer

(PHP 3>= 3.0.9, PHP 4 )

cpdf_output_buffer -- Outputs the pdf document in memory buffer

Description

void cpdf_output_buffer ( int pdf document)

The cpdf_output_buffer() function outputs the pdf document to stdout. The document has to be created in memory which is the case if cpdf_open() has been called with no filename parameter.

See also cpdf_open().

cpdf_page_init

(PHP 3>= 3.0.8, PHP 4 )

cpdf_page_init -- Starts new page

Description

void cpdf_page_init ( int pdf document, int page number, int orientation, float height, float width [, float unit])

The cpdf_page_init() function starts a new page with height height and width width. The page has number page number and orientation orientation. orientation can be 0 for portrait and 1 for landscape. The last optional parameter unit sets the unit for the coordinate system. The value should be the number of postscript points per unit. Since one inch is equal to 72 points, a value of 72 would set the unit to one inch. The default is also 72.

See also cpdf_set_current_page().

cpdf_place_inline_image

(PHP 3>= 3.0.9, PHP 4 )

cpdf_place_inline_image -- Places an image on the page

Description

void cpdf_place_inline_image ( int pdf document, int image, float x-coor, float y-coor, float angle, float width, float height [, int mode])

The cpdf_place_inline_image() function places an image created with the php image functions on the page at position (x-coor, y-coor). The image can be scaled at the same time.

The optional parameter mode determines the unit length. If it's 0 or omitted the default unit as specified for the page is used. Otherwise the coordinates are measured in postscript points disregarding the current unit.

See also cpdf_import_jpeg().

cpdf_rect

(PHP 3>= 3.0.8, PHP 4 )

cpdf_rect -- Draw a rectangle

Description

void cpdf_rect ( int pdf document, float x-coor, float y-coor, float width, float height [, int mode])

The cpdf_rect() function draws a rectangle with its lower left corner at point (x-coor, y-coor). This width is set to width. This height is set to height.

The optional parameter mode determines the unit length. If it's 0 or omitted the default unit as specified for the page is used. Otherwise the coordinates are measured in postscript points disregarding the current unit.

cpdf_restore

(PHP 3>= 3.0.8, PHP 4 )

cpdf_restore -- Restores formerly saved environment

Description

void cpdf_restore ( int pdf document)

The cpdf_restore() function restores the environment saved with cpdf_save(). It works like the postscript command grestore. Very useful if you want to translate or rotate an object without effecting other objects.

Exemplo 1. Save/Restore

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

See also cpdf_save().

cpdf_rlineto

(PHP 3>= 3.0.9, PHP 4 )

cpdf_rlineto -- Draws a line

Description

void cpdf_rlineto ( int pdf document, float x-coor, float y-coor [, int mode])

The cpdf_rlineto() function draws a line from the current point to the relative point with coordinates (x-coor, y-coor).

The optional parameter mode determines the unit length. If it's 0 or omitted the default unit as specified for the page is used. Otherwise the coordinates are measured in postscript points disregarding the current unit.

See also cpdf_moveto(), cpdf_rmoveto(), cpdf_curveto().

cpdf_rmoveto

(PHP 3>= 3.0.9, PHP 4 )

cpdf_rmoveto -- Sets current point

Description

void cpdf_rmoveto ( int pdf document, float x-coor, float y-coor [, int mode])

The cpdf_rmoveto() function set the current point relative to the coordinates x-coor and y-coor.

The optional parameter mode determines the unit length. If it's 0 or omitted the default unit as specified for the page is used. Otherwise the coordinates are measured in postscript points disregarding the current unit.

See also cpdf_moveto().

cpdf_rotate_text

(PHP 3>= 3.0.9, PHP 4 )

cpdf_rotate_text --  Sets text rotation angle

Description

void cpdf_rotate_text ( int pdfdoc, float angle)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

cpdf_rotate

(PHP 3>= 3.0.8, PHP 4 )

cpdf_rotate -- Sets rotation

Description

void cpdf_rotate ( int pdf document, float angle)

The cpdf_rotate() function set the rotation in degrees to angle.

cpdf_save_to_file

(PHP 3>= 3.0.8, PHP 4 )

cpdf_save_to_file -- Writes the pdf document into a file

Description

void cpdf_save_to_file ( int pdf document, string filename)

The cpdf_save_to_file() function outputs the pdf document into a file if it has been created in memory.

This function is not needed if the pdf document has been open by specifying a filename as a parameter of cpdf_open().

See also cpdf_output_buffer(), cpdf_open().

cpdf_save

(PHP 3>= 3.0.8, PHP 4 )

cpdf_save -- Saves current environment

Description

void cpdf_save ( int pdf document)

The cpdf_save() function saves the current environment. It works like the postscript command gsave. Very useful if you want to translate or rotate an object without effecting other objects.

See also cpdf_restore().

cpdf_scale

(PHP 3>= 3.0.8, PHP 4 )

cpdf_scale -- Sets scaling

Description

void cpdf_scale ( int pdf document, float x-scale, float y-scale)

The cpdf_scale() function set the scaling factor in both directions.

cpdf_set_action_url

(PHP 3>= 3.0.9, PHP 4 )

cpdf_set_action_url --  Sets hyperlink

Description

void cpdf_set_action_url ( int pdfdoc, float xll, float yll, float xur, float xur, string url [, int mode])

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

cpdf_set_char_spacing

(PHP 3>= 3.0.8, PHP 4 )

cpdf_set_char_spacing -- Sets character spacing

Description

void cpdf_set_char_spacing ( int pdf document, float space)

The cpdf_set_char_spacing() function sets the spacing between characters.

See also cpdf_set_word_spacing(), cpdf_set_leading().

cpdf_set_creator

(PHP 3>= 3.0.8, PHP 4 )

cpdf_set_creator -- Sets the creator field in the pdf document

Description

void cpdf_set_creator ( string creator)

The cpdf_set_creator() function sets the creator of a pdf document.

See also cpdf_set_subject(), cpdf_set_title(), cpdf_set_keywords().

cpdf_set_current_page

(PHP 3>= 3.0.9, PHP 4 )

cpdf_set_current_page -- Sets current page

Description

void cpdf_set_current_page ( int pdf document, int page number)

The cpdf_set_current_page() function set the page on which all operations are performed. One can switch between pages until a page is finished with cpdf_finalize_page().

See also cpdf_finalize_page().

cpdf_set_font_directories

(PHP 4 >= 4.0.6)

cpdf_set_font_directories --  Sets directories to search when using external fonts

Description

void cpdf_set_font_directories ( int pdfdoc, string pfmdir, string pfbdir)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

cpdf_set_font_map_file

(PHP 4 >= 4.0.6)

cpdf_set_font_map_file --  Sets fontname to filename translation map when using external fonts

Description

void cpdf_set_font_map_file ( int pdfdoc, string filename)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

cpdf_set_font

(PHP 3>= 3.0.8, PHP 4 )

cpdf_set_font -- Select the current font face and size

Description

void cpdf_set_font ( int pdf document, string font name, float size, string encoding)

The cpdf_set_font() function sets the current font face, font size and encoding. Currently only the standard postscript fonts are supported.

The last parameter encoding can take the following values: "MacRomanEncoding", "MacExpertEncoding", "WinAnsiEncoding", and "NULL". "NULL" stands for the font's built-in encoding.

See the ClibPDF Manual for more information, especially how to support asian fonts.

cpdf_set_horiz_scaling

(PHP 3>= 3.0.8, PHP 4 )

cpdf_set_horiz_scaling -- Sets horizontal scaling of text

Description

void cpdf_set_horiz_scaling ( int pdf document, float scale)

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

cpdf_set_keywords

(PHP 3>= 3.0.8, PHP 4 )

cpdf_set_keywords -- Sets the keywords field of the pdf document

Description

void cpdf_set_keywords ( string keywords)

The cpdf_set_keywords() function sets the keywords of a pdf document.

See also cpdf_set_title(), cpdf_set_creator(), cpdf_set_subject().

cpdf_set_leading

(PHP 3>= 3.0.8, PHP 4 )

cpdf_set_leading -- Sets distance between text lines

Description

void cpdf_set_leading ( int pdf document, float distance)

The cpdf_set_leading() function sets the distance between text lines. This will be used if text is output by cpdf_continue_text().

See also cpdf_continue_text().

cpdf_set_page_animation

(PHP 3>= 3.0.9, PHP 4 )

cpdf_set_page_animation -- Sets duration between pages

Description

void cpdf_set_page_animation ( int pdf document, int transition, float duration)

The cpdf_set_page_animation() function set the transition between following pages.

The value of transition can be

0 for none,
1 for two lines sweeping across the screen reveal the page,
2 for multiple lines sweeping across the screen reveal the page,
3 for a box reveals the page,
4 for a single line sweeping across the screen reveals the page,
5 for the old page dissolves to reveal the page,
6 for the dissolve effect moves from one screen edge to another,
7 for the old page is simply replaced by the new page (default)

The value of duration is the number of seconds between page flipping.

cpdf_set_subject

(PHP 3>= 3.0.8, PHP 4 )

cpdf_set_subject -- Sets the subject field of the pdf document

Description

void cpdf_set_subject ( string subject)

The cpdf_set_subject() function sets the subject of a pdf document.

See also cpdf_set_title(), cpdf_set_creator(), cpdf_set_keywords().

cpdf_set_text_matrix

(PHP 3>= 3.0.8, PHP 4 )

cpdf_set_text_matrix -- Sets the text matrix

Description

void cpdf_set_text_matrix ( int pdf document, array matrix)

The cpdf_set_text_matrix() function sets a matrix which describes a transformation applied on the current text font.

cpdf_set_text_pos

(PHP 3>= 3.0.8, PHP 4 )

cpdf_set_text_pos -- Sets text position

Description

void cpdf_set_text_pos ( int pdf document, float x-coor, float y-coor [, int mode])

The cpdf_set_text_pos() function sets the position of text for the next cpdf_show() function call.

The optional parameter mode determines the unit length. If it's 0 or omitted the default unit as specified for the page is used. Otherwise the coordinates are measured in postscript points disregarding the current unit.

See also cpdf_show(), cpdf_text().

cpdf_set_text_rendering

(PHP 3>= 3.0.8, PHP 4 )

cpdf_set_text_rendering -- Determines how text is rendered

Description

void cpdf_set_text_rendering ( int pdf document, int mode)

The cpdf_set_text_rendering() function determines how text is rendered.

The possible values for mode are 0=fill text, 1=stroke text, 2=fill and stroke text, 3=invisible, 4=fill text and add it to clipping path, 5=stroke text and add it to clipping path, 6=fill and stroke text and add it to clipping path, 7=add it to clipping path.

cpdf_set_text_rise

(PHP 3>= 3.0.8, PHP 4 )

cpdf_set_text_rise -- Sets the text rise

Description

void cpdf_set_text_rise ( int pdf document, float value)

The cpdf_set_text_rise() function sets the text rising to value units.

cpdf_set_title

(PHP 3>= 3.0.8, PHP 4 )

cpdf_set_title -- Sets the title field of the pdf document

Description

void cpdf_set_title ( string title)

The cpdf_set_title() function sets the title of a pdf document.

See also cpdf_set_subject(), cpdf_set_creator(), cpdf_set_keywords().

cpdf_set_viewer_preferences

(PHP 3>= 3.0.9, PHP 4 )

cpdf_set_viewer_preferences --  How to show the document in the viewer

Description

void cpdf_set_viewer_preferences ( int pdfdoc, array preferences)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

cpdf_set_word_spacing

(PHP 3>= 3.0.8, PHP 4 )

cpdf_set_word_spacing -- Sets spacing between words

Description

void cpdf_set_word_spacing ( int pdf document, float space)

The cpdf_set_word_spacing() function sets the spacing between words.

See also cpdf_set_char_spacing(), cpdf_set_leading().

cpdf_setdash

(PHP 3>= 3.0.8, PHP 4 )

cpdf_setdash -- Sets dash pattern

Description

void cpdf_setdash ( int pdf document, float white, float black)

The cpdf_setdash() function set the dash pattern white white units and black black units. If both are 0 a solid line is set.

cpdf_setflat

(PHP 3>= 3.0.8, PHP 4 )

cpdf_setflat -- Sets flatness

Description

void cpdf_setflat ( int pdf document, float value)

The cpdf_setflat() function set the flatness to a value between 0 and 100.

cpdf_setgray_fill

(PHP 3>= 3.0.8, PHP 4 )

cpdf_setgray_fill -- Sets filling color to gray value

Description

void cpdf_setgray_fill ( int pdf document, float value)

The cpdf_setgray_fill() function sets the current gray value to fill a path.

See also cpdf_setrgbcolor_fill().

cpdf_setgray_stroke

(PHP 3>= 3.0.8, PHP 4 )

cpdf_setgray_stroke -- Sets drawing color to gray value

Description

void cpdf_setgray_stroke ( int pdf document, float gray value)

The cpdf_setgray_stroke() function sets the current drawing color to the given gray value.

See also cpdf_setrgbcolor_stroke().

cpdf_setgray

(PHP 3>= 3.0.8, PHP 4 )

cpdf_setgray -- Sets drawing and filling color to gray value

Description

void cpdf_setgray ( int pdf document, float gray value)

The cpdf_setgray() function sets the current drawing and filling color to the given gray value.

See also cpdf_setrgbcolor_stroke(), cpdf_setrgbcolor_fill().

cpdf_setlinecap

(PHP 3>= 3.0.8, PHP 4 )

cpdf_setlinecap -- Sets linecap parameter

Description

void cpdf_setlinecap ( int pdf document, int value)

The cpdf_setlinecap() function set the linecap parameter between a value of 0 and 2. 0 = butt end, 1 = round, 2 = projecting square.

cpdf_setlinejoin

(PHP 3>= 3.0.8, PHP 4 )

cpdf_setlinejoin -- Sets linejoin parameter

Description

void cpdf_setlinejoin ( int pdf document, long value)

The cpdf_setlinejoin() function set the linejoin parameter between a value of 0 and 2. 0 = miter, 1 = round, 2 = bevel.

cpdf_setlinewidth

(PHP 3>= 3.0.8, PHP 4 )

cpdf_setlinewidth -- Sets line width

Description

void cpdf_setlinewidth ( int pdf document, float width)

The cpdf_setlinewidth() function set the line width to width.

cpdf_setmiterlimit

(PHP 3>= 3.0.8, PHP 4 )

cpdf_setmiterlimit -- Sets miter limit

Description

void cpdf_setmiterlimit ( int pdf document, float value)

The cpdf_setmiterlimit() function set the miter limit to a value greater or equal than 1.

cpdf_setrgbcolor_fill

(PHP 3>= 3.0.8, PHP 4 )

cpdf_setrgbcolor_fill -- Sets filling color to rgb color value

Description

void cpdf_setrgbcolor_fill ( int pdf document, float red value, float green value, float blue value)

The cpdf_setrgbcolor_fill() function sets the current rgb color value to fill a path.

See also cpdf_setrgbcolor_stroke(), cpdf_setrgbcolor().

cpdf_setrgbcolor_stroke

(PHP 3>= 3.0.8, PHP 4 )

cpdf_setrgbcolor_stroke -- Sets drawing color to rgb color value

Description

void cpdf_setrgbcolor_stroke ( int pdf document, float red value, float green value, float blue value)

The cpdf_setrgbcolor_stroke() function sets the current drawing color to the given rgb color value.

See also cpdf_setrgbcolor_fill(), cpdf_setrgbcolor().

cpdf_setrgbcolor

(PHP 3>= 3.0.8, PHP 4 )

cpdf_setrgbcolor -- Sets drawing and filling color to rgb color value

Description

void cpdf_setrgbcolor ( int pdf document, float red value, float green value, float blue value)

The cpdf_setrgbcolor() function sets the current drawing and filling color to the given rgb color value.

See also cpdf_setrgbcolor_stroke(), cpdf_setrgbcolor_fill().

cpdf_show_xy

(PHP 3>= 3.0.8, PHP 4 )

cpdf_show_xy -- Output text at position

Description

void cpdf_show_xy ( int pdf document, string text, float x-coor, float y-coor [, int mode])

The cpdf_show_xy() function outputs the string text at position with coordinates (x-coor, y-coor).

The optional parameter mode determines the unit length. If it's 0 or omitted the default unit as specified for the page is used. Otherwise the coordinates are measured in postscript points disregarding the current unit.

Nota: The function cpdf_show_xy() is identical to cpdf_text() without the optional parameters.

See also cpdf_text().

cpdf_show

(PHP 3>= 3.0.8, PHP 4 )

cpdf_show -- Output text at current position

Description

void cpdf_show ( int pdf document, string text)

The cpdf_show() function outputs the string in text at the current position.

See also cpdf_text(), cpdf_begin_text(), cpdf_end_text().

cpdf_stringwidth

(PHP 3>= 3.0.8, PHP 4 )

cpdf_stringwidth -- Returns width of text in current font

Description

float cpdf_stringwidth ( int pdf document, string text)

The cpdf_stringwidth() function returns the width of the string in text. It requires a font to be set before.

See also cpdf_set_font().

cpdf_stroke

(PHP 3>= 3.0.8, PHP 4 )

cpdf_stroke -- Draw line along path

Description

void cpdf_stroke ( int pdf document)

The cpdf_stroke() function draws a line along current path.

See also cpdf_closepath(), cpdf_closepath_stroke().

cpdf_text

(PHP 3>= 3.0.8, PHP 4 )

cpdf_text -- Output text with parameters

Description

void cpdf_text ( int pdf document, string text, float x-coor, float y-coor [, int mode [, float orientation [, int alignmode]]])

The cpdf_text() function outputs the string text at position with coordinates (x-coor, y-coor).

The optional parameter mode determines the unit length. If it's 0 or omitted the default unit as specified for the page is used. Otherwise the coordinates are measured in postscript points disregarding the current unit. The optional parameter orientation is the rotation of the text in degree. The optional parameter alignmode determines how the text is aligned.

See the ClibPDF documentation for possible values.

See also cpdf_show_xy().

cpdf_translate

(PHP 3>= 3.0.8, PHP 4 )

cpdf_translate -- Sets origin of coordinate system

Description

void cpdf_translate ( int pdf document, float x-coor, float y-coor [, int mode])

The cpdf_translate() function set the origin of coordinate system to the point (x-coor, y-coor).

The optional parameter mode determines the unit length. If it's 0 or omitted the default unit as specified for the page is used. Otherwise the coordinates are measured in postscript points disregarding the current unit.

XI. Crack functions

Introdução

These functions allow you to use the CrackLib library to test the 'strength' of a password. The 'strength' of a password is tested by that checks length, use of upper and lower case and checked against the specified CrackLib dictionary. CrackLib will also give helpful diagnostic messages that will help 'strengthen' the password.


Requisitos

More information regarding CrackLib along with the library can be found at http://www.users.dircon.co.uk/~crypto/.


Instalação

In order to use these functions, you must compile PHP with Crack support by using the --with-crack[=DIR] option.


Configuração durante execução

O comportamento dessas funções podem ser modificado pelas configurações do php.ini.

Tabela 1. Crack configuration options

Name Default Changeable
crack.default_dictionary NULL PHP_INI_SYSTEM
For further details and definition of the PHP_INI_* constants see ini_set().


Tipos Resource

Esta extensão não possui nenhum tipo resource.


Constantes Predefinidas

Esta extensão não possui nenhuma constante.


Exemplos

This example shows how to open a CrackLib dictionary, test a given password, retrieve any diagnostic messages, and close the dictionary.

Exemplo 1. CrackLib example

<?php
// Open CrackLib Dictionary
$dictionary = crack_opendict('/usr/local/lib/pw_dict')
     or die('Unable to open CrackLib dictionary');

// Perform password check
$check = crack_check($dictionary, 'gx9A2s0x');

// Retrieve messages
$diag = crack_getlastmessage();
echo $diag; // 'strong password'

// Close dictionary
crack_closedict($dictionary);
?>

Nota: If crack_check() returns TRUE, crack_getlastmessage() will return 'strong password'.

Índice
crack_check -- Performs an obscure check with the given password
crack_closedict -- Closes an open CrackLib dictionary
crack_getlastmessage -- Returns the message from the last obscure check
crack_opendict -- Opens a new CrackLib dictionary

crack_check

(PHP 4 >= 4.0.5)

crack_check -- Performs an obscure check with the given password

Description

bool crack_check ( [resource dictionary, string password])

Returns TRUE if password is strong, or FALSE otherwise.

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

crack_check() performs an obscure check with the given password on the specified dictionary . If dictionary is not specified, the last opened dictionary is used.

crack_closedict

(PHP 4 >= 4.0.5)

crack_closedict -- Closes an open CrackLib dictionary

Description

bool crack_closedict ( [resource dictionary])

Retorna TRUE em caso de sucesso ou FALSE em falhas.

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

crack_closedict() closes the specified dictionary identifier. If dictionary is not specified, the current dictionary is closed.

crack_getlastmessage

(PHP 4 >= 4.0.5)

crack_getlastmessage -- Returns the message from the last obscure check

Description

string crack_getlastmessage ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

crack_getlastmessage() returns the message from the last obscure check.

crack_opendict

(PHP 4 >= 4.0.5)

crack_opendict -- Opens a new CrackLib dictionary

Description

resource crack_opendict ( string dictionary)

Returns a dictionary resource identifier on success, or FALSE on failure.

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

crack_opendict() opens the specified CrackLib dictionary for use with crack_check().

Nota: Only one dictionary may be open at a time.

See also: crack_check(), and crack_closedict().

XII. CURL, Client URL Library Functions

Introdução

PHP supports libcurl, a library created by Daniel Stenberg, that allows you to connect and communicate to many different types of servers with many different types of protocols. libcurl currently supports the http, https, ftp, gopher, telnet, dict, file, and ldap protocols. libcurl also supports HTTPS certificates, HTTP POST, HTTP PUT, FTP uploading (this can also be done with PHP's ftp extension), HTTP form based upload, proxies, cookies, and user+password authentication.

These functions have been added in PHP 4.0.2.


Requisitos

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 CURL below version 7.0.2-beta. From PHP version 4.2.3 you will atleast need CURL version 7.9.0 or higher.


Instalação

To use PHP's CURL support you must also compile PHP --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 should be a file named libcurl.a located in the "lib" directory. Beginning with PHP 4.3.0 you can configure PHP to use CURL for url streams --with-curlwrappers.

Note to Win32 Users: In order to enable this module on a Windows environment, you must copy libeay32.dll and ssleay32.dll from the DLL folder of the PHP/Win32 binary package to the SYSTEM32 folder of your windows machine. (Ex: C:\WINNT\SYSTEM32 or C:\WINDOWS\SYSTEM32)


Constantes Predefinidas

As contantes abaixo são definidas por esta extensão e somente estarão disponíveis quando a extensão foi compilada com o PHP ou carregada dinamicamente durante a execução.

CURLOPT_PORT (integer)

CURLOPT_FILE (integer)

CURLOPT_INFILE (integer)

CURLOPT_INFILESIZE (integer)

CURLOPT_URL (integer)

CURLOPT_PROXY (integer)

CURLOPT_VERBOSE (integer)

CURLOPT_HEADER (integer)

CURLOPT_HTTPHEADER (integer)

CURLOPT_NOPROGRESS (integer)

CURLOPT_NOBODY (integer)

CURLOPT_FAILONERROR (integer)

CURLOPT_UPLOAD (integer)

CURLOPT_POST (integer)

CURLOPT_FTPLISTONLY (integer)

CURLOPT_FTPAPPEND (integer)

CURLOPT_NETRC (integer)

CURLOPT_FOLLOWLOCATION (integer)

CURLOPT_FTPASCII (integer)

CURLOPT_PUT (integer)

CURLOPT_MUTE (integer)

CURLOPT_USERPWD (integer)

CURLOPT_PROXYUSERPWD (integer)

CURLOPT_RANGE (integer)

CURLOPT_TIMEOUT (integer)

CURLOPT_POSTFIELDS (integer)

CURLOPT_REFERER (integer)

CURLOPT_USERAGENT (integer)

CURLOPT_FTPPORT (integer)

CURLOPT_LOW_SPEED_LIMIT (integer)

CURLOPT_LOW_SPEED_TIME (integer)

CURLOPT_RESUME_FROM (integer)

CURLOPT_COOKIE (integer)

CURLOPT_SSLCERT (integer)

CURLOPT_SSLCERTPASSWD (integer)

CURLOPT_WRITEHEADER (integer)

CURLOPT_SSL_VERIFYHOST (integer)

CURLOPT_COOKIEFILE (integer)

CURLOPT_SSLVERSION (integer)

CURLOPT_TIMECONDITION (integer)

CURLOPT_TIMEVALUE (integer)

CURLOPT_CUSTOMREQUEST (integer)

CURLOPT_STDERR (integer)

CURLOPT_TRANSFERTEXT (integer)

CURLOPT_RETURNTRANSFER (integer)

CURLOPT_QUOTE (integer)

CURLOPT_POSTQUOTE (integer)

CURLOPT_INTERFACE (integer)

CURLOPT_KRB4LEVEL (integer)

CURLOPT_HTTPPROXYTUNNEL (integer)

CURLOPT_FILETIME (integer)

CURLOPT_WRITEFUNCTION (integer)

CURLOPT_READFUNCTION (integer)

CURLOPT_PASSWDFUNCTION (integer)

CURLOPT_HEADERFUNCTION (integer)

CURLOPT_MAXREDIRS (integer)

CURLOPT_MAXCONNECTS (integer)

CURLOPT_CLOSEPOLICY (integer)

CURLOPT_FRESH_CONNECT (integer)

CURLOPT_FORBID_REUSE (integer)

CURLOPT_RANDOM_FILE (integer)

CURLOPT_EGDSOCKET (integer)

CURLOPT_CONNECTTIMEOUT (integer)

CURLOPT_SSL_VERIFYPEER (integer)

CURLOPT_CAINFO (integer)

CURLOPT_COOKIEJAR (integer)

CURLOPT_SSL_CIPHER_LIST (integer)

CURLOPT_BINARYTRANSFER (integer)

CURLCLOSEPOLICY_LEAST_RECENTLY_USED (integer)

CURLCLOSEPOLICY_LEAST_TRAFFIC (integer)

CURLCLOSEPOLICY_SLOWEST (integer)

CURLCLOSEPOLICY_CALLBACK (integer)

CURLCLOSEPOLICY_OLDEST (integer)

CURLINFO_EFFECTIVE_URL (integer)

CURLINFO_HTTP_CODE (integer)

CURLINFO_HEADER_SIZE (integer)

CURLINFO_REQUEST_SIZE (integer)

CURLINFO_TOTAL_TIME (integer)

CURLINFO_NAMELOOKUP_TIME (integer)

CURLINFO_CONNECT_TIME (integer)

CURLINFO_PRETRANSFER_TIME (integer)

CURLINFO_SIZE_UPLOAD (integer)

CURLINFO_SIZE_DOWNLOAD (integer)

CURLINFO_SPEED_DOWNLOAD (integer)

CURLINFO_SPEED_UPLOAD (integer)

CURLINFO_FILETIME (integer)

CURLINFO_SSL_VERIFYRESULT (integer)

CURLINFO_CONTENT_LENGTH_DOWNLOAD (integer)

CURLINFO_CONTENT_LENGTH_UPLOAD (integer)

CURLE_OK (integer)

CURLE_UNSUPPORTED_PROTOCOL (integer)

CURLE_FAILED_INIT (integer)

CURLE_URL_MALFORMAT (integer)

CURLE_URL_MALFORMAT_USER (integer)

CURLE_COULDNT_RESOLVE_PROXY (integer)

CURLE_COULDNT_RESOLVE_HOST (integer)

CURLE_COULDNT_CONNECT (integer)

CURLE_FTP_WEIRD_SERVER_REPLY (integer)

CURLE_FTP_ACCESS_DENIED (integer)

CURLE_FTP_USER_PASSWORD_INCORRECT (integer)

CURLE_FTP_WEIRD_PASS_REPLY (integer)

CURLE_FTP_WEIRD_USER_REPLY (integer)

CURLE_FTP_WEIRD_PASV_REPLY (integer)

CURLE_FTP_WEIRD_227_FORMAT (integer)

CURLE_FTP_CANT_GET_HOST (integer)

CURLE_FTP_CANT_RECONNECT (integer)

CURLE_FTP_COULDNT_SET_BINARY (integer)

CURLE_PARTIAL_FILE (integer)

CURLE_FTP_COULDNT_RETR_FILE (integer)

CURLE_FTP_WRITE_ERROR (integer)

CURLE_FTP_QUOTE_ERROR (integer)

CURLE_HTTP_NOT_FOUND (integer)

CURLE_WRITE_ERROR (integer)

CURLE_MALFORMAT_USER (integer)

CURLE_FTP_COULDNT_STOR_FILE (integer)

CURLE_READ_ERROR (integer)

CURLE_OUT_OF_MEMORY (integer)

CURLE_OPERATION_TIMEOUTED (integer)

CURLE_FTP_COULDNT_SET_ASCII (integer)

CURLE_FTP_PORT_FAILED (integer)

CURLE_FTP_COULDNT_USE_REST (integer)

CURLE_FTP_COULDNT_GET_SIZE (integer)

CURLE_HTTP_RANGE_ERROR (integer)

CURLE_HTTP_POST_ERROR (integer)

CURLE_SSL_CONNECT_ERROR (integer)

CURLE_FTP_BAD_DOWNLOAD_RESUME (integer)

CURLE_FILE_COULDNT_READ_FILE (integer)

CURLE_LDAP_CANNOT_BIND (integer)

CURLE_LDAP_SEARCH_FAILED (integer)

CURLE_LIBRARY_NOT_FOUND (integer)

CURLE_FUNCTION_NOT_FOUND (integer)

CURLE_ABORTED_BY_CALLBACK (integer)

CURLE_BAD_FUNCTION_ARGUMENT (integer)

CURLE_BAD_CALLING_ORDER (integer)

CURLE_HTTP_PORT_FAILED (integer)

CURLE_BAD_PASSWORD_ENTERED (integer)

CURLE_TOO_MANY_REDIRECTS (integer)

CURLE_UNKNOWN_TELNET_OPTION (integer)

CURLE_TELNET_OPTION_SYNTAX (integer)

CURLE_OBSOLETE (integer)

CURLE_SSL_PEER_CERTIFICATE (integer)


Exemplos

Once you've compiled PHP with CURL support, you can 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 transfer via the curl_setopt(), then you can execute the session with 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 example.com homepage into a file:

Exemplo 1. Using PHP's CURL module to fetch the example.com homepage

<?php

$ch = curl_init ("http://www.example.com/");
$fp = fopen ("example_homepage.txt", "w");

curl_setopt ($ch, CURLOPT_FILE, $fp);
curl_setopt ($ch, CURLOPT_HEADER, 0);

curl_exec ($ch);
curl_close ($ch);
fclose ($fp);
?>

Índice
curl_close -- Close a CURL session
curl_errno -- Return an integer containing the last error number
curl_error --  Return a string containing the last error for the current session
curl_exec -- Perform a CURL session
curl_getinfo --  Get information regarding a specific transfer
curl_init -- Initialize a CURL session
curl_setopt -- Set an option for a CURL transfer
curl_version -- Return the current CURL version

curl_close

(PHP 4 >= 4.0.2)

curl_close -- Close a CURL session

Description

void curl_close ( resource ch)

This function closes a CURL session and frees all resources. The CURL handle, ch, is also deleted.

curl_errno

(PHP 4 >= 4.0.3)

curl_errno -- Return an integer containing the last error number

Description

int curl_errno ( resource ch)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

curl_error

(PHP 4 >= 4.0.3)

curl_error --  Return a string containing the last error for the current session

Description

string curl_error ( resource ch)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

curl_exec

(PHP 4 >= 4.0.2)

curl_exec -- Perform a CURL session

Description

bool curl_exec ( resource ch)

This function 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 session (given by the ch).

Dica: Como toda saída é normalmente enviada direto para o browser, você pode usar as Funções de Controle de Output para capturar o resultado e guardá-lo em uma string (por exemplo).

curl_getinfo

(PHP 4 >= 4.0.4)

curl_getinfo --  Get information regarding a specific transfer

Description

string curl_getinfo ( resource ch [, int opt])

Returns information about the last transfer, opt may be one of the following:

  • "CURLINFO_EFFECTIVE_URL" - Last effective URL

  • "CURLINFO_HTTP_CODE" - Last received HTTP code

  • "CURLINFO_FILETIME" - Remote time of the retrieved document, if -1 is returned the time of the document is unknown

  • "CURLINFO_TOTAL_TIME" - Total transaction time in seconds for last transfer

  • "CURLINFO_NAMELOOKUP_TIME" - Time in seconds until name resolving was complete

  • "CURLINFO_CONNECT_TIME" - Time in seconds it took to establish the connection

  • "CURLINFO_PRETRANSFER_TIME" - Time in seconds from start until just before file transfer begins

  • "CURLINFO_STARTTRANSFER_TIME" - Time in seconds until the first byte is about to be transfered

  • "CURLINFO_REDIRECT_TIME" - Time in seconds of all redirection steps before final transaction was started

  • "CURLINFO_SIZE_UPLOAD" - Total number of bytes uploaded

  • "CURLINFO_SIZE_DOWNLOAD" - Total number of bytes downloaded

  • "CURLINFO_SPEED_DOWNLOAD" - Average download speed

  • "CURLINFO_SPEED_UPLOAD" - Average upload speed

  • "CURLINFO_HEADER_SIZE" - Total size of all headers received

  • "CURLINFO_REQUEST_SIZE" - Total size of issued requests, currently only for HTTP requests

  • "CURLINFO_SSL_VERIFYRESULT" - Result of SSL certification verification requested by setting CURLOPT_SSL_VERIFYPEER

  • "CURLINFO_CONTENT_LENGTH_DOWNLOAD" - content-length of download, read from Content-Length: field

  • "CURLINFO_CONTENT_LENGTH_UPLOAD" - Specified size of upload

  • "CURLINFO_CONTENT_TYPE" - Content-type of downloaded object, NULL indicates server did not send valid Content-Type: header

If called without the optional parameter opt an assoctive array is returned with the following array elements which correspond to opt options:

  • "url"

  • "content_type"

  • "http_encode"

  • "header_size"

  • "request_size"

  • "filetime"

  • "ssl_verify_result"

  • "redirect_count"

  • "total_time"

  • "namelookup_time"

  • "connect_time"

  • "pretransfer_time"

  • "size_upload"

  • "size_download"

  • "speed_download"

  • "speed_upload"

  • "download_content_length"

  • "upload_content_length"

  • "starttransfer_time"

  • "redirect_time"

curl_init

(PHP 4 >= 4.0.2)

curl_init -- Initialize a CURL session

Description

resource curl_init ( [string url])

The curl_init() will initialize a new session and return a CURL handle for use with the curl_setopt(), curl_exec(), and curl_close() functions. If the optional url parameter is supplied then the CURLOPT_URL option will be set to the value of the parameter. You can manually set this using the curl_setopt() function.

Exemplo 1. Initializing a new CURL session and fetching a webpage

<?php
$ch = curl_init();

curl_setopt ($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt ($ch, CURLOPT_HEADER, 0);

curl_exec ($ch);

curl_close ($ch);
?>

See also: curl_close(), curl_setopt()

curl_setopt

(PHP 4 >= 4.0.2)

curl_setopt -- Set an option for a CURL transfer

Description

bool curl_setopt ( resource ch, string option, mixed value)

The curl_setopt() function will set options for a CURL session identified by the ch parameter. The option parameter is the option you want to set, and the value is the value of the option given by the option.

The value should be a long for the following options (specified in the option parameter):

  • CURLOPT_INFILESIZE: When you are uploading a file to a remote site, this option should be used to tell PHP what the expected size of the infile will be.

  • CURLOPT_VERBOSE: Set this option to a non-zero value if you want CURL to report everything that is happening.

  • CURLOPT_HEADER: Set this option to a non-zero value if you want the header to be included in the output.

  • CURLOPT_NOPROGRESS: Set this option to a non-zero value if you don't want PHP to display a progress meter for CURL transfers.

    Nota: PHP automatically sets this option to a non-zero parameter, this should only be changed for debugging purposes.

  • CURLOPT_NOBODY: Set this option to a non-zero value if you don't want the body included with the output.

  • CURLOPT_FAILONERROR: Set this option to a non-zero value if you want PHP to fail silently if the HTTP code returned is greater than 300. The default behavior is to return the page normally, ignoring the code.

  • CURLOPT_UPLOAD: Set this option to a non-zero value if you want PHP to prepare for an upload.

  • CURLOPT_POST: Set this option to a non-zero value if you want PHP to do a regular HTTP POST. This POST is a normal application/x-www-form-urlencoded kind, most commonly used by HTML forms.

  • CURLOPT_FTPLISTONLY: Set this option to a non-zero value and PHP will just list the names of an FTP directory.

  • CURLOPT_FTPAPPEND: Set this option to a non-zero value and PHP will append to the remote file instead of overwriting it.

  • CURLOPT_NETRC: Set this option to a non-zero value and PHP will scan your ~./netrc file to find your username and password for the remote site that you're establishing a connection with.

  • CURLOPT_FOLLOWLOCATION: Set this option to a non-zero value to follow any "Location: " header that the server sends as a part of the HTTP header (note this is recursive, PHP will follow as many "Location: " headers that it is sent.)

  • CURLOPT_PUT: Set this option to a non-zero value to HTTP PUT a file. The file to PUT must be set with the CURLOPT_INFILE and CURLOPT_INFILESIZE.

  • CURLOPT_MUTE: Set this option to a non-zero value and PHP will be completely silent with regards to the CURL functions.

  • CURLOPT_TIMEOUT: Pass a long as a parameter that contains the maximum time, in seconds, that you'll allow the CURL functions to take.

  • CURLOPT_LOW_SPEED_LIMIT: Pass a long as a parameter that contains the transfer speed in bytes per second that the transfer should be below during CURLOPT_LOW_SPEED_TIME seconds for PHP to consider it too slow and abort.

  • CURLOPT_LOW_SPEED_TIME: Pass a long as a parameter that contains the time in seconds that the transfer should be below the CURLOPT_LOW_SPEED_LIMIT for PHP to consider it too slow and abort.

  • CURLOPT_RESUME_FROM: Pass a long as a parameter that contains the offset, in bytes, that you want the transfer to start from.

  • CURLOPT_SSLVERSION: Pass a long as a parameter that contains the SSL version (2 or 3) to use. By default PHP will try and determine this by itself, although, in some cases you must set this manually.

  • CURLOPT_SSL_VERIFYHOST: Pass a long if CURL should verify the Common name of the peer certificate in the SSL handshake. A value of 1 denotes that we should check for the existence of the common name, a value of 2 denotes that we should make sure it matches the provided hostname.

  • CURLOPT_TIMECONDITION: Pass a long as a parameter that defines how the CURLOPT_TIMEVALUE is treated. You can set this parameter to TIMECOND_IFMODSINCE or TIMECOND_ISUNMODSINCE. This is a HTTP-only feature.

  • CURLOPT_TIMEVALUE: Pass a long as a parameter that is the time in seconds since January 1st, 1970. The time will be used as specified by the CURLOPT_TIMEVALUE option, or by default the TIMECOND_IFMODSINCE will be used.

  • CURLOPT_RETURNTRANSFER: Pass a non-zero value if you want CURL to directly return the transfer instead of printing it out directly.

The value parameter should be a string for the following values of the option parameter:

  • CURLOPT_URL: This is the URL that you want PHP to fetch. You can also set this option when initializing a session with the curl_init() function.

  • CURLOPT_USERPWD: Pass a string formatted in the [username]:[password] manner, for PHP to use for the connection.

  • CURLOPT_PROXYUSERPWD: Pass a string formatted in the [username]:[password] format for connection to the HTTP proxy.

  • CURLOPT_RANGE: Pass the specified range you want. It should be in the "X-Y" format, where X or Y may be left out. The HTTP transfers also support several intervals, separated with commas as in X-Y,N-M.

  • CURLOPT_POSTFIELDS: Pass a string containing the full data to post in an HTTP "POST" operation.

  • CURLOPT_REFERER: Pass a string containing the "referer" header to be used in an HTTP request.

  • CURLOPT_USERAGENT: Pass a string containing the "user-agent" header to be used in an HTTP request.

  • CURLOPT_FTPPORT: Pass a string containing the value which will be used to get the IP address to use for the ftp "POST" instruction. The POST instruction tells the remote server to connect to our specified IP address. The string may be a plain IP address, a hostname, a network interface name (under UNIX), or just a plain '-' to use the systems default IP address.

  • CURLOPT_COOKIE: Pass a string containing the content of the cookie to be set in the HTTP header.

  • CURLOPT_SSLCERT: Pass a string containing the filename of PEM formatted certificate.

  • CURLOPT_SSLCERTPASSWD: Pass a string containing the password required to use the CURLOPT_SSLCERT certificate.

  • CURLOPT_COOKIEFILE: Pass a string containing the name of the file containing the cookie data. The cookie file can be in Netscape format, or just plain HTTP-style headers dumped into a file.

  • CURLOPT_CUSTOMREQUEST: Pass a string to be used instead of GET or HEAD when doing an HTTP request. This is useful for doing DELETE or other, more obscure, HTTP requests. Valid values are things like GET, POST, and so on; i.e. do not enter a whole HTTP request line here. For instance, entering 'GET /index.html HTTP/1.0\r\n\r\n' would be incorrect.

    Nota: Don't do this without making sure your server supports the command first.

  • CURLOPT_PROXY: Give the name of the HTTP proxy to tunnel requests through.

  • CURLOPT_INTERFACE: Pass the name of the outgoing network interface to use. This can be an interface name, an IP address or a host name.

  • CURLOPT_KRB4LEVEL: Pass the KRB4 (Kerberos 4) security level. Anyone of the following strings (in order from least powerful, to most powerful): 'clear', 'safe', 'confidential', 'private'. If the string does not match one of these, then 'private' is used. If you set this to NULL, this disables KRB4 security. KRB4 security only works with FTP transactions currently.

  • CURLOPT_HTTPHEADER: Pass an array of HTTP header fields to set.

  • CURLOPT_QUOTE: Pass an array of FTP commands to perform on the server prior to the FTP request.

  • CURLOPT_POSTQUOTE: Pass an array of FTP commands to execute on the server, after the FTP request has been performed.

The following options expect a file descriptor that is obtained by using the fopen() function:

  • CURLOPT_FILE: The file where the output of your transfer should be placed, the default is STDOUT.

  • CURLOPT_INFILE: The file where the input of your transfer comes from.

  • CURLOPT_WRITEHEADER: The file to write the header part of the output into.

  • CURLOPT_STDERR: The file to write errors to instead of stderr.

curl_version

(PHP 4 >= 4.0.2)

curl_version -- Return the current CURL version

Description

string curl_version ( void)

The curl_version() function returns a string containing the current CURL version.

XIII. Cybercash payment functions

Instalação

These functions are only available if the interpreter has been compiled with the --with-cybercash=[DIR].

This extension has been removed from PHP as of PHP 4.3.0, if you have questions as to why then you will find the following CyberCash Faq helpful. In short, CyberCash was bought out by VeriSign and although the CyberCash service continues to exist, VeriSign encourages users to switch. See the above faq for details.

Índice
cybercash_base64_decode -- base64 decode data for Cybercash
cybercash_base64_encode -- base64 encode data for Cybercash
cybercash_decr -- Cybercash decrypt
cybercash_encr -- Cybercash encrypt

cybercash_base64_decode

(PHP 4 <= 4.2.3)

cybercash_base64_decode -- base64 decode data for Cybercash

Description

string cybercash_base64_decode ( string inbuff)

cybercash_base64_encode

(PHP 4 <= 4.2.3)

cybercash_base64_encode -- base64 encode data for Cybercash

Description

string cybercash_base64_encode ( string inbuff)

cybercash_decr

(PHP 4 <= 4.2.3)

cybercash_decr -- Cybercash decrypt

Description

array cybercash_decr ( string wmk, string sk, string inbuff)

The function returns an associative array with the elements "errcode" and, if "errcode" is FALSE, "outbuff" (string), "outLth" (long) and "macbuff" (string).

cybercash_encr

(PHP 4 <= 4.2.3)

cybercash_encr -- Cybercash encrypt

Description

array cybercash_encr ( string wmk, string sk, string inbuff)

The function returns an associative array with the elements "errcode" and, if "errcode" is FALSE, "outbuff" (string), "outLth" (long) and "macbuff" (string).

XIV. Crédit Mutuel CyberMUT functions

Introdução

This extension allows you to process credit cards transactions using Crédit Mutuel CyberMUT system (http://www.creditmutuel.fr/centre_commercial/vendez_sur_internet.html).

CyberMUT is a popular Web Payment Service in France, provided by the Crédit Mutuel bank. If you are foreign in France, these functions will not be useful for you.

The use of these functions is almost identical to the original SDK functions, except for the parameters of return for cybermut_creerformulairecm() and cybermut_creerreponsecm(), which are returned directly by functions PHP, whereas they had passed in reference in the original functions.

These functions have been added in PHP 4.0.6.

Nota: These functions only provide a link to CyberMUT SDK. Be sure to read the CyberMUT Developers Guide for full details of the required parameters.


Instalação

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 will require the appropriate SDK for your platform, which may be sent to you after your CyberMUT's subscription (contact them via Web, or go to the nearest Crédit Mutuel).

Nota: This extension is not available on Windows platforms.

Índice
cybermut_creerformulairecm -- Generate HTML form of request for payment
cybermut_creerreponsecm --  Generate the acknowledgement of delivery of the confirmation of payment
cybermut_testmac --  Make sure that there no was data diddling contained in the received message of confirmation

cybermut_creerformulairecm

(4.0.5 - 4.2.3 only)

cybermut_creerformulairecm -- Generate HTML form of request for payment

Description

string cybermut_creerformulairecm ( string url_CM, string version, string TPE, string montant, string ref_commande, string texte_libre, string url_retour, string url_retour_ok, string url_retour_err, string langue, string code_societe, string texte_bouton)

cybermut_creerformulairecm() is used to generate the HTML form of request for payment.

Exemplo 1. First step of payment (equiv cgi1.c)

<?php
// Directory where the keys are located
putenv("CMKEYDIR=/var/creditmut/cles");
 
// Version number
$VERSION="1.2";

  $retour =  cybermut_creerformulairecm(
  "https://www.creditmutuel.fr/test/telepaiement/paiement.cgi",
  $VERSION,
  "1234567890",
  "300FRF",
  $REFERENCE,
  $TEXTE_LIBRE,
  $URL_RETOUR,
  $URL_RETOUR_OK,
  $URL_RETOUR_ERR,
  "francais",
  "company",
  "Paiement par carte bancaire");
 
  echo $retour;                                                               
?>

See also cybermut_testmac() and cybermut_creerreponsecm().

cybermut_creerreponsecm

(4.0.5 - 4.2.3 only)

cybermut_creerreponsecm --  Generate the acknowledgement of delivery of the confirmation of payment

Description

string cybermut_creerreponsecm ( string phrase)

cybermut_creerreponsecm() returns a string containing delivery acknowledgement message.

The parameter is "OK" if the message of confirmation of the payment was correctly identified by cybermut_testmac(). Any other chain is regarded as an error message.

See also cybermut_creerformulairecm() and cybermut_testmac().

cybermut_testmac

(4.0.5 - 4.2.3 only)

cybermut_testmac --  Make sure that there no was data diddling contained in the received message of confirmation

Description

bool cybermut_testmac ( string code_MAC, string version, string TPE, string cdate, string montant, string ref_commande, string texte_libre, string code-retour)

cybermut_testmac() is used to make sure that there was not data diddling contained in the received message of confirmation. Pay attention to parameters code-retour and texte-libre, which cannot be evaluated as is, because of the dash. You must retrieve them by using:
<?php
  $code_retour = $_GET["code-retour"];
  $texte_libre = $_GET["texte-libre"];
?>

Exemplo 1. Last step of payment (equiv cgi2.c)

<?php
// Make sure that Enable Track Vars is ON.
// Directory where are located the keys
putenv("CMKEYDIR=/var/creditmut/cles");
 
// Version number
$VERSION="1.2";

$texte_libre = $_GET["texte-libre"];
$code_retour = $_GET["code-retour"];                                     

$mac_ok = cybermut_testmac($MAC,$VERSION,$TPE,$date,$montant,$reference,$texte_libre,$code_retour);

if ($mac_ok) {

  //
  // insert data processing here
  //
  //

  $result=cybermut_creerreponsecm("OK");
} else {
  $result=cybermut_creerreponsecm("Document Falsifie");
}
 
?>

See also cybermut_creerformulairecm() and cybermut_creerreponsecm().

XV. Cyrus IMAP administration functions

Introdução

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

Nota: This extension is not available on Windows platforms.


Instalação

To enable Cyrus IMAP support and to use these functions you have to compile PHP with the --with-cyrus option.


Constantes Predefinidas

As contantes abaixo são definidas por esta extensão e somente estarão disponíveis quando a extensão foi compilada com o PHP ou carregada dinamicamente durante a execução.

CYRUS_CONN_NONSYNCLITERAL (integer)

CYRUS_CONN_INITIALRESPONSE (integer)

CYRUS_CALLBACK_NUMBERED (integer)

CYRUS_CALLBACK_NOLITERAL (integer)

Índice
cyrus_authenticate -- Authenticate against a Cyrus IMAP server
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 -- Send a query to a Cyrus IMAP server
cyrus_unbind -- Unbind ...

cyrus_authenticate

(PHP 4 >= 4.1.0)

cyrus_authenticate -- Authenticate against a Cyrus IMAP server

Description

bool cyrus_authenticate ( resource connection [, string mechlist [, string service [, string user [, int minssf [, int maxssf]]]]])

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

cyrus_bind

(PHP 4 >= 4.1.0)

cyrus_bind -- Bind callbacks to a Cyrus IMAP connection

Description

bool cyrus_bind ( resource connection, array callbacks)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

cyrus_close

(PHP 4 >= 4.1.0)

cyrus_close -- Close connection to a Cyrus IMAP server

Description

bool cyrus_close ( resource connection)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

cyrus_connect

(PHP 4 >= 4.1.0)

cyrus_connect -- Connect to a Cyrus IMAP server

Description

resource cyrus_connect ( [string host [, string port [, int flags]]])

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

cyrus_query

(PHP 4 >= 4.1.0)

cyrus_query -- Send a query to a Cyrus IMAP server

Description

bool cyrus_query ( resource connection, string query)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

cyrus_unbind

(PHP 4 >= 4.1.0)

cyrus_unbind -- Unbind ...

Description

bool cyrus_unbind ( resource connection, string trigger_name)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

XVI. Character type functions

Introdução

The functions provided by this extension check whether a 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 behave exactly like their C counterparts from ctype.h.

When called with a string argument they will check every character in the string and will only return TRUE if every character in the string matches the requested criteria. When called with an empty string the result will always be TRUE.

Passing anything else but a string or integer will return FALSE immediately.


Requisitos

None besides functions from the standard C library which are always available.


Instalação

Beginning with PHP 4.2.0 these functions are enabled by default. For older versions you have to configure and compile PHP with --enable-ctype. You can disable ctype support with --disable-ctype.

The windows version of PHP has built in support for this extension. You do not need to load any additional extension in order to use these functions.

Nota: Builtin support for ctype is available with PHP 4.3.0.


Configuração durante execução

Esta extenção não define nenhum parâmetro de configuração no php.ini.


Tipos Resource

Esta extensão não possui nenhum tipo resource.


Constantes Predefinidas

Esta extensão não possui nenhuma constante.

Índice
ctype_alnum -- Check for alphanumeric character(s)
ctype_alpha -- Check for alphabetic character(s)
ctype_cntrl -- Check for control character(s)
ctype_digit -- Check for numeric character(s)
ctype_graph -- Check for any printable character(s) except space
ctype_lower -- Check for lowercase character(s)
ctype_print -- Check for printable character(s)
ctype_punct --  Check for any printable character which is not whitespace or an alphanumeric character
ctype_space -- Check for whitespace character(s)
ctype_upper -- Check for uppercase character(s)
ctype_xdigit --  Check for character(s) representing a hexadecimal digit

ctype_alnum

(PHP 4 >= 4.0.4)

ctype_alnum -- Check for alphanumeric character(s)

Description

bool ctype_alnum ( string text)

Returns TRUE if every character in text is either a letter or a digit, FALSE otherwise. In the standard C locale letters are just [A-Za-z]. The function is equivalent to (ctype_alpha($text) || ctype_digit($text)).

See also ctype_alpha(), ctype_digit(), and setlocale().

ctype_alpha

(PHP 4 >= 4.0.4)

ctype_alpha -- Check for alphabetic character(s)

Description

bool ctype_alpha ( string text)

Returns TRUE if every character in text is a letter from the current locale, FALSE otherwise. In the standard C locale letters are just [A-Za-z] and ctype_alpha() is equivalent to (ctype_upper($text) || ctype_lower($text)), but other languages have letters that are considered neither upper nor lower case.

See also ctype_upper(), ctype_lower(), and setlocale().

ctype_cntrl

(PHP 4 >= 4.0.4)

ctype_cntrl -- Check for control character(s)

Description

bool ctype_cntrl ( string text)

Returns TRUE if every character in text has a special control function, FALSE otherwise. Control characters are e.g. line feed, tab, esc.

ctype_digit

(PHP 4 >= 4.0.4)

ctype_digit -- Check for numeric character(s)

Description

bool ctype_digit ( string text)

Returns TRUE if every character in text is a decimal digit, FALSE otherwise.

See also ctype_alnum() and ctype_xdigit().

ctype_graph

(PHP 4 >= 4.0.4)

ctype_graph -- Check for any printable character(s) except space

Description

bool ctype_graph ( string text)

Returns TRUE if every character in text is printable and actually creates visible output (no white space), FALSE otherwise.

See also ctype_alnum(), ctype_print(), and ctype_punct().

ctype_lower

(PHP 4 >= 4.0.4)

ctype_lower -- Check for lowercase character(s)

Description

bool ctype_lower ( string text)

Returns TRUE if every character in text is a lowercase letter in the current locale.

See also ctype_alpha() and ctype_upper().

ctype_print

(PHP 4 >= 4.0.4)

ctype_print -- Check for printable character(s)

Description

bool ctype_print ( string text)

Returns TRUE if every character in text will actually create output (including blanks). Returns FALSE if text contains control characters or characters that do not have any output or control function at all.

See also ctype_cntrl(), ctype_graph(), and ctype_punct().

ctype_punct

(PHP 4 >= 4.0.4)

ctype_punct --  Check for any printable character which is not whitespace or an alphanumeric character

Description

bool ctype_punct ( string text)

Returns TRUE if every character in text is printable, but neither letter, digit or blank, FALSE otherwise.

See also ctype_cntrl(), ctype_graph(), and ctype_punct().

ctype_space

(PHP 4 >= 4.0.4)

ctype_space -- Check for whitespace character(s)

Description

bool ctype_space ( string text)

Returns TRUE if every character in text creates some sort of white space, FALSE otherwise. Besides the blank character this also includes tab, vertical tab, line feed, carriage return and form feed characters.

ctype_upper

(PHP 4 >= 4.0.4)

ctype_upper -- Check for uppercase character(s)

Description

bool ctype_upper ( string text)

Returns TRUE if every character in text is a uppercase letter in the current locale.

See also ctype_alpha() and ctype_lower().

ctype_xdigit

(PHP 4 >= 4.0.4)

ctype_xdigit --  Check for character(s) representing a hexadecimal digit

Description

bool ctype_xdigit ( string text)

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.

See also ctype_digit().

XVII. Database (dbm-style) abstraction layer functions

Introdução

These functions build the foundation for accessing Berkeley DB style databases.

This is a general abstraction layer for several file-based databases. As such, functionality is limited to a common subset of features supported by modern databases such as Sleepycat Software's DB2. (This is not to be confused with IBM's DB2 software, which is supported through the ODBC functions.)


Requisitos

The behaviour of various aspects depends on the implementation of the underlying database. Functions such as dba_optimize() and dba_sync() will do what they promise for one database and will do nothing for others. You have to download and install supported dba-Handlers.

Tabela 1. List of DBA handlers

Handler Notes
dbm Dbm is the oldest (original) type of Berkeley DB style databases. You should avoid it, if possible. We do not support the compatibility functions built into DB2 and gdbm, because they are only compatible on the source code level, but cannot handle the original dbm format.
ndbm Ndbm is a newer type and more flexible than dbm. It still has most of the arbitrary limits of dbm (therefore it is deprecated).
gdbm Gdbm is the GNU database manager.
db2 DB2 is Sleepycat Software's DB2. It is described as "a programmatic toolkit that provides high-performance built-in database support for both standalone and client/server applications.
db3 DB3 is Sleepycat Software's DB3.
db4 DB4 is Sleepycat Software's DB4. This is available since PHP 5.0.0.
cdb Cdb is "a fast, reliable, lightweight package for creating and reading constant databases." It is from the author of qmail and can be found here. Since it is constant, we support only reading operations. And since PHP 4.3.0 we support writing (not updating) through the internal cdb library.
cdb_make Since PHP 4.3.0 we support creation (not updating) of cdb files when the bundeled cdb library is used.
flatfile This is available since PHP 4.3.0 for compatibility with the deprecated dbm extension only and should be avoided. However you may use this where files were created in this format. That happens when configure could not find any external library.

When invoking the dba_open() or dba_popen() functions, one of the handler names must be supplied as an argument. The actually available list of handlers is displayed by invoking phpinfo() or dba_handlers().


Instalação

By using the --enable-dba=shared configuration option you can build a dynamic loadable modul to enable PHP for basic support of dbm-style databases. You also have to add support for at least one of the following handlers by specifying the --with-XXXX configure switch to your PHP configure line.

Tabela 2. Supported DBA handlers

Handler Configure Switch
dbm To enable support for dbm add --with-dbm[=DIR].
ndbm To enable support for ndbm add --with-ndbm[=DIR].
gdbm To enable support for gdbm add --with-gdbm[=DIR].
db2 To enable support for db2 add --with-db2[=DIR].

Nota: db2 conflicts with db3 and db4.

db3 To enable support for db3 add --with-db3[=DIR].

Nota: db3 conflicts with db2 and db4.

db4 To enable support for db4 add --with-db4[=DIR].

Nota: db4 conflicts with db2 and db3.

Nota: This was added in PHP 5.0.0. In earlier version you need to use --with-db3=DIR with DIR being the path to db4 librarie. It is not possible to use db versions starting from 4.1 with PHP prior to version 4.3.0.

cdb To enable support for cdb add --with-cdb[=DIR].

Nota: Since PHP 4.3.0 you can omit DIR to use the bundeled cdb library that adds the cdb_make handler which allows creation of cdb files and allows to access cdb files on the network using php's streams.

flatfile To enable support for flatfile add --with-flatfile.

Nota: This was added in PHP 4.3.0 to add compatibility with deprecated dbm extension. Uee this handler only when you cannot install one of the libraries required by the other handlers and when you cannot use bundeled cdb handler.

Nota: Up to PHP 4.3.0 you are able to add both db2 and db3 handler but only one of them can be used internally. That means that you cannot have both file formats. Starting with PHP 5.0.0 there is a configuration check avoid such missconfigurations.


Configuração durante execução

Esta extenção não define nenhum parâmetro de configuração no php.ini.


Tipos Resource

The functions dba_open() and dba_popen() return a handle to the specified database file to access which is used by all other dba-function calls.


Constantes Predefinidas

Esta extensão não possui nenhuma constante.


Exemplos

Exemplo 1. DBA example

<?php

$id = dba_open ("/tmp/test.db", "n", "db2");

if (!$id) {
    echo "dba_open failed\n";
    exit;
}

dba_replace ("key", "This is an example!", $id);

if (dba_exists ("key", $id)) {
    echo dba_fetch ("key", $id);
    dba_delete ("key", $id);
}

dba_close ($id);
?>

DBA is binary safe and does not have any arbitrary limits. However, it inherits all limits set by the underlying database implementation.

All file-based databases must provide a way of setting the file mode of a new created database, if that is possible at all. The file mode is commonly passed as the fourth argument to dba_open() or dba_popen().

You can access all entries of a database in a linear way by using the dba_firstkey() and dba_nextkey() functions. You may not change the database while traversing it.

Exemplo 2. Traversing a database

<?php

// ...open database...

$key = dba_firstkey ($id);

while ($key != false) {
    if (...) {          // remember the key to perform some action later
        $handle_later[] = $key;
    }
    $key = dba_nextkey ($id);
}

for ($i = 0; $i < count($handle_later); $i++)
    dba_delete ($handle_later[$i], $id);

?>

Índice
dba_close -- Close database
dba_delete -- Delete entry specified by key
dba_exists -- Check whether key exists
dba_fetch -- Fetch data specified by key
dba_firstkey -- Fetch first key
dba_handlers -- List handlers available
dba_insert -- Insert entry
dba_list -- List all open database files
dba_nextkey -- Fetch next key
dba_open -- Open database
dba_optimize -- Optimize database
dba_popen -- Open database persistently
dba_replace -- Replace or insert entry
dba_sync -- Synchronize database

dba_close

(PHP 3>= 3.0.8, PHP 4 )

dba_close -- Close database

Description

void dba_close ( resource handle)

dba_close() closes the established database and frees all resources specified by handle.

handle is a database handle returned by dba_open().

dba_close() does not return any value.

See also: dba_open() and dba_popen()

dba_delete

(PHP 3>= 3.0.8, PHP 4 )

dba_delete -- Delete entry specified by key

Description

bool dba_delete ( string key, resource handle)

dba_delete() deletes the entry specified by key from the database specified with handle.

key is the key of the entry which is deleted.

handle is a database handle returned by dba_open().

dba_delete() returns TRUE or FALSE, if the entry is deleted or not deleted, respectively.

See also: dba_exists(), dba_fetch(), dba_insert(), and dba_replace().

dba_exists

(PHP 3>= 3.0.8, PHP 4 )

dba_exists -- Check whether key exists

Description

bool dba_exists ( string key, resource handle)

dba_exists() checks whether the specified key exists in the database specified by handle.

Key is the key the check is performed for.

Handle is a database handle returned by dba_open().

dba_exists() returns TRUE or FALSE, if the key is found or not found, respectively.

See also: dba_fetch(), dba_delete(), dba_insert(), and dba_replace().

dba_fetch

(PHP 3>= 3.0.8, PHP 4 )

dba_fetch -- Fetch data specified by key

Description

string dba_fetch ( string key [, int skip, resource handle])

dba_fetch() fetches the data specified by key from the database specified with handle.

Key is the key the data is specified by.

Skip is the number of key-value pairs to ignore when using cdb databases. This value is ignored for all other databases which do not support multiple keys with the same name.

Handle is a database handle returned by dba_open().

dba_fetch() returns the associated string or FALSE, if the key/data pair is found or not found, respectively.

See also: dba_exists(), dba_delete(), dba_insert(), and dba_replace().

Nota: The skip parameter is available since PHP 4.3 to support cdb's capability of multiple keys having the same name.

dba_firstkey

(PHP 3>= 3.0.8, PHP 4 )

dba_firstkey -- Fetch first key

Description

string dba_firstkey ( resource handle)

dba_firstkey() returns the first key of the database specified by handle and resets the internal key pointer. This permits a linear search through the whole database.

Handle is a database handle returned by dba_open().

dba_firstkey() returns the key or FALSE depending on whether it succeeds or fails, respectively.

See also: dba_nextkey() and example 2 in the DBA examples

dba_handlers

(PHP 4 >= 4.3.0)

dba_handlers -- List handlers available

Description

array dba_handlers ( void)

dba_handlers() returns an array with all handlers suppoerted by this extension.

When the internal cdb library is used you will see 'cdb' and 'cdb_make'.

dba_insert

(PHP 3>= 3.0.8, PHP 4 )

dba_insert -- Insert entry

Description

bool dba_insert ( string key, string value, resource handle)

dba_insert() inserts the entry described with key and value into the database specified by handle. It fails, if an entry with the same key already exists.

key is the key of the entry to be inserted.

value is the value to be inserted.

handle is a database handle returned by dba_open().

dba_insert() returns TRUE or FALSE, depending on whether it succeeds of fails, respectively.

See also: dba_exists() dba_delete() dba_fetch() dba_replace()

dba_list

(PHP 4 >= 4.3.0)

dba_list -- List all open database files

Description

array dba_list ( void)

dba_list() returns an associative array with all open database files. This array is in the form: resourceid=>filename.

dba_nextkey

(PHP 3>= 3.0.8, PHP 4 )

dba_nextkey -- Fetch next key

Description

string dba_nextkey ( resource handle)

dba_nextkey() returns the next key of the database specified by handle and advances the internal key pointer.

handle is a database handle returned by dba_open().

dba_nextkey() returns the key or FALSE depending on whether it succeeds or fails, respectively.

See also: dba_firstkey() and example 2 in the DBA examples

dba_open

(PHP 3>= 3.0.8, PHP 4 )

dba_open -- Open database

Description

resource dba_open ( string path, string mode, string handler [, ...])

dba_open() establishes a database instance for path with mode using handler.

path is commonly a regular path in your filesystem.

mode is "r" for read access, "w" for read/write access to an already existing database, "c" for read/write access and database creation if it doesn't currently exist, and "n" for create, truncate and read/write access. Additional you can set the databse lock method with the next char. Use "l" to lock the database with an .lck file or "d" to lock the databasefile itself. It is important that all of your applications do this consistently. If you want to test the access and do not want to wait for the lock you can add "t" as third character. When you are absolutly sure that you do not require database locking you can do so by using "-" instead of "l" or "d". When none of "d", "l" or "-" is used dba will lock on the database file as it would with "d".

handler is the name of the handler which shall be used for accessing path. It is passed all optional parameters given to dba_open() and can act on behalf of them.

dba_open() returns a positive handle or FALSE, in the case the database was opened successfull or fails, respectively.

Nota: There can only be one writer for one database file. When you use dba on a webserver and more than one request requires write operations they can only be done one after another. Also read during write is not allowed. The dba extension uses locks to prevent this. See the follwoing table:

Tabela 1. DBA locking

already open mode = "rl" mode = "rlt" mode = "wl" mode = "wlt" mode = "rd" mode = "rdt" mode = "wd" mode = "wdt"
not open ok ok ok ok ok ok ok ok
mode = "rl" ok ok wait false illegal illegal illegal illegal
mode = "wl" wait false wait false illegal illegal illegal illegal
mode = "rd" illegal illegal illegal illegal ok ok wait false
mode = "wd" illegal illegal illegal illegal wait false wait false

ok: the second call will be successfull.
wait: the second call waits until dba_close() is called for the first.
false: the second call returns false.
illegal: you must not mix "l" and "d" modifiers for mode parameter.

Nota: Since PHP 4.3.0 it is possible to open database files over network connection. However in cases a socket connection will be used (as with http or ftp) the connection will be locked instead of the resource itself. This is important to know since in such cases locking is simply ignored on the resource and other solutions have to be found.

Nota: Locking and the mode modifiers "l", "d", "-" and "t" were added in PHP 4.3.0. In PHP versions before PHP 4.3.0 you must use semaphores to guard against simultanious database access for any database handler with the exception of GDBM. See System V semaphore support.

See also: dba_popen() dba_close()

dba_optimize

(PHP 3>= 3.0.8, PHP 4 )

dba_optimize -- Optimize database

Description

bool dba_optimize ( resource handle)

dba_optimize() optimizes the underlying database specified by handle.

handle is a database handle returned by dba_open().

dba_optimize() returns TRUE or FALSE, if the optimization succeeds or fails, respectively.

See also: dba_sync()

dba_popen

(PHP 3>= 3.0.8, PHP 4 )

dba_popen -- Open database persistently

Description

resource dba_popen ( string path, string mode, string handler [, ...])

dba_popen() establishes a persistent database instance for path with mode using handler.

path is commonly a regular path in your filesystem.

mode is "r" for read access, "w" for read/write access to an already existing database, "c" for read/write access and database creation if it doesn't currently exist, and "n" for create, truncate and read/write access.

handler is the name of the handler which shall be used for accessing path. It is passed all optional parameters given to dba_popen() and can act on behalf of them.

dba_popen() returns a positive handle or FALSE, in the case the open is successful or fails, respectively.

See also: dba_open() dba_close()

dba_replace

(PHP 3>= 3.0.8, PHP 4 )

dba_replace -- Replace or insert entry

Description

bool dba_replace ( string key, string value, resource handle)

dba_replace() replaces or inserts the entry described with key and value into the database specified by handle.

key is the key of the entry to be inserted.

value is the value to be inserted.

handle is a database handle returned by dba_open().

dba_replace() returns TRUE or FALSE, depending on whether it succeeds of fails, respectively.

See also: dba_exists(), dba_delete(), dba_fetch(), and dba_insert().

dba_sync

(PHP 3>= 3.0.8, PHP 4 )

dba_sync -- Synchronize database

Description

bool dba_sync ( resource handle)

dba_sync() synchronizes the database specified by handle. This will probably trigger a physical write to disk, if supported.

handle is a database handle returned by dba_open().

dba_sync() returns TRUE or FALSE, if the synchronization succeeds or fails, respectively.

See also: dba_optimize()

XVIII. Funções data e hora

Introdução

Você pode usar estas funções para tratar com a data e a hora. Estas funções te permitem conseguir a data e a hora do servidor onde o PHP está rodando. Você pode usar estas funções para formatar a saída de data e hora de muitas maneiras diferentes.

Nota: Por favor mantenha em mente que estas funções dependem das configurações locais do servidor. Considerar especialmente horário-de-verão e anos bissextos.


Requisitos

Nenhuma biblioteca externa é necessária para compilar esta extensão.


Instalação

Não há nenhuma instalação nescessária para utilizar estas funções, elas fazem parte do núcleo do PHP.


Configuração durante execução

Esta extenção não define nenhum parâmetro de configuração no php.ini.


Tipos Resource

Esta extensão não possui nenhum tipo resource.


Constantes Predefinidas

Esta extensão não possui nenhuma constante.

Índice
checkdate -- Validar uma data Gregoriana
date -- Formata a data e a hora local
getdate -- Consegue informações data/hora
gettimeofday -- Obtém a hora local
gmdate -- Formata uma data/hora GMT/CUT
gmmktime -- Consegue um timestamp UNIX para uma data GMT
gmstrftime --  Formata uma hora/data GMT/CUT de acordo com as configurações locais
localtime -- Obtém a hora local
microtime --  Retorna um timestamp UNIX com microsegundos
mktime -- Obtém um modelo UNIX para uma data
strftime --  Formata uma hora/data de acordo com as configurações locais
strtotime --  Analisa qualquer descrição em texto em inglês de data hora em timestamp UNIX
time -- Retorna o timestamp UNIX

checkdate

(PHP 3, PHP 4 )

checkdate -- Validar uma data Gregoriana

Descrição

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

Retorna TRUE se a data dada é válida; caso contrário retorna FALSE. Checa a validade da data formada pelos argumentos. Uma data é considerada válida se:

  • o year está entre 1 e 32767

  • o month está entre 1 e 12

  • Day deve está dentro do número de dias permitidos para o dado month. years são levados em consideração.

Veja também mktime() e strtotime().

date

(PHP 3, PHP 4 )

date -- Formata a data e a hora local

Descrição

string date ( string format [, int timestamp])

Retorna uma string de acordo com o formato da string usando o inteiro dado timestamp ou a a hora corrente local se nenhum timestamp é dado.

Nota: A linha válida de um timestamp é tipicamente de Fri, 13 Dec 1901 20:45:54 GMT to Tue, 19 Jan 2038 03:14:07 GMT. (Estas são as datas que correspodem aos mínimos e máximos valores para um inteiro de 32-bit definido). No windows esta linha é limitada de 01-01-1970 para 19-01-2038.

Para gerar um timestamp de uma string para representação de data, você deve estar capaz de usarstrtotime(). Adicionalmente, alguns bancos de dados têm para converter suas datas em timestamps (tais como a função MySQL's UNIX_TIMESTAMP ).

Os seguintes caracteres são reconhecidos na estrutura da string:

  • a - "am" ou "pm"

  • A - "AM" ou "PM"

  • B - Swatch Internet time

  • d - dia do mês, 2 digitos com zeros zeros à esquerda; i.e. "01" até "31"

  • D - dia da semana, texto, 3 letras; e.g. "Fri"

  • F - mês, texto, longo; e.g. "January"

  • g - hora, Forma com 12-horas sem zeros à esquerda; i.e. "1" até "12"

  • G - hora, Forma com 24-horas sem zeros à esquerda; i.e. "0" até "23"

  • h - hora, Forma com 12-horas; i.e. "01" até "12"

  • H - hora, Forma com 24-horas; i.e. "00" até "23"

  • i - minutos; i.e. "00" até "59"

  • I (capital i) - "1" Se no horário de verão, senão "0".

  • j - Dia do mês sem zeros à esquerda; i.e. "1" até "31"

  • l (minúscula 'L') - dia da semana, texo, longo; e.g. "Friday"

  • L - booleano se é um ano bissexto; i.e. "0" ou "1"

  • m - mês; i.e. "01" até "12"

  • M - mês, texto, 3 letras; e.g. "Jan"

  • n - mês sem zeros à esquerda; i.e. "1" até "12"

  • O - Diferença entre o horário de Greenwich em horas; e.g. "+0200"

  • r - RFC 822 formatted date; e.g. "Thu, 21 Dec 2000 16:01:07 +0200" (adicionda no PHP 4.0.4)

  • s - segundos; i.e. "00" até "59"

  • S - Sufixo ordinal para o dia do mês, 2 characteres; i.e. "st", "nd", "rd" or "th"

  • t - número de dias do dado mês; i.e. "28" até "31"

  • T - Timezone setting desta máquina; e.g. "EST" or "MDT"

  • U - segundos desde a época Unix (January 1 1970 00:00:00 GMT)

  • w - dia da semana, numérico, i.e. "0" (domingo) até "6" (Sábado)

  • W - ISO-8601 números de semanas do ano, semana começa na segunda-feira (adicionado no PHP 4.1.0)

  • Y - ano, 4 dígitos; e.g. "1999"

  • y - ano, 2 dígitos; e.g. "99"

  • z - dia do ano; i.e. "0" até "365"

  • Z - timezone offset em segundos (i.e. "-43200" to "43200"). O offset para as timezones oeste de UTC é sempre negativa, e para as leste de UTC é sempre positiva.

Caracteres irreconhecíveis na forma de string serão impressas como são. O "Z" formato poderá sempre retornar "0" quando usar gmdate().

Exemplo 1. date() exemplo

echo date ("l dS of F Y h:i:s A");
echo "July 1, 2000 is on a " . date ("l", mktime(0,0,0,7,1,2000));

Você pode prevenir um caracter conhecido no formato de string de um existente por escape com uma barra invertida precedendo-o. Se o caracter com a barra invertida já é uma sequência especial , você pode precisar também de escape para a barra invertida.

Exemplo 2. Caracteres de escape em date()

echo date("l \\t\h\e jS"); // prints something like 'Saturday the 8th'

é possível usar date() e mktime() juntos para encontrar datas no futuro ou no passado.

Exemplo 3. date() e mktime() exemplo

$tomorrow  = mktime (0,0,0,date("m")  ,date("d")+1,date("Y"));
$lastmonth = mktime (0,0,0,date("m")-1,date("d"),  date("Y"));
$nextyear  = mktime (0,0,0,date("m"),  date("d"),  date("Y")+1);

Nota: Esta pode ser mais confiável do que simplesmente adicionar ou subtrair o número de segundos em um dia ou mês para um timestamp devido ao horário de verão.

Alguns exemplos de date() formatação. Note que você poderia escapar qualquer outro caracter, qualquer um que correntemente tenha um significado especial produziria resultados indesejáveis, e outros caracteres poderiam assumir significados em futuras versões do PHP. Quando usar escape, certifique o uso de aspas simples para evitar caracteres como \n próprio para novas linhas.

Exemplo 4. date() Formatação

/* Today is March 10th, 2001, 5:16:18 pm */
$today = date("F j, Y, g:i a");                 // March 10, 2001, 5:16 pm
$today = date("m.d.y");                         // 03.10.01
$today = date("j, n, Y");                       // 10, 3, 2001
$today = date("Ymd");                           // 20010310
$today = date('h-i-s, j-m-y, it is w Day z ');  // 05-16-17, 10-03-01, 1631 1618 6 Fripm01
$today = date('\i\t \i\s \t\h\e jS \d\a\y.');   // It is the 10th day.
$today = date("D M j G:i:s T Y");               // Sat Mar 10 15:16:08 MST 2001
$today = date('H:m:s \m \i\s\ \m\o\n\t\h');     // 17:03:17 m is month
$today = date("H:i:s");                         // 17:16:17

Para formatar datas em outras línguas, você usaria as funções setlocale() e strftime() .

Veja também getlastmod(), gmdate(), mktime(), strftime() e time().

getdate

(PHP 3, PHP 4 )

getdate -- Consegue informações data/hora

Descrição

array getdate ( [int timestamp])

Retorna uma matriz contendo a data do timestamp, ou a hora corrente local se se nenhum timestamp é dado, como a seguintes elementos da matriz:

  • "seconds" - segundos

  • "minutes" - minutos

  • "hours" - horas

  • "mday" - dia do ano

  • "wday" - dia da semana, numérico : de 0 como Domingo até 6 como Sábado

  • "mon" - mês, numérico

  • "year" - ano, numérico

  • "yday" - dia do ano, numérico; i.e. "299"

  • "weekday" - dia da semana, texo, completo; i.e. "Friday"

  • "month" - mês, texto, completo; i.e. "January"

Exemplo 1. getdate() exemplo

$today = getdate(); 
$month = $today['month']; 
$mday = $today['mday']; 
$year = $today['year']; 
echo "$month $mday, $year";

gettimeofday

(PHP 3>= 3.0.7, PHP 4 )

gettimeofday -- Obtém a hora local

Descrição

array gettimeofday ( void)

Esta é uma interface para gettimeofday(2). Esta retorna uma matriz contendo o dado retornado da comunicação com o sistema.

  • "sec" - segundos

  • "usec" - microsegundos

  • "minuteswest" - minutos Leste de Greenwich

  • "dsttime" - tipo de correção dst

gmdate

(PHP 3, PHP 4 )

gmdate -- Formata uma data/hora GMT/CUT

Descrição

string gmdate ( string format [, int timestamp])

Idêntico a função date() exceto que o tempo está em Greenwich Mean Time (GMT). Por exemplo, quando execulta ma Finlândia (GMT +0200), a primeira linha abaixo imprime "Jan 01 1998 00:00:00", enquando a segunda imprime "Dec 31 1997 22:00:00".

Exemplo 1. gmdate() exemplo

echo date ("M d Y H:i:s", mktime (0,0,0,1,1,1998));
echo gmdate ("M d Y H:i:s", mktime (0,0,0,1,1,1998));

veja também date(), mktime(), gmmktime() e strftime().

gmmktime

(PHP 3, PHP 4 )

gmmktime -- Consegue um timestamp UNIX para uma data GMT

Descrição

int gmmktime ( int hour, int minute, int second, int month, int day, int year [, int is_dst])

Idêntico ao mktime() exceto que os parâmetros passados representam uma data GMT.

gmstrftime

(PHP 3>= 3.0.12, PHP 4 )

gmstrftime --  Formata uma hora/data GMT/CUT de acordo com as configurações locais

Descrição

string gmstrftime ( string format [, int timestamp])

Mesmo comportamento que strftime() exceto que o tempo retornado é Greenwich Mean Time (GMT). Por exemplo, quando roda no Padrão de tempo Oriental (GMT -0500), a primeira linha abaixo imprime "Dec 31 1998 20:00:00", enquanto a segunda linha imprime "Jan 01 1999 01:00:00".

Exemplo 1. gmstrftime() exemplo

setlocale (LC_TIME, 'en_US');
echo strftime ("%b %d %Y %H:%M:%S", mktime (20,0,0,12,31,98))."\n";
echo gmstrftime ("%b %d %Y %H:%M:%S", mktime (20,0,0,12,31,98))."\n";

Veja também strftime().

localtime

(PHP 4 )

localtime -- Obtém a hora local

Descrição

array localtime ( [int timestamp [, bool is_associative]])

A função localtime() retorna uma matriz idêntica àquela da estrutura retornada pela chamada de uma função em C. O primeiro argumento para localtime() é o timestamp, se este não é dado, a hora atual é usada. O segundo argumento para localtime() é o is_associative, se este é definido como 0 ou não fornecido então a matriz é retornada como uma matriz normal , matriz com indices numéricos. Se o argumento é definido como 1 então localtime() é uma matriz associativa contendo todos os diferentes elementos da estrutura retornados pela chamada da função C para o localtime. Os nomes das diferentes chaves da matriz associativa são as seguintes:

  • "tm_sec" - segundos

  • "tm_min" - minutos

  • "tm_hour" - hora

  • "tm_mday" - dia do mês

  • "tm_mon" - mês do ano, começa com 0 para Janeiro

  • "tm_year" - Anos desde 1900

  • "tm_wday" - Dia da semana

  • "tm_yday" - Dia do ano

  • "tm_isdst" - Está em horário de verão

microtime

(PHP 3, PHP 4 )

microtime --  Retorna um timestamp UNIX com microsegundos

Description

string microtime ( void)

Retorna uma string "msec sec" onde sec é o tempo atual medido no número de segundos desde a Era Unix (0:00:00 January 1, 1970 GMT), e msec é a parte em microsegundos. Esta função está disponível unicamente em sistemas operacionais que suportam a chamada gettimeofday().

Ambas porções de string são retornadas em segundos.

Exemplo 1. microtime() exemplo

function getmicrotime(){ 
    list($usec, $sec) = explode(" ",microtime()); 
    return ((float)$usec + (float)$sec); 
    } 

$time_start = getmicrotime();
    
for ($i=0; $i < 1000; $i++){
    //do nothing, 1000 times
    }

$time_end = getmicrotime();
$time = $time_end - $time_start;

echo "Did nothing in $time seconds";

Veja também time().

mktime

(PHP 3, PHP 4 )

mktime -- Obtém um modelo UNIX para uma data

Descrição

int mktime ( int hour, int minute, int second, int month, int day, int year [, int is_dst])

Atenção: Note a estranha ordem dos argumentos, que diferem da ordem dos argumentos em um chamada regular da UNIX mktime() e que não combina bem com si mesma para a omissão dos parâmetros da direita para a esquerda (veja abaixo). é um erro comum misturar estes valores acima em um script.

Retorna o timestamp Unix correspondente para os argumentos dados. Este timestamp é um longo inteiro contendo o número de segundos entre a Era Unix (January 1 1970) e o tempo especificado.

Argumentos podem ser omitidos da direita para esquerda; quaisquer argumentos assim omitidos serão definidos para o valor atual de acordo com a data e a hora local.

is_dst pode ser definido para 1 se está durante o horário de verão, 0 se não estiver, ou -1 (o padrão) se não se sabe se está em horário de verão ou não. Se é desconhecido, o PHP tenta calcular. Isto pode causar resultados inesperados (mas não incorretos).

Nota: is_dst adicionado no 3.0.10.

mktime() é útil para fazer data aritimética e validação, ela calculará automaticamente o valor correto para um receptor fora de linha. Por exemplo, cada uma das seguintes linhas produz a string "Jan-01-1998".

Exemplo 1. mktime() exemplo

echo date ("M-d-Y", mktime (0,0,0,12,32,1997));
echo date ("M-d-Y", mktime (0,0,0,13,1,1997));
echo date ("M-d-Y", mktime (0,0,0,1,1,1998));
echo date ("M-d-Y", mktime (0,0,0,1,1,98));
Year pode ser com 2 ou 4 dígitos, com valores entre 0-69 mapeando para 2000-2069 e 70-99 para 1970-1999 (em sistemas onde time_t é um inteiro marcado de 32bit, como a maioria de hoje, uma linha válida Year é qualquer coisa entre 1902 e 2037).

O último dia de qualquer mês pode ser expresso como o dia "0" do próximo mês, não o dia -1. Os seguintes exemplos produzirão a string "The last day in Feb 2000 is: 29".

Exemplo 2. Ultimo dia do próximo mês

$lastday = mktime (0,0,0,3,0,2000);
echo strftime ("Last day in Feb 2000 is: %d", $lastday);
     
$lastday = mktime (0,0,0,4,-31,2000);
echo strftime ("Last day in Feb 2000 is: %d", $lastday);

Data com ano, mês e dia igual a zero é considerado ilegal (senão ele é considerado como 30.11.1999, que poderia ser um comportamento estranho).

Veja também date() e time().

strftime

(PHP 3, PHP 4 )

strftime --  Formata uma hora/data de acordo com as configurações locais

Descrição

string strftime ( string format [, int timestamp])

Retorna uma string formatada de acordo com o formato dado em timestamp ou o horário corrente se nenhum timestamp é dado. Nomes de mês e dia da semana e outras strings dependentes de linguagens respeitam o a localidade definida com setlocale().

As seguintes conversões especificadoras são conhecidas no formato de string:

  • %a - dia da semana abreviado de acordo com a localidade

  • %A - nome da semana completo de acordo com a localidade

  • %b - nome do mês abreviado de acordo com a localidade

  • %B - nome do mês completo de acordo com a localidade

  • %c - representação da data e hora preferida para a localidade

  • %C - número do século (o ano dividido por 100 e truncado para um inteiro, de 00 até 99)

  • %d - dia do mês como um número decimal (de 01 até 31)

  • %D - mesmo que %m/%d/%y

  • %e - dia do mês como um número decimal, um simples dígito é precedido por espaço (de ' 1' até '31')

  • %g - como %G, mas sem o século.

  • %G - o 4-dígito do ano correspodendo as ISO week number (see %V). Este tem o mesmo formato e valor que %Y, exceto que se o ISO week number pertence ao prévio ou próximo ano, aquele ano é usado ao invés deste.

  • %h - mesmo que %b

  • %H - hora como um número decimal usando um relógio de 24-horas (de 00 até 23)

  • %I - hora como um número decimal usando um relógio de 12-hoas (de 01 até 12)

  • %j - dia do ano como número decimal (de 001 até 366)

  • %m - mês como número decimal (de 01 até 12)

  • %M - minuto como número decimal

  • %n - caracter novalinha

  • %p - um dos dois `am' ou `pm' de acordo com o valor da hora dada, ou as strings correspondentes para a localidade

  • %r - hora em a.m. e p.m. notação

  • %R - hora em notação de 24 horas

  • %S - segundo como um número decimal

  • %t - caracter tab

  • %T - hora corrente, igual a %H:%M:%S

  • %u - dia da semana como número decimal [1,7], com 1 representando Segunda-feira

    Atenção

    Sun Solaris parece iniciar o Domingo como 1 embora ISO 9889:1999 (o padrão C corrente) claramente especificados que ele poderia ser segunda-feira.

  • %U - dia da semana do ano corrente como número decimal, começando com o primeiro domingo como o primeiro dia da primeira semana

  • %V - \O número da semana corrente ISO 8601:1988 do ano corrente como um número decimal, de 01 até 53, onde semana 1 é a primeira semana que tem pelo menos 4 dias no ano corrente, e com segunda-feira como o primeiro dia da semana. (Use %G ou %g para o componente anual que corresponde ao dia da semana para o para o timestamp especificado.)

  • %W - dia da semana do ano corrente como número decimal, começando com o a segunda-feira como o primeiro dia da primera semana

  • %w - dia da semana como número decimal, domingo sendo 0

  • %x - representação preferida para a data para a localidade corrente sem a hora

  • %X - representação preferida para a hora para a localidade corrente sem a data

  • %y - ano como número decimal sem o século (de 00 até 99)

  • %Y - ano como número decimal incluindo o século

  • %Z - time zone ou nome or abreviação

  • %% - a literal `%' character

Nota: Note que todas as conversões especificadas podem ser suportadas pela sua biblioteca C, em alguns casos elas não serão suportadas pelo PHP strftime(). significa que e.g. %e, %T, e %D não trabalharão em windows.

Exemplo 1. strftime() exemplo

setlocale (LC_TIME, "C");
print (strftime ("%A in Finnish is "));
setlocale (LC_TIME, "fi_FI");
print (strftime ("%A, in French "));
setlocale (LC_TIME, "fr_FR");
print (strftime ("%A and in German "));
setlocale (LC_TIME, "de_DE");
print (strftime ("%A.\n"));
Este exemplo trabalha se você tiver as respectivas localidades instaladas em seu sistema.

Veja também setlocale() e mktime() e a Open Group specification de strftime().

strtotime

(PHP 3>= 3.0.12, PHP 4 )

strtotime --  Analisa qualquer descrição em texto em inglês de data hora em timestamp UNIX

Descrição

int strtotime ( string time [, int now])

A função espera que seja dado uma string contendo um formato de data em inglês e tentará analisar esse formato dentro de um timestamp Unix relativo ao timestamp dado em now, ou a hora atual se nada é fornecido. Se fracassa, -1 é retornado.

Porque strtotime() comporta-se de acordo com a sintaxe de data GNU, procure na página do manual GNU Date Input Formats. Lá está descrito a sintaxe válida para o parâmetro time.

Exemplo 1. strtotime() exemplos

echo strtotime ("now"), "\n";
echo strtotime ("10 September 2000"), "\n";
echo strtotime ("+1 day"), "\n";
echo strtotime ("+1 week"), "\n";
echo strtotime ("+1 week 2 days 4 hours 2 seconds"), "\n";
echo strtotime ("next Thursday"), "\n";
echo strtotime ("last Monday"), "\n";

Exemplo 2. Checando por fracasso

$str = 'Not Good';
if (($timestamp = strtotime($str)) === -1) {
    echo "The string ($str) is bogus";
} else {
    echo "$str == ". date('l dS of F Y h:i:s A',$timestamp);
}

Nota: A linha de um timestamp válido é basicamente Fri, 13 Dec 1901 20:45:54 GMT to Tue, 19 Jan 2038 03:14:07 GMT. (Estes são os dados que correspondem aos valores máximos e mínimos para um inteiro de 32-bit.)

time

(PHP 3, PHP 4 )

time -- Retorna o timestamp UNIX

Descrição

int hour ( void)

Retorna a hora atual medida no número de segundos desde a Era Unix (January 1 1970 00:00:00 GMT).

Veja também date().

XIX. dBase functions

Introdução

These functions allow you to access records stored in dBase-format (dbf) databases.

There is no support for indexes or memo fields. There is no support for locking, too. Two concurrent webserver processes modifying the same dBase file will very likely ruin your database.

dBase files are simple sequential files of fixed length records. Records are appended to the end of the file and delete records are kept until you call dbase_pack().

We recommend that you do not use dBase files as your production database. Choose any real SQL server instead; MySQL or Postgres are common choices with PHP. dBase support is here to allow you to import and export data to and from your web database, because the file format is commonly understood by Windows spreadsheets and organizers.


Instalação

In order to enable the bundled dbase library and to use these functions, you must compile PHP with the --enable-dbase option.


Configuração durante execução

Esta extenção não define nenhum parâmetro de configuração no php.ini.


Tipos Resource

Esta extensão não possui nenhum tipo resource.


Constantes Predefinidas

Esta extensão não possui nenhuma constante.

Índice
dbase_add_record -- Add a record to a dBase database
dbase_close -- Close a dBase database
dbase_create -- Creates a dBase database
dbase_delete_record -- Deletes a record from a dBase database
dbase_get_record_with_names --  Gets a record from a dBase database as an associative array
dbase_get_record -- Gets a record from a dBase database
dbase_numfields --  Find out how many fields are in a dBase database
dbase_numrecords --  Find out how many records are in a dBase database
dbase_open -- Opens a dBase database
dbase_pack -- Packs a dBase database
dbase_replace_record -- Replace a record in a dBase database

dbase_add_record

(PHP 3, PHP 4 )

dbase_add_record -- Add a record to a dBase database

Description

bool dbase_add_record ( int dbase_identifier, array record)

Adds the data in the record to the database. If the number of items in the supplied record isn't equal to the number of fields in the database, the operation will fail and FALSE will be returned.

dbase_close

(PHP 3, PHP 4 )

dbase_close -- Close a dBase database

Description

bool dbase_close ( int dbase_identifier)

Closes the database associated with dbase_identifier.

dbase_create

(PHP 3, PHP 4 )

dbase_create -- Creates a dBase database

Description

int dbase_create ( string filename, array fields)

The fields parameter is an array of arrays, each array describing the format of one field in the database. Each field consists of a name, a character indicating the field type, a length, and a precision.

The types of fields available are:

L

Boolean. These do not have a length or precision.

M

Memo. (Note that these aren't supported by PHP.) These do not have a length or precision.

D

Date (stored as YYYYMMDD). These do not have a length or precision.

N

Number. These have both a length and a precision (the number of digits after the decimal point).

C

String.

If the database is successfully created, a dbase_identifier is returned, otherwise FALSE is returned.

Exemplo 1. Creating a dBase database file

// "database" name
$dbname = "/tmp/test.dbf";

// database "definition"
$def =
    array(
        array("date",     "D"),
        array("name",     "C",  50),
        array("age",      "N",   3, 0),
        array("email",    "C", 128),
        array("ismember", "L")
    );

// creation
if (!dbase_create($dbname, $def))
    print "<strong>Error!</strong>";

dbase_delete_record

(PHP 3, PHP 4 )

dbase_delete_record -- Deletes a record from a dBase database

Description

bool dbase_delete_record ( int dbase_identifier, int record)

Marks record to be deleted from the database. To actually remove the record from the database, you must also call dbase_pack().

dbase_get_record_with_names

(PHP 3>= 3.0.4, PHP 4 )

dbase_get_record_with_names --  Gets a record from a dBase database as an associative array

Description

array dbase_get_record_with_names ( int dbase_identifier, int record)

Returns the data from record in an associative array. The array also includes an associative member named 'deleted' which is set to 1 if the record has been marked for deletion (see dbase_delete_record()).

Each field is converted to the appropriate PHP type, except:

  • Dates are left as strings

  • Integers that would have caused an overflow (> 32 bits) are returned as strings

dbase_get_record

(PHP 3, PHP 4 )

dbase_get_record -- Gets a record from a dBase database

Description

array dbase_get_record ( int dbase_identifier, int record)

Returns the data from record in an array. The array is indexed starting at 0, and includes an associative member named 'deleted' which is set to 1 if the record has been marked for deletion (see dbase_delete_record().

Each field is converted to the appropriate PHP type, except:

  • Dates are left as strings

  • Integers that would have caused an overflow (> 32 bits) are returned as strings

dbase_numfields

(PHP 3, PHP 4 )

dbase_numfields --  Find out how many fields are in a dBase database

Description

int dbase_numfields ( int dbase_identifier)

Returns the number of fields (columns) in the specified database. Field numbers are between 0 and dbase_numfields($db)-1, while record numbers are between 1 and dbase_numrecords($db).

Exemplo 1. Using dbase_numfields()

$rec = dbase_get_record($db, $recno);
$nf  = dbase_numfields($db);
for ($i=0; $i < $nf; $i++) {
    print $rec[$i]."<br>\n";
}

dbase_numrecords

(PHP 3, PHP 4 )

dbase_numrecords --  Find out how many records are in a dBase database

Description

int dbase_numrecords ( int dbase_identifier)

Returns the number of records (rows) in the specified database. Record numbers are between 1 and dbase_numrecords($db), while field numbers are between 0 and dbase_numfields($db)-1.

dbase_open

(PHP 3, PHP 4 )

dbase_open -- Opens a dBase database

Description

int dbase_open ( string filename, int flags)

The flags correspond to those for the open() system call. (Typically 0 means read-only, 1 means write-only, and 2 means read and write.)

Returns a dbase_identifier for the opened database, or FALSE if the database couldn't be opened.

Nota: Quando o safe-mode está ativo, o PHP verifica se o(s) arquivo(s) e/ou diretório(s) que serão afetados por esta operação tem o mesmo UID (proprietário) do script que está sendo executado.

dbase_pack

(PHP 3, PHP 4 )

dbase_pack -- Packs a dBase database

Description

bool dbase_pack ( int dbase_identifier)

Packs the specified database (permanently deleting all records marked for deletion using dbase_delete_record()).

dbase_replace_record

(PHP 3>= 3.0.11, PHP 4 )

dbase_replace_record -- Replace a record in a dBase database

Description

bool dbase_replace_record ( int dbase_identifier, array record, int dbase_record_number)

Replaces the data associated with the record record_number with the data in the record in the database. If the number of items in the supplied record is not equal to the number of fields in the database, the operation will fail and FALSE will be returned.

dbase_record_number is an integer which spans from 1 to the number of records in the database (as returned by dbase_numrecords()).

XX. DBM Functions [deprecated]

Introdução

These functions allow you to store records stored in a dbm-style database. This type of database (supported by the Berkeley DB, GDBM, and some system libraries, as well as a built-in flatfile library) stores key/value pairs (as opposed to the full-blown records supported by relational databases).

Nota: However, dbm support is deprecated and you are encourged to use the Database (dbm-style) abstraction layer functions instead.


Requisitos

To use this functions you have to compile PHP with support for an underlying database. See the list of supported Databases.


Instalação

In order to use these functions, you must compile PHP with dbm support by using the --with-db option. In addition you must ensure support for an underlying database or you can use some sytem libraries.


Configuração durante execução

Esta extenção não define nenhum parâmetro de configuração no php.ini.


Tipos Resource

The function dbmopen() returns an database identifier which is used by the other dbm-functions.


Constantes Predefinidas

Esta extensão não possui nenhuma constante.


Exemplos

Exemplo 1. DBM example

$dbm = dbmopen ("lastseen", "w");
if (dbmexists ($dbm, $userid)) {
    $last_seen = dbmfetch ($dbm, $userid);
} else {
    dbminsert ($dbm, $userid, time());
}
do_stuff();
dbmreplace ($dbm, $userid, time());
dbmclose ($dbm);

Índice
dblist --  Describes the DBM-compatible library being used
dbmclose -- Closes a dbm database
dbmdelete --  Deletes the value for a key from a DBM database
dbmexists --  Tells if a value exists for a key in a DBM database
dbmfetch --  Fetches a value for a key from a DBM database
dbmfirstkey --  Retrieves the first key from a DBM database
dbminsert --  Inserts a value for a key in a DBM database
dbmnextkey --  Retrieves the next key from a DBM database
dbmopen -- Opens a DBM database
dbmreplace --  Replaces the value for a key in a DBM database

dblist

(PHP 3, PHP 4 )

dblist --  Describes the DBM-compatible library being used

Description

string dblist ( void)

Exemplo 1. Getting the information on the command line

[marcus@zaphod marcus]$ php -r 'echo dblist();'
This is GDBM version 1.8.0, as of May 19, 1999.

dbmclose

(PHP 3, PHP 4 )

dbmclose -- Closes a dbm database

Description

bool dbmclose ( resource dbm_identifier)

Unlocks and closes the specified database.

dbmdelete

(PHP 3, PHP 4 )

dbmdelete --  Deletes the value for a key from a DBM database

Description

bool dbmdelete ( resource dbm_identifier, string key)

Deletes the value for key in the database.

Returns FALSE if the key didn't exist in the database.

dbmexists

(PHP 3, PHP 4 )

dbmexists --  Tells if a value exists for a key in a DBM database

Description

bool dbmexists ( resource dbm_identifier, string key)

Returns TRUE if there is a value associated with the key.

dbmfetch

(PHP 3, PHP 4 )

dbmfetch --  Fetches a value for a key from a DBM database

Description

string dbmfetch ( resource dbm_identifier, string key)

Returns the value associated with key.

dbmfirstkey

(PHP 3, PHP 4 )

dbmfirstkey --  Retrieves the first key from a DBM database

Description

string dbmfirstkey ( resource dbm_identifier)

Returns the first key in the database. Note that no particular order is guaranteed since the database may be built using a hash-table, which doesn't guarantee any ordering.

dbminsert

(PHP 3, PHP 4 )

dbminsert --  Inserts a value for a key in a DBM database

Description

int dbminsert ( resource dbm_identifier, string key, string value)

Adds the value to the database with the specified key.

Returns -1 if the database was opened read-only, 0 if the insert was successful, and 1 if the specified key already exists. (To replace the value, use dbmreplace().)

dbmnextkey

(PHP 3, PHP 4 )

dbmnextkey --  Retrieves the next key from a DBM database

Description

string dbmnextkey ( resource dbm_identifier, string key)

Returns the next key after key. By calling dbmfirstkey() followed by successive calls to dbmnextkey() it is possible to visit every key/value pair in the dbm database. For example:

Exemplo 1. Visiting every key/value pair in a DBM database

$key = dbmfirstkey ($dbm_id);
while ($key) {
    echo "$key = " . dbmfetch ($dbm_id, $key) . "\n";
    $key = dbmnextkey ($dbm_id, $key);
}

dbmopen

(PHP 3, PHP 4 )

dbmopen -- Opens a DBM database

Description

resource dbmopen ( string filename, string flags)

The first argument is the full-path filename of the DBM file to be opened and the second is the file open mode which is one of "r", "n", "c" or "w" for read-only, new (implies read-write, and most likely will truncate an already-existing database of the same name), create (implies read-write, and will not truncate an already-existing database of the same name) and read-write respectively.

Returns an identifier to be passed to the other DBM functions on success, or FALSE on failure.

If NDBM support is used, NDBM will actually create filename.dir and filename.pag files. GDBM only uses one file, as does the internal flat-file support, and Berkeley DB creates a filename.db file. Note that PHP does its own file locking in addition to any file locking that may be done by the DBM library itself. PHP does not delete the .lck files it creates. It uses these files simply as fixed inodes on which to do the file locking. For more information on DBM files, see your Unix man pages, or obtain GNU's GDBM.

Nota: Quando o safe-mode está ativo, o PHP verifica se o(s) arquivo(s) e/ou diretório(s) que serão afetados por esta operação tem o mesmo UID (proprietário) do script que está sendo executado.

dbmreplace

(PHP 3, PHP 4 )

dbmreplace --  Replaces the value for a key in a DBM database

Description

int dbmreplace ( resource dbm_identifier, string key, string value)

Replaces the value for the specified key in the database.

This will also add the key to the database if it didn't already exist.

XXI. dbx functions

Introdução

The dbx module is a database abstraction layer (db 'X', where 'X' is a supported database). The dbx functions allow you to access all supported databases using a single calling convention. The dbx-functions themselves do not interface directly to the databases, but interface to the modules that are used to support these databases.


Requisitos

To be able to use a database with the dbx-module, the module must be either linked or loaded into PHP, and the database module must be supported by the dbx-module. Currently, following databases are supported, but others will follow:

Documentation for adding additional database support to dbx can be found at http://www.guidance.nl/php/dbx/doc/.


Instalação

In order to have these functions available, you must compile PHP with dbx support by using the --enable-dbx option and all options for the databases that will be used, e.g. for MySQL you must also specify --with-mysql=[DIR]. To get other supported databases to work with the dbx-module refer to their specific documentation.


Configuração durante execução

O comportamento dessas funções podem ser modificado pelas configurações do php.ini.

Tabela 1. DBX Configuration Options

Name Default Changeable
dbx.colnames_case "unchanged" PHP_INI_SYSTEM
For further details and definition of the PHP_INI_* constants see ini_set().

Nota: This ini-option is available available from PHP 4.3.0.

Here is a short explanation of the configuration directives.

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


Tipos Resource

There are two resource types used in the dbx module. The first one is the link-object for a database connection, the second a result-object which helds the result of a query.


Constantes Predefinidas

As contantes abaixo são definidas por esta extensão e somente estarão disponíveis quando a extensão foi compilada com o PHP ou carregada dinamicamente durante a execução.

DBX_MYSQL (integer)

DBX_ODBC (integer)

DBX_PGSQL (integer)

DBX_MSSQL (integer)

DBX_FBSQL (integer)

DBX_OCI8 (integer) (available from PHP 4.3.0)

DBX_SYBASECT (integer)

DBX_PERSISTENT (integer)

DBX_RESULT_INFO (integer)

DBX_RESULT_INDEX (integer)

DBX_RESULT_ASSOC (integer)

DBX_COLNAMES_UNCHANGED (integer) (available from PHP 4.3.0)

DBX_COLNAMES_UPPERCASE (integer) (available from PHP 4.3.0)

DBX_COLNAMES_LOWERCASE (integer) (available from PHP 4.3.0)

DBX_CMP_NATIVE (integer)

DBX_CMP_TEXT (integer)

DBX_CMP_NUMBER (integer)

DBX_CMP_ASC (integer)

DBX_CMP_DESC (integer)

Índice
dbx_close -- Close an open connection/database
dbx_compare -- Compare two rows for sorting purposes
dbx_connect -- Open a connection/database
dbx_error --  Report the error message of the latest function call in the module (not just in the connection)
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)
dbx_sort --  Sort a result from a dbx_query by a custom sort function

dbx_close

(PHP 4 >= 4.0.6)

dbx_close -- Close an open connection/database

Description

bool dbx_close ( object link_identifier)

Retorna TRUE em caso de sucesso ou FALSE em falhas.

Exemplo 1. dbx_close() example

<?php
$link = dbx_connect(DBX_MYSQL, "localhost", "db", "username", "password")
    or die ("Could not connect");

print("Connected successfully");
dbx_close($link);
?>

Nota: Always refer to the module-specific documentation as well.

See also: dbx_connect().

dbx_compare

(PHP 4 >= 4.1.0)

dbx_compare -- Compare two rows for sorting purposes

Description

int dbx_compare ( array row_a, array row_b, string column_key [, int flags])

dbx_compare() returns 0 if the row_a[$column_key] is equal to row_b[$column_key], and 1 or -1 if the former is greater or is smaller than the latter one, respectively, or vice versa if the flag is set to DBX_CMP_DESC. dbx_compare() is a helper function for dbx_sort() to ease the make and use of the custom sorting function.

The flags can be set to specify comparison direction:

  • DBX_CMP_ASC - ascending order

  • DBX_CMP_DESC - descending order

and the preferred comparison type:

  • DBX_CMP_NATIVE - no type conversion

  • DBX_CMP_TEXT - compare items as strings

  • DBX_CMP_NUMBER - compare items numerically

One of the direction and one of the type constant can be combined with bitwise OR operator (|). The default value for the flags parameter is DBX_CMP_ASC | DBX_CMP_NATIVE.

Exemplo 1. dbx_compare() example

<?php
function user_re_order ($a, $b) {
    $rv = dbx_compare ($a, $b, "parentid", DBX_CMP_DESC);
    if ( !$rv ) {
        $rv = dbx_compare ($a, $b, "id", DBX_CMP_NUMBER);
    }
    return $rv;
}

$link   = dbx_connect (DBX_ODBC, "", "db", "username", "password")
    or die ("Could not connect");

$result = dbx_query ($link, "SELECT id, parentid, description FROM table ORDER BY id");
    // data in $result is now ordered by id

dbx_sort ($result, "user_re_order");
    // date in $result is now ordered by parentid (descending), then by id

dbx_close ($link);
?>

See also dbx_sort().

dbx_connect

(PHP 4 >= 4.0.6)

dbx_connect -- Open a connection/database

Description

object dbx_connect ( mixed module, string host, string database, string username, string password [, int persistent])

dbx_connect() returns an object on success, FALSE on error. If a connection has been made but the database could not be selected, the connection is closed and FALSE is returned. The persistent parameter can be set to DBX_PERSISTENT, if so, a persistent connection will be created.

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 they only work if the module is actually loaded.

  • DBX_MYSQL or "mysql"

  • DBX_ODBC or "odbc"

  • DBX_PGSQL or "pgsql"

  • DBX_MSSQL or "mssql"

  • DBX_FBSQL or "fbsql" (available from PHP 4.1.0)

  • DBX_SYBASECT or "sybase_ct" (available from PHP 4.2.0)

  • DBX_OCI8 or "oci8" (available from PHP 4.3.0)

The host, database, username and password parameters are expected, but not always used depending on the connect functions for the abstracted module.

The returned object has three properties:

database

It is the name of the currently selected database.

handle

It is a valid handle for the connected database, and as such it can be used in module-specific functions (if required).

$link = dbx_connect (DBX_MYSQL, "localhost", "db", "username", "password");
mysql_close ($link->handle); // dbx_close($link) would be better here

module

It is used internally by dbx only, and is actually the module number mentioned above.

Exemplo 1. dbx_connect() example

<?php
$link = dbx_connect (DBX_ODBC, "", "db", "username", "password", DBX_PERSISTENT)
    or die ("Could not connect");

print ("Connected successfully");
dbx_close ($link);
?>

Nota: Always refer to the module-specific documentation as well.

See also: dbx_close().

dbx_error

(PHP 4 >= 4.0.6)

dbx_error --  Report the error message of the latest function call in the module (not just in the connection)

Description

string dbx_error ( object link_identifier)

dbx_error() returns a string containing the error message from the last function call of the abstracted module (e.g. mysql module). If there are multiple connections in the same module, just the last error is given. If there are connections on different modules, the latest error is returned for the module specified by the link_identifier parameter.

Exemplo 1. dbx_error() example

<?php
$link   = dbx_connect(DBX_MYSQL, "localhost", "db", "username", "password")
    or die ("Could not connect");

$result = dbx_query($link, "select id from non_existing_table");
if ( $result == 0 ) {
    echo dbx_error ($link);
}
dbx_close ($link);
?>

Nota: Always refer to the module-specific documentation as well.

The error message for Microsoft SQL Server is actually the result of the mssql_get_last_message() function.

The error message for Oracle (oci8) is not implemented (yet).

dbx_escape_string

(PHP 4 >= 4.3.0)

dbx_escape_string --  Escape a string so it can safely be used in an sql-statement.

Description

string dbx_escape_string ( object link_identifier, string text)

dbx_escape_string() returns the text, escaped where necessary (such as quotes, backslashes etc). It returns NULL on error.

Exemplo 1. dbx_escape_string() example

<?php
$link   = dbx_connect(DBX_MYSQL, "localhost", "db", "username", "password")
    or die ("Could not connect");

$text = dbx_escape_string($link, "It\'s quoted and backslashed (\\).");
$result = dbx_query($link, "insert into tbl (txt) values ('".$text."')");
if ( $result == 0 ) {
    echo dbx_error ($link);
}
dbx_close ($link);
?>

See also: dbx_query().

dbx_query

(PHP 4 >= 4.0.6)

dbx_query -- Send a query and fetch all results (if any)

Description

object dbx_query ( object link_identifier, string sql_statement [, long flags])

dbx_query() returns an object or 1 on success, and 0 on failure. The result object is returned only if the query given in sql_statement produces a result set.

Exemplo 1. How to handle the returned value

<?php
$link   = dbx_connect(DBX_ODBC, "", "db", "username", "password")
    or die("Could not connect");

$result = dbx_query($link, 'SELECT id, parentid, description FROM table');

if ( is_object($result) ) {
    // ... do some stuff here, see detailed examples below ...
    // first, print out field names and types 
    // then, draw a table filled with the returned field values
}
else if ( $result == 1 ) {
    echo("Query executed successfully, but no result set returned");
}
else {
    exit("Query failed");
}

dbx_close($link);
?>

The flags parameter is used to control the amount of information that is returned. It may be any combination of the following constants with the bitwise OR operator (|). The DBX_COLNAMES_* flags override the dbx.colnames_case setting from php.ini.

DBX_RESULT_INDEX

It is always set, that is, the returned object has a data property which is a 2 dimensional array indexed numerically. For example, in the expression data[2][3] 2 stands for the row (or record) number and 3 stands for the column (or field) number. The first row and column are indexed at 0.

If DBX_RESULT_ASSOC is also specified, the returning object contains the information related to DBX_RESULT_INFO too, even if it was not specified.

DBX_RESULT_INFO

It provides info about columns, such as field names and field types.

DBX_RESULT_ASSOC

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 the numerically indexed data, so modifying data[0][0] causes that data[0]['field_name_for_first_column'] is modified as well.

DBX_COLNAMES_UNCHANGED (available from PHP 4.3.0)

The case of the returned column names will not be changed.

DBX_COLNAMES_UPPERCASE (available from PHP 4.3.0)

The case of the returned column names will be changed to uppercase.

DBX_COLNAMES_LOWERCASE (available from PHP 4.3.0)

The case of the returned column names will be changed to lowercase.

Note that DBX_RESULT_INDEX is always used, regardless of the actual value of flags parameter. This means that the following combinations is effective only:

  • DBX_RESULT_INDEX

  • DBX_RESULT_INDEX | DBX_RESULT_INFO

  • DBX_RESULT_INDEX | DBX_RESULT_INFO | DBX_RESULT_ASSOC - this is the default, if flags is not specified.

The returing object has four or five properties depending on flags:

handle

It is a valid handle for the connected database, and as such it can be used in module specific functions (if required).

$result = dbx_query ($link, "SELECT id FROM table");
mysql_field_len ($result->handle, 0);

cols and rows

These contain the number of columns (or fields) and rows (or records) respectively.

$result = dbx_query ($link, 'SELECT id FROM table');
echo $result->rows; // number of records
echo $result->cols; // number of fields

info (optional)

It is returned only if either DBX_RESULT_INFO or DBX_RESULT_ASSOC is specified in the flags parameter. It is a 2 dimensional array, that has two named rows (name and type) to retrieve column information.

Exemplo 2. lists each field's name and type

$result = dbx_query ($link, 'SELECT id FROM table',
                     DBX_RESULT_INDEX | DBX_RESULT_INFO);

for ($i = 0; $i < $result->cols; $i++ ) {
    echo $result->info['name'][$i] . "\n";
    echo $result->info['type'][$i] . "\n";  
}
data

This property contains the actual resulting data, possibly associated with column names as well depending on flags. If DBX_RESULT_ASSOC is set, it is possible to use $result->data[2]["field_name"].

Exemplo 3. outputs the content of data property into HTML table

$result = dbx_query ($link, 'SELECT id, parentid, description FROM table');

echo "<table>\n";
foreach ( $result->data as $row ) {
    echo "<tr>\n";
    foreach ( $row as $field ) {
        echo "<td>$field</td>";
    }
    echo "</tr>\n";
}
echo "</table>\n";

Nota: Always refer to the module-specific documentation as well.

Column names for queries on an Oracle database are returned in lowercase.

See also: dbx_escape_string() and dbx_connect().

dbx_sort

(PHP 4 >= 4.0.6)

dbx_sort --  Sort a result from a dbx_query by a custom sort function

Description

bool dbx_sort ( object result, string user_compare_function)

Retorna TRUE em caso de sucesso ou FALSE em falhas.

Nota: It is always better to use ORDER BY SQL clause instead of dbx_sort(), if possible.

Exemplo 1. dbx_sort() example

<?php
function user_re_order ($a, $b) {
    $rv = dbx_compare ($a, $b, "parentid", DBX_CMP_DESC);
    if ( !$rv ) {
        $rv = dbx_compare ($a, $b, "id", DBX_CMP_NUMBER);
    }
    return $rv;
}

$link   = dbx_connect (DBX_ODBC, "", "db", "username", "password")
    or die ("Could not connect");

$result = dbx_query ($link, "SELECT id, parentid, description FROM tbl ORDER BY id");
    // data in $result is now ordered by id

dbx_sort ($result, "user_re_order");
    // data in $result is now ordered by parentid (descending), then by id

dbx_close ($link);
?>

See also dbx_compare().

XXII. DB++ Functions

Atenção

Este módulo é EXPERIMENTAL. Isso quer dizer que o comportamento neste módulo --- incluindo suas funções e seus nomes, e TUDO mais que está documentado sobre esse módulo --- poderá mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use este módulo por sua própria conta e risco.


Introdução

db++, made by the German company Concept asa, is a 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 database in the first place but provides its own AQL query language which is much more influenced by the relational algebra then SQL is.

Concept asa always had an interest in supporting open source languages, db++ has had Perl and Tcl call interfaces for years now and uses Tcl as its internal stored procedure language.


Requisitos

This extension relies on external client libraries so you have to have a db++ client installed on the system you want to use this extension on.

Concept asa provides db++ Demo versions and documentation for Linux, some other UNIX versions. There is also a Windows version of db++, but this extension doesn't support it (yet).


Instalação

In order to build this extension yourself you need the db++ client libraries and header files to be installed on your system (these are included in the db++ installation archives by default). You have to run configure with option --with-dbplus to build this extension.

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 you have add the installation path to the configure option like this: --with-dbplus=/your/installation/path.


Configuração durante execução

Esta extenção não define nenhum parâmetro de configuração no php.ini.


Tipos Resource

dbplus_relation

Most db++ functions operate on or return dbplus_relation resources. A dbplus_relation is a handle to a stored relation or a relation generated as the result of a query.


Constantes Predefinidas

As contantes abaixo são definidas por esta extensão e somente estarão disponíveis quando a extensão foi compilada com o PHP ou carregada dinamicamente durante a execução.


db++ error codes

Tabela 1. DB++ Error Codes

PHP Constant db++ constant meaning
DBPLUS_ERR_NOERR (integer) ERR_NOERR Null error condition
DBPLUS_ERR_DUPLICATE (integer) ERR_DUPLICATE Tried to insert a duplicate tuple
DBPLUS_ERR_EOSCAN (integer) ERR_EOSCAN End of scan from rget()
DBPLUS_ERR_EMPTY (integer) ERR_EMPTY Relation is empty (server)
DBPLUS_ERR_CLOSE (integer) ERR_CLOSE The server can't close
DBPLUS_ERR_WLOCKED (integer) ERR_WLOCKED The record is write locked
DBPLUS_ERR_LOCKED (integer) ERR_LOCKED Relation was already locked
DBPLUS_ERR_NOLOCK (integer) ERR_NOLOCK Relation cannot be locked
DBPLUS_ERR_READ (integer) ERR_READ Read error on relation
DBPLUS_ERR_WRITE (integer) ERR_WRITE Write error on relation
DBPLUS_ERR_CREATE (integer) ERR_CREATE Create() system call failed
DBPLUS_ERR_LSEEK (integer) ERR_LSEEK Lseek() system call failed
DBPLUS_ERR_LENGTH (integer) ERR_LENGTH Tuple exceeds maximum length
DBPLUS_ERR_OPEN (integer) ERR_OPEN Open() system call failed
DBPLUS_ERR_WOPEN (integer) ERR_WOPEN Relation already opened for writing
DBPLUS_ERR_MAGIC (integer) ERR_MAGIC File is not a relation
DBPLUS_ERR_VERSION (integer) ERR_VERSION File is a very old relation
DBPLUS_ERR_PGSIZE (integer) ERR_PGSIZE Relation uses a different page size
DBPLUS_ERR_CRC (integer) ERR_CRC Invalid crc in the superpage
DBPLUS_ERR_PIPE (integer) ERR_PIPE Piped relation requires lseek()
DBPLUS_ERR_NIDX (integer) ERR_NIDX Too many secondary indices
DBPLUS_ERR_MALLOC (integer) ERR_MALLOC Malloc() call failed
DBPLUS_ERR_NUSERS (integer) ERR_NUSERS Error use of max users
DBPLUS_ERR_PREEXIT (integer) ERR_PREEXIT Caused by invalid usage
DBPLUS_ERR_ONTRAP (integer) ERR_ONTRAP Caused by a signal
DBPLUS_ERR_PREPROC (integer) ERR_PREPROC Error in the preprocessor
DBPLUS_ERR_DBPARSE (integer) ERR_DBPARSE Error in the parser
DBPLUS_ERR_DBRUNERR (integer) ERR_DBRUNERR Run error in db
DBPLUS_ERR_DBPREEXIT (integer) ERR_DBPREEXIT Exit condition caused by prexit() * procedure
DBPLUS_ERR_WAIT (integer) ERR_WAIT Wait a little (Simple only)
DBPLUS_ERR_CORRUPT_TUPLE (integer) ERR_CORRUPT_TUPLE A client sent a corrupt tuple
DBPLUS_ERR_WARNING0 (integer) ERR_WARNING0 The Simple routines encountered a non fatal error which was corrected
DBPLUS_ERR_PANIC (integer) ERR_PANIC The server should not really die but after a disaster send ERR_PANIC to all its clients
DBPLUS_ERR_FIFO (integer) ERR_FIFO Can't create a fifo
DBPLUS_ERR_PERM (integer) ERR_PERM Permission denied
DBPLUS_ERR_TCL (integer) ERR_TCL TCL_error
DBPLUS_ERR_RESTRICTED (integer) ERR_RESTRICTED Only two users
DBPLUS_ERR_USER (integer) ERR_USER An error in the use of the library by an application programmer
DBPLUS_ERR_UNKNOWN (integer) ERR_UNKNOWN  

Índice
dbplus_add -- Add a tuple to a relation
dbplus_aql -- Perform AQL query
dbplus_chdir -- Get/Set database virtual current directory
dbplus_close -- Close a relation
dbplus_curr -- Get current tuple from relation
dbplus_errcode --  Get error string for given errorcode or last error
dbplus_errno -- Get error code for last operation
dbplus_find -- Set a constraint on a relation
dbplus_first -- Get first tuple from relation
dbplus_flush -- Flush all changes made on a relation
dbplus_freealllocks -- Free all locks held by this client
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
dbplus_getunique -- Get a id number unique to a relation
dbplus_info -- ???
dbplus_last -- Get last tuple from relation
dbplus_lockrel -- Request write lock on relation
dbplus_next -- Get next tuple from relation
dbplus_open -- Open relation file
dbplus_prev -- Get previous tuple from relation
dbplus_rchperm -- Change relation permissions
dbplus_rcreate -- Creates a new DB++ relation
dbplus_rcrtexact -- Creates an exact but empty copy of a relation including indices
dbplus_rcrtlike -- Creates an empty copy of a relation with default indices
dbplus_resolve -- Resolve host information for relation
dbplus_restorepos -- ???
dbplus_rkeys -- Specify new primary key for a relation
dbplus_ropen -- Open relation file local
dbplus_rquery -- Perform local (raw) AQL query
dbplus_rrename -- Rename a relation
dbplus_rsecindex --  Create a new secondary index for a relation
dbplus_runlink -- Remove relation from filesystem
dbplus_rzap -- Remove all tuples from relation
dbplus_savepos -- ???
dbplus_setindex -- ???
dbplus_setindexbynumber -- ???
dbplus_sql -- Perform SQL query
dbplus_tcl -- Execute TCL code on server side
dbplus_tremove -- Remove tuple and return new current tuple
dbplus_undo -- ???
dbplus_undoprepare -- ???
dbplus_unlockrel -- Give up write lock on relation
dbplus_unselect -- Remove a constraint from relation
dbplus_update -- Update specified tuple in relation
dbplus_xlockrel -- Request exclusive lock on relation
dbplus_xunlockrel -- Free exclusive lock on relation

dbplus_add

(4.1.0 - 4.2.3 only)

dbplus_add -- Add a tuple to a relation

Description

int dbplus_add ( resource relation, array tuple)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

This function will add a tuple to a relation. The tuple data is an array of attribute/value pairs to be inserted into the given relation. After successful execution the tuple array will contain the complete data of the newly created tuple, including all implicitly set domain fields like sequences.

The function will return zero (aka. DBPLUS_ERR_NOERR) 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.

dbplus_aql

(4.1.0 - 4.2.3 only)

dbplus_aql -- Perform AQL query

Description

resource dbplus_aql ( string query [, string server [, string dbpath]])

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

dbplus_aql() will execute an AQL query on the given server and dbpath.

On success it will return a relation handle. The result data may be fetched from this relation by calling dbplus_next() and dbplus_current(). Other relation access functions will not work on a result relation.

Further information on the AQL A... Query Language is provided in the original db++ manual.

dbplus_chdir

(4.1.0 - 4.2.3 only)

dbplus_chdir -- Get/Set database virtual current directory

Description

string dbplus_chdir ( [string newdir])

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

dbplus_chdir() will change the virtual current directory where relation files will be looked for by dbplus_open(). dbplus_chdir() will return the absolute path of the current directory. Calling dbplus_chdir() without giving any newdir may be used to query the current working directory.

dbplus_close

(4.1.0 - 4.2.3 only)

dbplus_close -- Close a relation

Description

int dbplus_close ( resource relation)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Calling dbplus_close() will close a relation previously opened by dbplus_open().

dbplus_curr

(4.1.0 - 4.2.3 only)

dbplus_curr -- Get current tuple from relation

Description

int dbplus_curr ( resource relation, array tuple)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

dbplus_curr() will read the data for the current tuple for the given relation and will 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 dbplus_errcode() or the introduction to this chapter for more information on db++ error codes.

See also dbplus_first(), dbplus_prev(), dbplus_next(), and dbplus_last().

dbplus_errcode

(4.1.0 - 4.2.3 only)

dbplus_errcode --  Get error string for given errorcode or last error

Description

string dbplus_errcode ( int errno)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

dbplus_errcode() returns a cleartext error string for the error code passed as errno of for the result code of the last db++ operation if no parameter is given.

dbplus_errno

(4.1.0 - 4.2.3 only)

dbplus_errno -- Get error code for last operation

Description

int dbplus_errno ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

dbplus_errno() will return the error code returned by the last db++ operation.

See also dbplus_errcode().

dbplus_find

(4.1.0 - 4.2.3 only)

dbplus_find -- Set a constraint on a relation

Description

int dbplus_find ( resource relation, array constraints, mixed tuple)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

dbplus_find() will place a constraint on the given relation. Further calls to functions like dbplus_curr() or dbplus_next() will only return tuples matching the given constraints.

Constraints are triplets of strings containing of a domain name, a comparison operator and a comparison value. The constraints parameter array may consist of a collection of string arrays, each of which contains a domain, an operator and a value, or of a single string array containing a multiple of three elements.

The comparison operator may be one of the following strings: '==', '>', '>=', '<', '<=', '!=', '~' for a regular expression match and 'BAND' or 'BOR' for bitwise operations.

See also dbplus_unselect().

dbplus_first

(4.1.0 - 4.2.3 only)

dbplus_first -- Get first tuple from relation

Description

int dbplus_first ( resource relation, array tuple)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

dbplus_curr() will read the data for the first tuple for the given relation, make it the current tuple and 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 dbplus_errcode() or the introduction to this chapter for more information on db++ error codes.

See also dbplus_curr(), dbplus_prev(), dbplus_next(), and dbplus_last().

dbplus_flush

(4.1.0 - 4.2.3 only)

dbplus_flush -- Flush all changes made on a relation

Description

int dbplus_flush ( resource relation)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

dbplus_flush() will write all changes applied to relation since the last flush to disk.

The function will return zero (aka. DBPLUS_ERR_NOERR) 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.

dbplus_freealllocks

(4.1.0 - 4.2.3 only)

dbplus_freealllocks -- Free all locks held by this client

Description

int dbplus_freealllocks ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

dbplus_freeaalllocks() will free all tuple locks held by this client.

See also dbplus_getlock(), dbplus_freelock(), and dbplus_freerlocks().

dbplus_freelock

(4.1.0 - 4.2.3 only)

dbplus_freelock -- Release write lock on tuple

Description

int dbplus_freelock ( resource relation, string tname)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

dbplus_freelock() will release a write lock on the given tuple previously obtained by dbplus_getlock().

See also dbplus_getlock(), dbplus_freerlocks(), and dbplus_freealllocks().

dbplus_freerlocks

(4.1.0 - 4.2.3 only)

dbplus_freerlocks -- Free all tuple locks on given relation

Description

int dbplus_freerlocks ( resource relation)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

dbplus_freerlocks() will free all tuple locks held on the given relation.

See also dbplus_getlock(), dbplus_freelock(), and dbplus_freealllocks().

dbplus_getlock

(4.1.0 - 4.2.3 only)

dbplus_getlock -- Get a write lock on a tuple

Description

int dbplus_getlock ( resource relation, string tname)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

dbplus_getlock() will request a write lock on the specified tuple. It will return zero on success or a non-zero error code, especially DBPLUS_ERR_WLOCKED, on failure.

See also dbplus_freelock(), dbplus_freerlocks(), and dbplus_freealllocks().

dbplus_getunique

(4.1.0 - 4.2.3 only)

dbplus_getunique -- Get a id number unique to a relation

Description

int dbplus_getunique ( resource relation, int uniqueid)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

dbplus_getunique() will obtain a number guaranteed to be unique for the given relation and will pass it back in the variable given as uniqueid.

The function will return zero (aka. DBPLUS_ERR_NOERR) 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.

dbplus_info

(4.1.0 - 4.2.3 only)

dbplus_info -- ???

Description

int dbplus_info ( resource relation, string key, array )

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Not implemented yet.

dbplus_last

(4.1.0 - 4.2.3 only)

dbplus_last -- Get last tuple from relation

Description

int dbplus_last ( resource relation, array tuple)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

dbplus_curr() will read the data for the last tuple for the given relation, make it the current tuple and 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 dbplus_errcode() or the introduction to this chapter for more information on db++ error codes.

See also dbplus_first(), dbplus_curr(), dbplus_prev(), and dbplus_next().

dbplus_lockrel

(no version information, might be only in CVS)

dbplus_lockrel -- Request write lock on relation

Description

int dbplus_lockrel ( resource relation)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

dbplus_lockrel() will request a write lock on the given relation. Other clients may still query the relation, but can't alter it while it is locked.

dbplus_next

(4.1.0 - 4.2.3 only)

dbplus_next -- Get next tuple from relation

Description

int dbplus_next ( resource relation, array )

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

dbplus_curr() will read the data for the next tuple for 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) 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.

See also dbplus_first(), dbplus_curr(), dbplus_prev(), and dbplus_last().

dbplus_open

(4.1.0 - 4.2.3 only)

dbplus_open -- Open relation file

Description

resource dbplus_open ( string name)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

The relation file name will be opened. name can be either a file name or a relative or absolute path name. This will be mapped in any case to an absolute relation file path on a specific host machine and server.

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 value, the actual error code may be asked for by calling dbplus_errno().

dbplus_prev

(4.1.0 - 4.2.3 only)

dbplus_prev -- Get previous tuple from relation

Description

int dbplus_prev ( resource relation, array tuple)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

dbplus_curr() will read the data for the next tuple for 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) 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.

See also dbplus_first(), dbplus_curr(), dbplus_next(), and dbplus_last().

dbplus_rchperm

(4.1.0 - 4.2.3 only)

dbplus_rchperm -- Change relation permissions

Description

int dbplus_rchperm ( resource relation, int mask, string user, string group)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

dbplus_rchperm() will change access permissions as specified by mask, user and group. The values for these are operating system specific.

dbplus_rcreate

(4.1.0 - 4.2.3 only)

dbplus_rcreate -- Creates a new DB++ relation

Description

resource dbplus_rcreate ( string name, mixed domlist [, boolean overwrite])

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

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 overwrite is set to TRUE.

domlist should contain the domain specification for the new relation within an array of domain description strings. ( dbplus_rcreate() will also accept a string with space delimited domain description strings, but it is recommended to use an array). A domain description string consists of a domain name unique to this relation, a slash and a type specification character. See the db++ documentation, especially the dbcreate(1) manpage, for a description of available type specifiers and their meanings.

dbplus_rcrtexact

(4.1.0 - 4.2.3 only)

dbplus_rcrtexact -- Creates an exact but empty copy of a relation including indices

Description

resource dbplus_rcrtexact ( string name, resource relation, boolean overwrite)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

dbplus_rcrtexact() will create an exact but empty copy of the given relation under a new name. An existing relation by the same name will only be overwritten if overwrite is TRUE and no other process is currently using the relation.

dbplus_rcrtlike

(4.1.0 - 4.2.3 only)

dbplus_rcrtlike -- Creates an empty copy of a relation with default indices

Description

resource dbplus_rcrtlike ( string name, resource relation, int flag)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

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 be overwritten if overwrite is TRUE and no other process is currently using the relation.

dbplus_resolve

(4.1.0 - 4.2.3 only)

dbplus_resolve -- Resolve host information for relation

Description

int dbplus_resolve ( string relation_name)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

dbplus_resolve() will try to resolve the given 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 under the keys 'sid', 'host' and 'host_path' or FALSE on error.

See also dbplus_tcl().

dbplus_restorepos

(4.1.0 - 4.2.3 only)

dbplus_restorepos -- ???

Description

int dbplus_restorepos ( resource relation, array tuple)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Not implemented yet.

dbplus_rkeys

(4.1.0 - 4.2.3 only)

dbplus_rkeys -- Specify new primary key for a relation

Description

resource dbplus_rkeys ( resource relation, mixed domlist)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

dbplus_rkeys() will replace the current primary key for relation with the combination of domains specified by domlist.

domlist may be passed as a single domain name string or as an array of domain names.

dbplus_ropen

(4.1.0 - 4.2.3 only)

dbplus_ropen -- Open relation file local

Description

resource dbplus_ropen ( string name)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

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_next() may be applied to the returned relation.

dbplus_rquery

(4.1.0 - 4.2.3 only)

dbplus_rquery -- Perform local (raw) AQL query

Description

int dbplus_rquery ( string query, string dbpath)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

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 will work on local data only.

dbplus_rrename

(4.1.0 - 4.2.3 only)

dbplus_rrename -- Rename a relation

Description

int dbplus_rrename ( resource relation, string name)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

dbplus_rrename() will change the name of relation to name.

dbplus_rsecindex

(4.1.0 - 4.2.3 only)

dbplus_rsecindex --  Create a new secondary index for a relation

Description

resource dbplus_rsecindex ( resource relation, mixed domlist, int type)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

dbplus_rsecindex() will create a new secondary index for relation with consists of the domains specified by domlist and is of type type

domlist may be passed as a single domain name string or as an array of domain names.

dbplus_runlink

(4.1.0 - 4.2.3 only)

dbplus_runlink -- Remove relation from filesystem

Description

int dbplus_runlink ( resource relation)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

dbplus_unlink() will close and remove the relation.

dbplus_rzap

(4.1.0 - 4.2.3 only)

dbplus_rzap -- Remove all tuples from relation

Description

int dbplus_rzap ( resource relation)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

dbplus_rzap() will remove all tuples from relation.

dbplus_savepos

(4.1.0 - 4.2.3 only)

dbplus_savepos -- ???

Description

int dbplus_savepos ( resource relation)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Not implemented yet.

dbplus_setindex

(4.1.0 - 4.2.3 only)

dbplus_setindex -- ???

Description

int dbplus_setindex ( resource relation, string idx_name)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Not implemented yet.

dbplus_setindexbynumber

(4.1.0 - 4.2.3 only)

dbplus_setindexbynumber -- ???

Description

int dbplus_setindexbynumber ( resource relation, int idx_number)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Not implemented yet.

dbplus_sql

(4.1.0 - 4.2.3 only)

dbplus_sql -- Perform SQL query

Description

resource dbplus_sql ( string query, string server, string dbpath)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Not implemented yet.

dbplus_tcl

(4.1.0 - 4.2.3 only)

dbplus_tcl -- Execute TCL code on server side

Description

int dbplus_tcl ( int sid, string script)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

A db++ server will prepare a TCL interpreter for each client connection. This interpreter will enable the server 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 transfers and context switches.

dbplus_tcl() needs to pass the client connection id the TCL script code should be executed by. dbplus_resolve() will provide this connection id. The function will return whatever the TCL code returns or a TCL error message if the TCL code fails.

See also dbplus_resolve().

dbplus_tremove

(4.1.0 - 4.2.3 only)

dbplus_tremove -- Remove tuple and return new current tuple

Description

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

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

dbplus_tremove() removes tuple from relation if it perfectly matches a tuple within the relation. current, if given, will contain the data of the new current tuple after calling dbplus_tremove().

dbplus_undo

(4.1.0 - 4.2.3 only)

dbplus_undo -- ???

Description

int dbplus_undo ( resource relation)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Not implemented yet.

dbplus_undoprepare

(4.1.0 - 4.2.3 only)

dbplus_undoprepare -- ???

Description

int dbplus_undoprepare ( resource relation)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Not implemented yet.

dbplus_unlockrel

(4.1.0 - 4.2.3 only)

dbplus_unlockrel -- Give up write lock on relation

Description

int dbplus_unlockrel ( resource relation)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

dbplus_unlockrel() will release a write lock previously obtained by dbplus_lockrel().

dbplus_unselect

(4.1.0 - 4.2.3 only)

dbplus_unselect -- Remove a constraint from relation

Description

int dbplus_unselect ( resource relation)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Calling dbplus_unselect() will remove a constraint previously set by dbplus_find() on relation.

dbplus_update

(4.1.0 - 4.2.3 only)

dbplus_update -- Update specified tuple in relation

Description

int dbplus_update ( resource relation, array old, array new)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

dbplus_update() replaces the tuple given by old with the data from new if and only if old completely matches a tuple within relation.

dbplus_xlockrel

(4.1.0 - 4.2.3 only)

dbplus_xlockrel -- Request exclusive lock on relation

Description

int dbplus_xlockrel ( resource relation)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

dbplus_xlockrel() will request an exclusive lock on relation preventing even read access from other clients.

See also dbplus_xunlockrel().

dbplus_xunlockrel

(4.1.0 - 4.2.3 only)

dbplus_xunlockrel -- Free exclusive lock on relation

Description

int dbplus_xunlockrel ( resource relation)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

dbplus_xunlockrel() will release an exclusive lock on relation previously obtained by dbplus_xlockrel().

XXIII. Direct IO functions

Introdução

PHP supports the direct io functions as described in the Posix Standard (Section 6) for performing I/O functions at a lower level than the C-Language stream I/O functions (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 functions are more than adequate.

Nota: This extension is not available on Windows platforms.


Requisitos

Nenhuma biblioteca externa é necessária para compilar esta extensão.


Instalação

To get these functions to work, you have to configure PHP with --enable-dio.


Configuração durante execução

Esta extenção não define nenhum parâmetro de configuração no php.ini.


Tipos Resource

One resource type is defined by this extension: a file descriptor returnded by dio_open().


Constantes Predefinidas

Esta extensão não possui nenhuma constante.

Índice
dio_close -- Closes the file descriptor given by fd
dio_fcntl -- Performs a c library fcntl on fd
dio_open --  Opens a new filename with specified permissions of flags and creation permissions of mode
dio_read --  Reads n bytes from fd and returns them, if n is not specified, reads 1k block
dio_seek -- Seeks to pos on fd from whence
dio_stat --  Gets stat information about the file descriptor fd
dio_tcsetattr --  Sets terminal attributes and baud rate for a serial port
dio_truncate --  Truncates file descriptor fd to offset bytes
dio_write --  Writes data to fd with optional truncation at length

dio_close

(PHP 4 >= 4.2.0)

dio_close -- Closes the file descriptor given by fd

Description

void dio_close ( resource fd)

The function dio_close() closes the file descriptor resource.

dio_fcntl

(PHP 4 >= 4.2.0)

dio_fcntl -- Performs a c library fcntl on fd

Description

mixed dio_fcntl ( resource fd, int cmd [, mixed arg])

The dio_fcntl() function performs the operation specified by cmd on the file descriptor fd. Some commands require additional arguments args to be supplied.

arg is an associative array, when cmd is F_SETLK or F_SETLLW, with the following keys:

  • "start" - offset where lock begins

  • "length" - size of locked area. zero means to end of file

  • "wenth" - Where l_start is relative to: can be SEEK_SET, SEEK_END and SEEK_CUR

  • "type" - type of lock: can be F_RDLCK (read lock), F_WRLCK (write lock) or F_UNLCK (unlock)

cmd can be one of the following operations:

  • F_SETLK - Lock is set or cleared. If the lock is held by someone else dio_fcntl() returns -1.

  • F_SETLKW - like F_SETLK, but in case the lock is held by someone else, dio_fcntl() waits until the lock is released.

  • F_GETLK - dio_fcntl() returns an associative array (as described above) if someone else prevents lock. If there is no obstruction key "type" will set to F_UNLCK.

  • F_DUPFD - finds the lowest numbered available file descriptor greater or equal than arg and returns them.

  • F_SETFL - Sets the file descriptors flags to the value specified by arg, Which can be O_APPEND,O_NONBLOCK or O_ASYNC . To use O_ASYNC you will need to use the pcntl extension.

dio_open

(PHP 4 >= 4.2.0)

dio_open --  Opens a new filename with specified permissions of flags and creation permissions of mode

Description

resource dio_open ( string filename, int flags [, int mode])

dio_open() opens a file and returns a new file descriptor for it, or FALSE if any error occurred. If flags is O_CREAT, optional third parameter mode will set the mode of the file (creation permissions). The flags parameter can be one of the following options:

  • O_RDONLY - opens the file for read access

  • O_WRONLY - opens the file for write access

  • O_RDWR - opens the file for both reading and writing

The flags parameter can also include any combination of the following flags:

  • O_CREAT - creates the file, if it doesn't already exist

  • O_EXCL - if both, O_CREAT and O_EXCL are set, dio_open() fails, if file already exists

  • O_TRUNC - if file exists, and its opened for write access, file will be truncated to zero length.

  • O_APPEND - write operations write data at the end of file

  • O_NONBLOCK - sets non blocking mode

dio_read

(PHP 4 >= 4.2.0)

dio_read --  Reads n bytes from fd and returns them, if n is not specified, reads 1k block

Description

string dio_read ( resource fd [, int n])

The function dio_read() reads and returns n bytes from file with descriptor resource. If n is not specified, dio_read() reads 1K sized block and returns them.

dio_seek

(PHP 4 >= 4.2.0)

dio_seek -- Seeks to pos on fd from whence

Description

int dio_seek ( resource fd, int pos, int whence)

The function dio_seek() is used to change the file position of the file with descriptor resource. The parameter whence specifies how the position pos should be interpreted:

  • SEEK_SET - specifies that pos is specified from the beginning of the file

  • SEEK_CUR - Specifies that pos is a count of characters from the current file position. This count may be positive or negative

  • SEEK_END - Specifies that pos is a count of characters from the end of the file. A negative 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 position past the current end, and actually write data, you will extend the file with zeros up to that position

dio_stat

(PHP 4 >= 4.2.0)

dio_stat --  Gets stat information about the file descriptor fd

Description

array dio_stat ( resource fd)

Function dio_stat() returns information about the file with file descriptor fd. dio_stat() returns an associative array with the following keys:

  • "device" - device

  • "inode" - inode

  • "mode" - mode

  • "nlink" - number of hard links

  • "uid" - user id

  • "gid" - group id

  • "device_type" - device type (if inode device)

  • "size" - total size in bytes

  • "blocksize" - blocksize

  • "blocks" - number of blocks allocated

  • "atime" - time of last access

  • "mtime" - time of last modification

  • "ctime" - time of last change

On error dio_stat() returns NULL.

dio_tcsetattr

(PHP 4 >= 4.3.0)

dio_tcsetattr --  Sets terminal attributes and baud rate for a serial port

Description

dio_tcsetattr ( resource fd, array options)

The function dio_tcsetattr() sets the terminal attributes and baud rate of the open resource. The currently available options are

  • 'baud' - baud rate of the port - can be 38400,19200,9600,4800,2400,1800,1200,600,300,200,150,134,110,75 or 50, default value is 9600

  • 'bits' - data bits - can be 8,7,6 or 5 default value is 8

  • 'stop' - stop bits - can be 1 or 2 default value is 1

  • 'parity' - can be 0,1 or 2 default value is 0

Exemplo 1. Setting the baud rate on a serial port

<?php

$fd = dio_open('/dev/ttyS0', O_RDWR | O_NOCTTY | O_NONBLOCK);

dio_fcntl($fd,F_SETFL, O_SYNC );

dio_tcsetattr($fd, array(
  'baud' => 9600,
  'bits' => 8,
  'stop'  =>1,
  'parity' => 0
)); 

while (1) {

  $data = dio_read($fd,256);

  if ($data) {
      echo $data;
  }
} 

?>

Nota: This function was introduced in PHP 4.3.0.

dio_truncate

(PHP 4 >= 4.2.0)

dio_truncate --  Truncates file descriptor fd to offset bytes

Description

bool dio_truncate ( resource fd, int offset)

Function dio_truncate() causes the file referenced by fd to be truncated to at most offset bytes in size. If the file previously was larger than this size, the extra data is lost. If the file previously was shorter, it is unspecified whether the file is left unchanged or is extended. In the latter case the extended part reads as zero bytes. Returns 0 on success, otherwise -1.

dio_write

(PHP 4 >= 4.2.0)

dio_write --  Writes data to fd with optional truncation at length

Description

int dio_write ( resource fd, string data [, int len])

The function dio_write() writes up to len bytes from data to file fd. If len is not specified, dio_write() writes all data to the specified file. dio_write() returns the number of bytes written to fd.

XXIV. Diretórios

Introdução


Requisitos

Nenhuma biblioteca externa é necessária para compilar esta extensão.


Instalação

Não há nenhuma instalação nescessária para utilizar estas funções, elas fazem parte do núcleo do PHP.


Configuração durante execução

Esta extenção não define nenhum parâmetro de configuração no php.ini.


Tipos Resource


Constantes Predefinidas

Esta extensão não possui nenhuma constante.


Veja Também

Para funções relacionadas como dirname(), is_dir(), mkdir() e rmdir(), veja a seção Filesystem.

Índice
chdir -- mudar de diretório
chroot -- mudar o diretório raiz (root)
dir -- classe diretório
closedir -- fechar o handle do diretório
getcwd -- obtem o diretório atual
opendir -- abrir o handle do diretório
readdir -- ler os campos do manipulador do diretório
rewinddir -- voltar (rewind) o handle de diretório

chdir

(PHP 3, PHP 4 )

chdir -- mudar de diretório

Descrição

bool chdir ( string diretorio)

Muda o diretório atual do PHP para diretorio. Retorna FALSE se não for possível mudar de diretório ou TRUE em sucesso.

Veja também: getcwd().

chroot

(PHP 4 >= 4.0.5)

chroot -- mudar o diretório raiz (root)

Descrição

bool chroot ( string diretorio)

Muda o diretório raiz (root) do processo atual para o diretorio. Retorna FALSE se não for possível mudar o diretório raiz, retorna TRUE caso contrário.

Nota: Não é sensato usar esta função quando rodando em um ambiente de um webserver, porque não é possível reiniciar o diretório raiz (root) para / novamente no fim do pedido (request). Esta função somente irá funcionar desta forma quando rodando num ambiente CGI.

Nota: esta função não é implementada na plataforma Windows

dir

dir -- classe diretório

Descrição

 class dir {

  dir(string directory);
  string path;
  resource handle;

  string read();
  void rewind();
  void close();
}

Um mecanismo pseudo-orientado a objeto para ler um diretório. O parâmetro dado directory é aberto. Duas propriedades são disponíveis uma vez que o diretório foi aberto: A propriedade handle pode ser usada com outras funções de diretório como readdir(), rewinddir() e closedir(). A propriedade path é configurada para o caminho que o diretório foi aberto. Três métodos disponibilizados são: read, rewind e close.

Repare nos detalhes de como o valor retornado de dir() é verificado no exemplo abaixo. Nós explicitamente testamos se valor de retorno é idêntico (igual e do mesmo tipo que --- veja operadores de comparação para mais detalhes) a FALSE, desde que, de outra forma, qualquer entrada de diretório que seja avaliada para FALSE fará parar o loop.

Exemplo 1. Exemplo dir()

$d = dir("/etc");
echo "Manipulador: ".$d->handle."<br>\n";
echo "Caminho: ".$d->path."<br>\n";
while (false !== ($entry = $d->read())) {
    echo $entry."<br>\n";
}
$d->close();

Nota: A ordem em que os diretórios são retornadas pelo método é dependente do sistema.

Nota: Este módulo define a classe interna Directory, significando que você não será capaz de criar uma classe sua com esse nome. Para uma lista completa das classes predefinidas no PHP, veja em Classes Predefinidas.

closedir

(PHP 3, PHP 4 )

closedir -- fechar o handle do diretório

Descrição

void closedir ( resource dir_handle)

Fecha o stream do diretório indicado por dir_handle. O stream deve ter sido previamente aberto por opendir().

getcwd

(PHP 4 )

getcwd -- obtem o diretório atual

Descrição

string getcwd ( void)

Retorna o diretório atual.

Veja também: chdir().

opendir

(PHP 3, PHP 4 )

opendir -- abrir o handle do diretório

Descrição

resource opendir ( string path)

Retorna um handle de diretório para ser usado em chamadas subsequentes a closedir(), readdir(), e rewinddir().

Se o path não é um diretório válido ou o diretório não pode ser aberto devido a restrições das permissões ou erros no filesystem, opendir() retorna FALSE e gera um erro do PHP. Você pode suprimir o erro na saída de opendir() no seu script ao se inserir `@' na frente do nome da função.

Exemplo 1. exemplo de opendir()

<?php

if ($dir = @opendir("/tmp")) {
  while (($file = readdir($dir)) !== false) {
    echo "$file\n";
  }  
  closedir($dir);
}

?>

readdir

(PHP 3, PHP 4 )

readdir -- ler os campos do manipulador do diretório

Descrição

string readdir ( resource dir_handle)

Retorna o nome de arquivo do próximo arquivo do diretório. Os nomes de arquivos ão retornados na ordem informada pelo sistema de arquivos.

Verifique cuidadosamente o estilo de checagem dos valores retornados por readdir() nos exemplos abaixo. Nós explicitamente testamos se o valor retornado é idêntico a (igual e do mesmo tipo que FALSE --- veja Operadores de Comparação para maiores detalhes). De outra forma, qualquer entrada de diretório que seja avaliada para FALSE irá parar o loop (por exemplo, um diretório nomeado "0").

Exemplo 1. Lista todos os arquivos em um diretório

// Note que !== não existia antes do PHP 4.0.0-RC2
<?php
if ($handle = opendir('/path/to/files')) {
    echo "Manipulador de diretório: $handle\n";
    echo "Arquivos:\n";

    /* Esta é a forma correta de varrer o diretório */
    while (false !== ($file = readdir($handle))) {
        echo "$file\n";
    }

    /* Esta é a forma INCORRETA de varrer o diretório */
    while ($file = readdir($handle)) {
        echo "$file\n";
    }

    closedir($handle);
}
?>

Note que readdir() irá retornar o . e .. . Se você não quer estes simplesmente os retire:

Exemplo 2. Listar todos os arquivos no diretório atual e retirar . e ..

<?php 
if ($handle = opendir('.')) {
    while (false !== ($file = readdir($handle))) { 
        if ($file != "." && $file != "..") { 
            echo "$file\n"; 
        } 
    }
    closedir($handle); 
}
?>

Veja também is_dir().

rewinddir

(PHP 3, PHP 4 )

rewinddir -- voltar (rewind) o handle de diretório

Descrição

void rewinddir ( resource dir_handle)

Reinicia o stream do diretório indicado por dir_handle para o início do diretório.

XXV. DOM XML functions

Introdução

Atenção

Este módulo é EXPERIMENTAL. Isso quer dizer que o comportamento neste módulo --- incluindo suas funções e seus nomes, e TUDO mais que está documentado sobre esse módulo --- poderá mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use este módulo por sua própria conta e risco.

The DOM XML extension has been overhauled in PHP 4.3.0 to better comply with the DOM standard. The extension still contains many old functions, but they should no longer be used. In particular, functions that are not object-oriented should be avoided.

The extension allows you to operate on an XML document with the DOM API. It also provides a function domxml_xmltree() to turn the complete XML document into a tree of PHP objects. Currently, this tree should be considered read-only — you can modify it, but this would not make any sense since DomDocument_dump_mem() cannot be applied to it. Therefore, if you want to read an XML file and write a modified version, use DomDocument_create_element(), DomDocument_create_text_node(), set_attribute(), etc. and finally the DomDocument_dump_mem() function.


Requisitos

This extension makes use of the GNOME XML library. Download and install this library. You will need at least libxml-2.4.14. To use DOM XSLT features you can use the libxslt library and EXSLT enhancements from http://www.exslt.org/. Download and install these libraries if you plan to use (enhanced> XSLT features. You will need at least libxslt-1.0.18.


Instalação

This extension is only available if PHP was configured with --with-dom[=DIR]. Add --with-dom-xslt[=DIR] to include DOM XSLT support. DIR is the libxslt install directory. Add --with-dom-exslt[=DIR] to include DOM EXSLT support, where DIR is the libexslt install directory.

Note to Win32 Users: In order to enable this module on a Windows environment, you must copy libxml2.dll from the DLL folder of the PHP/Win32 binary package to the SYSTEM32 folder of your windows machine. (Ex: C:\WINNT\SYSTEM32 or C:\WINDOWS\SYSTEM32)


Deprecated functions

There are quite a few functions that do not fit into the DOM standard and should no longer be used. These functions are listed in the following table. The function DomNode_append_child() has changed its behaviour. It now adds a child and not a sibling. If this breaks your application, use the non-DOM function DomNode_append_sibling().

Tabela 1. Deprecated functions and their replacements

Old function New function
xmldoc domxml_open_mem()
xmldocfile domxml_open_file()
domxml_new_xmldoc domxml_new_doc()
domxml_dump_mem DomDocument_dump_mem()
domxml_dump_mem_file DomDocument_dump_file()
DomDocument_dump_mem_file DomDocument_dump_file()
DomDocument_add_root DomDocument_create_element() followed by DomNode_append_child()
DomDocument_dtd DomDocument_doctype()
DomDocument_root DomDocument_document_element()
DomDocument_children DomNode_child_nodes()
DomDocument_imported_node No replacement.
DomNode_add_child Create a new node with e.g. DomDocument_create_element() und add it with DomNode_append_child().
DomNode_children DomNode_child_nodes()
DomNode_parent DomNode_parent_node()
DomNode_new_child Create a new node with e.g. DomDocument_create_element() and add it with DomNode_append_child().
DomNode_set_content Create a new node with e.g. DomDocument_create_text_node() and add it with DomNode_append_child().
DomNode_get_content Content is just a text node and can be accessed with DomNode_child_nodes().
DomNode_set_content Content is just a text node and can be added with DomNode_append_child().


Constantes Predefinidas

As contantes abaixo são definidas por esta extensão e somente estarão disponíveis quando a extensão foi compilada com o PHP ou carregada dinamicamente durante a execução.

Tabela 2. XML constants

Constant Value Description
XML_ELEMENT_NODE (integer) 1 Node is an element
XML_ATTRIBUTE_NODE (integer) 2 Node is an attribute
XML_TEXT_NODE (integer) 3 Node is a piece of text
XML_CDATA_SECTION_NODE (integer) 4  
XML_ENTITY_REF_NODE (integer) 5  
XML_ENTITY_NODE (integer) 6 Node is an entity like &nbsp;
XML_PI_NODE (integer) 7 Node is a processing instruction
XML_COMMENT_NODE (integer) 8 Node is a comment
XML_DOCUMENT_NODE (integer) 9 Node is a document
XML_DOCUMENT_TYPE_NODE (integer) 10  
XML_DOCUMENT_FRAG_NODE (integer) 11  
XML_NOTATION_NODE (integer) 12  
XML_GLOBAL_NAMESPACE (integer) 1  
XML_LOCAL_NAMESPACE (integer) 2  
XML_HTML_DOCUMENT_NODE (integer)    
XML_DTD_NODE (integer)    
XML_ELEMENT_DECL_NODE (integer)    
XML_ATTRIBUTE_DECL_NODE (integer)    
XML_ENTITY_DECL_NODE (integer)    
XML_NAMESPACE_DECL_NODE (integer)    
XML_ATTRIBUTE_CDATA (integer)    
XML_ATTRIBUTE_ID (integer)    
XML_ATTRIBUTE_IDREF (integer)    
XML_ATTRIBUTE_IDREFS (integer)    
XML_ATTRIBUTE_ENTITY (integer)    
XML_ATTRIBUTE_NMTOKEN (integer)    
XML_ATTRIBUTE_NMTOKENS (integer)    
XML_ATTRIBUTE_ENUMERATION (integer)    
XML_ATTRIBUTE_NOTATION (integer)    
XPATH_UNDEFINED (integer)    
XPATH_NODESET (integer)    
XPATH_BOOLEAN (integer)    
XPATH_NUMBER (integer)    
XPATH_STRING (integer)    
XPATH_POINT (integer)    
XPATH_RANGE (integer)    
XPATH_LOCATIONSET (integer)    
XPATH_USERS (integer)    
XPATH_NUMBER (integer)    

Classes

The API of the module follows the DOM Level 2 standard as closely as possible. Consequently, the API is fully object-oriented. It is a good idea to have the DOM standard available when using this module. Though the API is object-oriented, there are many functions which can be called in a non-object-oriented way by passing the object to operate on as the first argument. These functions are mainly to retain compatibilty to older versions of the extension, and should not be used when creating new scripts.

This API differs from the official DOM API in two ways. First, all class attributes are implemented as functions with the same name. Secondly, the function names follow the PHP naming convention. This means that a DOM function lastChild() will be written as last_child().

This module defines a number of classes, which are listed — including their method — in the following tables. Classes with an equivalent in the DOM standard are named DOMxxx.

Tabela 3. List of classes

Class name Parent classes
DomAttribute DomNode
DomCData DomNode
DomComment DomCData : DomNode
DomDocument DomNode
DomDocumentType DomNode
DomElement DomNode
DomEntity DomNode
DomEntityReference DomNode
DomProcessingInstruction DomNode
DomText DomCData : DomNode
Parser Currently still called DomParser
XPathContext  

Tabela 4. DomDocument class (DomDocument : DomNode)

Method name Function name Remark
doctype DomDocument_doctype()  
document_elemnent DomDocument_document_element()  
create_element DomDocument_create_element()  
create_text_node DomDocument_create_text_node()  
create_comment DomDocument_create_comment()  
create_cdata_section DomDocument_create_cdata_section()  
create_processing_instruction DomDocument_create_processing_instruction()  
create_attribute DomDocument_create_attribute()  
create_entity_reference DomDocument_create_entity_reference()  
get_elements_by_tagname DomDocument_get_elements_by_tagname()  
get_element_by_id DomDocument_get_element_by_id()  
dump_mem DomDocument_dump_mem() not DOM standard
dump_file DomDocument_dump_file() not DOM standard
html_dump_mem DomDocument_html_dump_mem() not DOM standard
xpath_init xpath_init not DOM standard
xpath_new_context xpath_new_context not DOM standard
xptr_new_context xptr_new_context not DOM standard

Tabela 5. DomElement class (DomElement : DomNode)

Method name Function name Remark
tagname DomElement_tagname()  
get_attribute DomElement_get_attribute()  
set_attribute DomElement_set_attribute()  
remove_attribute DomElement_remove_attribute()  
get_attribute_node DomElement_get_attribute_node()  
get_elements_by_tagname DomElement_get_elements_by_tagname()  
has_attribute DomElement_has_attribute()  

Tabela 6. DomNode class

Method name Remark
DomNode_node_name()  
DomNode_node_value()  
DomNode_node_type()  
DomNode_last_child()  
DomNode_first_child()  
DomNode_child_nodes()  
DomNode_previous_sibling()  
DomNode_next_sibling()  
DomNode_parent_node()  
DomNode_owner_document()  
DomNode_insert_before()  
DomNode_append_child()  
DomNode_append_sibling() Not in DOM standard. This function emulates the former behaviour of DomNode_append_child().
DomNode_remove_child()  
DomNode_has_child_nodes()  
DomNode_has_attributes()  
DomNode_clone_node()  
DomNode_attributes()  
DomNode_unlink_node() Not in DOM standard
DomNode_replace_node() Not in DOM standard
DomNode_set_content() Not in DOM standard, deprecated
DomNode_get_content() Not in DOM standard, deprecated
DomNode_dump_node() Not in DOM standard
DomNode_is_blank_node() Not in DOM standard

Tabela 7. DomAttribute class (DomAttribute : DomNode)

Method name   Remark
name DomAttribute_name()  
value DomAttribute_value()  
specified DomAttribute_specified()  

Tabela 8. DomProcessingInstruction class (DomProcessingInstruction : DomNode)

Method name Function name Remark
target DomProcessingInstruction_target()  
data DomProcessingInstruction_data()  

Tabela 9. Parser class

Method name Function name Remark
add_chunk Parser_add_chunk()  
end Parser_end()  

Tabela 10. XPathContext class

Method name Function name Remark
eval XPathContext_eval()  
eval_expression XPathContext_eval_expression()  
register_ns XPathContext_register_ns()  

Tabela 11. DomDocumentType class (DomDocumentType : DomNode)

Method name Function name Remark
name DomDocumentType_name()  
entities DomDocumentType_entities()  
notations DomDocumentType_notations()  
public_id DomDocumentType_public_id()  
system_id DomDocumentType_system_id()  
internal_subset DomDocumentType_internal_subset()  

The classes DomDtd is derived from DomNode. DomComment is derived from DomCData.


Exemplos

Many examples in this reference require an XML string. Instead of repeating this string in every example, it will be put into a file which will be included by each example. This include file is shown in the following example section. Alternatively, you could create an XML document and read it with DomDocument_open_file().

Exemplo 1. Include file example.inc with XML string

<?php
$xmlstr = "<?xml version='1.0' standalone='yes'?>
<!DOCTYPE chapter SYSTEM '/share/sgml/Norman_Walsh/db3xml10/db3xml10.dtd'
[ <!ENTITY sp \"spanish\">
]>
<!-- lsfj  -->
<chapter language='en'><title language='en'>Title</title>
 <para language='ge'>
  &amp;sp;
  <!-- comment -->
  <informaltable ID='findme' language='&amp;sp;'>
   <tgroup cols='3'>
    <tbody>
     <row><entry>a1</entry><entry
morerows='1'>b1</entry><entry>c1</entry></row>
<row><entry>a2</entry><entry>c2</entry></row>
     <row><entry>a3</entry><entry>b3</entry><entry>c3</entry></row>
    </tbody>
   </tgroup>
  </informaltable>
 </para>
</chapter>";
?>

Índice
DomAttribute->name --  Returns name of attribute
DomAttribute->specified --  Checks if attribute is specified
DomAttribute->value --  Returns value of attribute
DomDocument->add_root [deprecated] --  Adds a root node
DomDocument->create_attribute -- Create new attribute
DomDocument->create_cdata_section -- Create new cdata node
DomDocument->create_comment -- Create new comment node
DomDocument->create_element_ns --  Create new element node with an associated namespace
DomDocument->create_element -- Create new element node
DomDocument->create_entity_reference -- 
DomDocument->create_processing_instruction -- Creates new PI node
DomDocument->create_text_node -- Create new text node
DomDocument->doctype --  Returns the document type
DomDocument->document_element --  Returns root element node
DomDocument->dump_file --  Dumps the internal XML tree back into a file
DomDocument->dump_mem --  Dumps the internal XML tree back into a string
DomDocument->get_element_by_id --  Searches for an element with a certain id
DomDocument->get_elements_by_tagname -- 
DomDocument->html_dump_mem --  Dumps the internal XML tree back into a string as HTML
DomDocument->xinclude --  Substitutes XIncludes in a DomDocument Object.
DomDocumentType->entities --  Returns list of entities
DomDocumentType->internal_subset --  Returns internal subset
DomDocumentType->name --  Returns name of document type
DomDocumentType->notations --  Returns list of notations
DomDocumentType->public_id --  Returns public id of document type
DomDocumentType->system_id --  Returns system id of document type
DomElement->get_attribute_node --  Returns value of attribute
DomElement->get_attribute --  Returns value of attribute
DomElement->get_elements_by_tagname --  Gets elements by tagname
DomElement->has_attribute --  Checks to see if attribute exists
DomElement->remove_attribute --  Removes attribute
DomElement->set_attribute --  Adds new attribute
DomElement->tagname --  Returns name of element
DomNode->add_namespace --  Adds a namespace declaration to a node.
DomNode->append_child --  Adds new child at the end of the children
DomNode->append_sibling --  Adds new sibling to a node
DomNode->attributes --  Returns list of attributes
DomNode->child_nodes --  Returns children of node
DomNode->clone_node --  Clones a node
DomNode->dump_node --  Dumps a single node
DomNode->first_child --  Returns first child of node
DomNode->get_content --  Gets content of node
DomNode->has_attributess --  Checks if node has attributes
DomNode->has_child_nodes --  Checks if node has children
DomNode->insert_before --  Inserts new node as child
DomNode->is_blank_node --  Checks if node is blank
DomNode->last_child --  Returns last child of node
DomNode->next_sibling --  Returns the next sibling of node
DomNode->node_name --  Returns name of node
DomNode->node_type --  Returns type of node
DomNode->node_value --  Returns value of a node
DomNode->owner_document --  Returns the document this node belongs to
DomNode->parent_node --  Returns the parent of the node
DomNode->prefix --  Returns name space prefix of node
DomNode->previous_sibling --  Returns the previous sibling of node
DomNode->remove_child --  Removes child from list of children
DomNode->replace_child --  Replaces a child
DomNode->replace_node --  Replaces node
DomNode->set_content --  Sets content of node
DomNode->set_name --  Sets name of node
DomNode->set_namespace --  Sets namespace of a node.
DomNode->unlink_node --  Deletes node
DomProcessingInstruction->data --  Returns data of pi node
DomProcessingInstruction->target --  Returns target of pi node
DomXsltStylesheet->process --  Applies the XSLT-Transformation on a DomDocument Object.
DomXsltStylesheet->result_dump_file --  Dumps the result from a XSLT-Transformation into a file
DomXsltStylesheet->result_dump_mem --  Dumps the result from a XSLT-Transformation back into a string
domxml_new_doc --  Creates new empty XML document
domxml_open_file -- Creates a DOM object from XML file
domxml_open_mem -- Creates a DOM object of an XML document
domxml_version --  Get XML library version
domxml_xmltree --  Creates a tree of PHP objects from an XML document
domxml_xslt_stylesheet_doc --  Creates a DomXsltStylesheet Object from a DomDocument Object.
domxml_xslt_stylesheet_file --  Creates a DomXsltStylesheet Object from a xsl document in a file.
domxml_xslt_stylesheet --  Creates a DomXsltStylesheet Object from a xml document in a string.
xpath_eval_expression --  Evaluates the XPath Location Path in the given string
xpath_eval --  Evaluates the XPath Location Path in the given string
xpath_new_context --  Creates new xpath context
xptr_eval --  Evaluate the XPtr Location Path in the given string
xptr_new_context --  Create new XPath Context

DomAttribute->name

(no version information, might be only in CVS)

DomAttribute->name --  Returns name of attribute

Description

bool DomAttribute->name ( void)

This function returns the name of the attribute.

See also domattribute_value().

DomAttribute->specified

(no version information, might be only in CVS)

DomAttribute->specified --  Checks if attribute is specified

Description

bool DomAttribute->specified ( void)

Check DOM standard for a detailed explanation.

DomAttribute->value

(no version information, might be only in CVS)

DomAttribute->value --  Returns value of attribute

Description

bool DomAttribute->value ( void)

This function returns the value of the attribute.

See also domattribute_name().

DomDocument->add_root [deprecated]

(no version information, might be only in CVS)

DomDocument->add_root [deprecated] --  Adds a root node

Description

resource DomDocument->add_root ( string name)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Adds a root element node to a dom document and returns the new node. The element name is given in the passed parameter.

Exemplo 1. Creating a simple HTML document header

<?php
$doc = domxml_new_doc("1.0");
$root = $doc->add_root("HTML");
$head = $root->new_child("HEAD", "");
$head->new_child("TITLE", "Hier der Titel");
echo htmlentities($doc->dump_mem());
?>

DomDocument->create_attribute

(no version information, might be only in CVS)

DomDocument->create_attribute -- Create new attribute

Description

object DomDocument->create_attribute ( string name, string value)

This function returns a new instance of class DomAttribute. The name of the attribute is the value of 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. 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_cdata_section(), domdocument_create_processing_instruction(), domdocument_create_entity_reference(), and domnode_insert_before().

DomDocument->create_cdata_section

(no version information, might be only in CVS)

DomDocument->create_cdata_section -- Create new cdata node

Description

string DomDocument->create_cdata_section ( string content)

This function returns a new instance of class DomCData. 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. 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_processing_instruction(), domdocument_create_entity_reference(), and domnode_insert_before().

DomDocument->create_comment

(no version information, might be only in CVS)

DomDocument->create_comment -- Create new comment node

Description

object DomDocument->create_comment ( string content)

This function returns a new instance of class DomComment. The content of the comment is the value of the passed parameter. This 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.

See also domnode_append_child(), domdocument_create_element(), domdocument_create_text(), domdocument_create_attribute(), domdocument_create_processing_instruction(), domdocument_create_entity_reference() and domnode_insert_before().

DomDocument->create_element_ns

(no version information, might be only in CVS)

DomDocument->create_element_ns --  Create new element node with an associated namespace

Description

object DomDocument->create_element_ns ( string uri, string name [, string prefix])

This function returns a new instance of class DomElement. The tag name of the element is the value of the passed parameter name. The URI of the namespace is the value of the passed parameter uri. If there is already a namespace declaration with the same uri in the root-node of the document, the prefix of this is 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 inserted with e.g. domnode_append_child().

The return value is FALSE if an error occured.

See also domdocument_create_element_ns(), domnode_add_namespace(), domnode_set_namespace(), domnode_append_child(), domdocument_create_text(), domdocument_create_comment(), domdocument_create_attribute(), domdocument_create_processing_instruction(), domdocument_create_entity_reference(), and domnode_insert_before().

DomDocument->create_element

(no version information, might be only in CVS)

DomDocument->create_element -- Create new element node

Description

object DomDocument->create_element ( string name)

This function returns a new instance of class DomElement. The tag name of the element is the value of the passed parameter. This 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.

See also domdocument_create_element_ns(), domnode_append_child(), domdocument_create_text(), domdocument_create_comment(), domdocument_create_attribute(), domdocument_create_processing_instruction(), domdocument_create_entity_reference(), and domnode_insert_before().

DomDocument->create_entity_reference

(no version information, might be only in CVS)

DomDocument->create_entity_reference -- 

Description

object DomDocument->create_entity_reference ( string content)

This function returns a new instance of class DomEntityReference. The content of the entity reference is the value of the passed parameter. This 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.

See also domnode_append_child(), domdocument_create_element(), domdocument_create_text(), domdocument_create_cdata_section(), domdocument_create_processing_instruction(), domdocument_create_attribute(), and domnode_insert_before().

DomDocument->create_processing_instruction

(no version information, might be only in CVS)

DomDocument->create_processing_instruction -- Creates new PI node

Description

string DomDocument->create_processing_instruction ( string content)

This function returns a new instance of class DomCData. The content of the pi is the value of the passed parameter. This 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.

See also domnode_append_child(), domdocument_create_element(), domdocument_create_text(), domdocument_create_cdata_section(), domdocument_create_attribute(), domdocument_create_entity_reference(), and domnode_insert_before().

DomDocument->create_text_node

(no version information, might be only in CVS)

DomDocument->create_text_node -- Create new text node

Description

object DomDocument->create_text_node ( string content)

This function returns a new instance of class DomText. The content of the text is the value of the passed parameter. This 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.

See also domnode_append_child(), domdocument_create_element(), domdocument_create_comment(), domdocument_create_text(), domdocument_create_attribute(), domdocument_create_processing_instruction(), domdocument_create_entity_reference(), and domnode_insert_before().

DomDocument->doctype

(no version information, might be only in CVS)

DomDocument->doctype --  Returns the document type

Description

object DomDocument->doctype ( void)

This function returns an object of class DomDocumentType. In versions of PHP before 4.3 this has been the class Dtd, but the DOM Standard does not know such a class.

See also the methods of class DomDocumentType.

DomDocument->document_element

(no version information, might be only in CVS)

DomDocument->document_element --  Returns root element node

Description

object DomDocument->document_element ( void)

This function returns the root element node of a document.

The following example returns just the element with name CHAPTER and prints it. The other node -- the comment -- is not returned.

Exemplo 1. Retrieving root element

<?php
include("example.inc");

if(!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$root = $dom->document_element();
print_r($root);
?>

DomDocument->dump_file

(no version information, might be only in CVS)

DomDocument->dump_file --  Dumps the internal XML tree back into a file

Description

string DomDocument->dump_file ( string filename [, bool compressionmode [, bool format]])

Creates an XML document from the dom representation. This function usually is called after building a new dom document from scratch as in the example below. The 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.

Exemplo 1. Creating a simple HTML document header

<?php
$doc = domxml_new_doc("1.0");
$root = $doc->create_element("HTML");
$root = $doc->append_child($root);
$head = $doc->create_element("HEAD");
$head = $root->append_child($head);
$title = $doc->create_element("TITLE");
$title = $head->append_child($title);
$text = $doc->create_text_node("This is the title");
$text = $title->append_child($text);
$doc->dump_file("/tmp/test.xml", false, true);
?>

See also domdocument_dump_mem() domdocument_html_dump_mem().

DomDocument->dump_mem

(no version information, might be only in CVS)

DomDocument->dump_mem --  Dumps the internal XML tree back into a string

Description

string DomDocument->dump_mem ( [bool format [, string encoding]])

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Creates an XML document from the dom representation. This function usually is called after building a new dom document from scratch as in the example below. The format specifies whether the output should be neatly formatted, or not.

Exemplo 1. Creating a simple HTML document header

<?php
$doc = domxml_new_doc("1.0");
$root = $doc->create_element("HTML");
$root = $doc->append_child($root);
$head = $doc->create_element("HEAD");
$head = $root->append_child($head);
$title = $doc->create_element("TITLE");
$title = $head->append_child($title);
$text = $doc->create_text_node("This is the title");
$text = $title->append_child($text);
echo "<PRE>";
echo htmlentities($doc->dump_mem(true));
echo "</PRE>";
?>

Nota: The first parameter was added in PHP 4.3.0.

See also domdocument_dump_file(), domdocument_html_dump_mem().

DomDocument->get_element_by_id

(no version information, might be only in CVS)

DomDocument->get_element_by_id --  Searches for an element with a certain id

Description

object DomDocument->get_element_by_id ( string id)

This function is similar to 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 attribute ID to be of type ID, though the current 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 attribute is of type id. This behaviour is likely to be fixed, so do not rely on the current behaviour.

See also domdocument_get_elements_by_tagname()

DomDocument->get_elements_by_tagname

(no version information, might be only in CVS)

DomDocument->get_elements_by_tagname -- 

Description

array DomDocument->get_elements_by_tagname ( string name)

See also domdocument_add_root()

DomDocument->html_dump_mem

(no version information, might be only in CVS)

DomDocument->html_dump_mem --  Dumps the internal XML tree back into a string as HTML

Description

string DomDocument->html_dump_mem ( void)

Creates an HTML document from the dom representation. This function usually is called after building a new dom document from scratch as in the example below.

Exemplo 1. Creating a simple HTML document header

<?php
$doc = domxml_new_doc("1.0");
$root = $doc->create_element("HTML");
$root = $doc->append_child($root);
$head = $doc->create_element("HEAD");
$head = $root->append_child($head);
$title = $doc->create_element("TITLE");
$title = $head->append_child($title);
$text = $doc->create_text_node("This is the title");
$text = $title->append_child($text);
echo "<PRE>";
echo htmlentities($doc->html_dump_mem());
echo "</PRE>";
?>

See also domdocument_dump_file(), domdocument_html_dump_mem().

DomDocument->xinclude

(no version information, might be only in CVS)

DomDocument->xinclude --  Substitutes XIncludes in a DomDocument Object.

Description

int DomDocument->xinclude ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

DomDocumentType->entities

(no version information, might be only in CVS)

DomDocumentType->entities --  Returns list of entities

Description

array DomDocumentType->entities ( void)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

DomDocumentType->internal_subset

(no version information, might be only in CVS)

DomDocumentType->internal_subset --  Returns internal subset

Description

bool DomDocumentType->internal_subset ( void)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

DomDocumentType->name

(no version information, might be only in CVS)

DomDocumentType->name --  Returns name of document type

Description

string DomDocumentType->name ( void)

This function returns the name of the document type.

DomDocumentType->notations

(no version information, might be only in CVS)

DomDocumentType->notations --  Returns list of notations

Description

array DomDocumentType->notations ( void)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

DomDocumentType->public_id

(no version information, might be only in CVS)

DomDocumentType->public_id --  Returns public id of document type

Description

string DomDocumentType->public_id ( void)

This function returns the public id of the document type.

The following example echos nothing.

Exemplo 1. Retrieving the public id

<?php
include("example.inc");

if(!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$doctype = $dom->doctype();
echo $doctype->public_id();
?>

DomDocumentType->system_id

(no version information, might be only in CVS)

DomDocumentType->system_id --  Returns system id of document type

Description

string DomDocumentType->system_id ( void)

Returns the system id of the document type.

The following example echos '/share/sgml/Norman_Walsh/db3xml10/db3xml10.dtd'.

Exemplo 1. Retrieving the system id

<?php
include("example.inc");

if(!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$doctype = $dom->doctype();
echo $doctype->system_id();
?>

DomElement->get_attribute_node

(no version information, might be only in CVS)

DomElement->get_attribute_node --  Returns value of attribute

Description

object DomElement->get_attribute_node ( object attr)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

DomElement->get_attribute

(no version information, might be only in CVS)

DomElement->get_attribute --  Returns value of attribute

Description

object DomElement->get_attribute ( string name)

Returns the attribute with name name of the current node.

(PHP >= 4.3 only) If no attribute with given name is found, an empty string is returned.

See also domelement_set_attribute()

DomElement->get_elements_by_tagname

(no version information, might be only in CVS)

DomElement->get_elements_by_tagname --  Gets elements by tagname

Description

bool DomElement->get_elements_by_tagname ( string name)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

DomElement->has_attribute

(no version information, might be only in CVS)

DomElement->has_attribute --  Checks to see if attribute exists

Description

bool DomElement->has_attribute ( string name)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

DomElement->remove_attribute

(no version information, might be only in CVS)

DomElement->remove_attribute --  Removes attribute

Description

bool DomElement->remove_attribute ( string name)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

DomElement->set_attribute

(no version information, might be only in CVS)

DomElement->set_attribute --  Adds new attribute

Description

bool DomElement->set_attribute ( string name, string value)

Sets an attribute with name name ot the given value. If the attribute does not exist, it will be created.

Exemplo 1. Setting an attribute

<?php
$doc = domxml_new_doc("1.0");
$node = $doc->create_element("para");
$newnode = $doc->append_child($node);
$newnode->set_attribute("align", "left");
?>

See also domelement_get_attribute()

DomElement->tagname

(no version information, might be only in CVS)

DomElement->tagname --  Returns name of element

Description

string DomElement->tagname ( void)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

DomNode->add_namespace

(no version information, might be only in CVS)

DomNode->add_namespace --  Adds a namespace declaration to a node.

Description

bool DomNode->add_namespace ( string uri, string prefix)

See also domdocument_create_element_ns(), domnode_set_namespace()

DomNode->append_child

(no version information, might be only in CVS)

DomNode->append_child --  Adds new child at the end of the children

Description

object DomNode->append_child ( object newnode)

This functions appends a child to an existing list of children or creates a new list of children. The child can be created with e.g. domdocument_create_element(), domdocument_create_text() etc. or simply by using any other node.

(PHP < 4.3) Before a new child is appended it is first duplicated. Therefore the new child is a completely new copy which can be modified without changing the node which was passed to this function. If the node passed has children itself, they will be duplicated as well, which makes it quite easy to duplicate large parts of a xml 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.

(PHP >= 4.3) The new child newnode is first unlinked from its existing context, if it already existed in a 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 xml document, use DomNode->clone_node() before appending.

The following example will add a new element node to a fresh document and sets the attribute "align" to "left".

Exemplo 1. Adding a child

<?php
$doc = domxml_new_doc("1.0");
$node = $doc->create_element("para");
$newnode = $doc->append_child($node);
$newnode->set_attribute("align", "left");
?>
The above example could also be written as the following:

Exemplo 2. Adding a child

<?php
$doc = domxml_new_doc("1.0");
$node = $doc->create_element("para");
$node->set_attribute("align", "left");
$newnode = $doc->append_child($node);
?>
A more comples example is the one below. It first searches for a certain element, duplicates it including its 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.

Exemplo 3. Adding a child

<?php
include("example.inc");

if(!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$elements = $dom->get_elements_by_tagname("informaltable");
print_r($elements);
$element = $elements[0];

$parent = $element->parent_node();
$newnode = $parent->append_child($element);
$children = $newnode->children();
$attr = $children[1]->set_attribute("align", "left");

echo "<PRE>";
$xmlfile = $dom->dump_mem();
echo htmlentities($xmlfile);
echo "</PRE>";
?>
The above example could also be done with domnode_insert_before() instead of domnode_append_child().

See also domnode_insert_before(), domnode_clone_node().

DomNode->append_sibling

(no version information, might be only in CVS)

DomNode->append_sibling --  Adds new sibling to a node

Description

object DomNode->append_sibling ( object newnode)

This functions appends a sibling to an existing node. The child can be created with e.g. domdocument_create_element(), domdocument_create_text() etc. or simply by using any other node.

Before a new sibling is added it is first duplicated. Therefore the new child is a completely new copy which can be modified without changing the node which was passed to this function. If the node passed has children itself, they will be duplicated as well, which makes it 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 the returned 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().

DomNode->attributes

(no version information, might be only in CVS)

DomNode->attributes --  Returns list of attributes

Description

array DomNode->attributes ( void)

This function only returns an array of attributes if the node is of type XML_ELEMENT_NODE.

(PHP >= 4.3 only) If no attributes are found, NULL is returned.

DomNode->child_nodes

(no version information, might be only in CVS)

DomNode->child_nodes --  Returns children of node

Description

array DomNode->child_nodes ( void)

Returns all children of the node.

See also domnode_next_sibling(), domnode_previous_sibling().

DomNode->clone_node

(no version information, might be only in CVS)

DomNode->clone_node --  Clones a node

Description

object DomNode->clone_node ( void)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

DomNode->dump_node

(no version information, might be only in CVS)

DomNode->dump_node --  Dumps a single node

Description

string DomNode->dump_node ( void)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

See also domdocument_dump_mem().

DomNode->first_child

(no version information, might be only in CVS)

DomNode->first_child --  Returns first child of node

Description

bool DomNode->first_child ( void)

Returns the first child of the node.

(PHP >= 4.3 only) If no first child is found, NULL is returned.

See also domnode_last_child(), domnode_next_sibling(), domnode_previous_sibling().

DomNode->get_content

(no version information, might be only in CVS)

DomNode->get_content --  Gets content of node

Description

string DomNode->get_content ( void)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

DomNode->has_attributess

(no version information, might be only in CVS)

DomNode->has_attributess --  Checks if node has attributes

Description

bool DomNode->has_attributes ( void)

This function checks if the node has attributes.

See also domnode_has_child_nodes().

DomNode->has_child_nodes

(no version information, might be only in CVS)

DomNode->has_child_nodes --  Checks if node has children

Description

bool DomNode->has_child_nodes ( void)

This function checks if the node has children.

See also domnode_child_nodes().

DomNode->insert_before

(no version information, might be only in CVS)

DomNode->insert_before --  Inserts new node as child

Description

object DomNode->insert_before ( object newnode, object refnode)

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 child you must use the returned node.

(PHP >= 4.3 only) If newnode already is part of a document, it will be first unlinked from its existing context. If refnode is NULL, then newnode will be inserted at the end of the list of children.

domnode_insert_before() is very similar to domnode_append_child() as the following example shows which does the same as the example at domnode_append_child().

Exemplo 1. Adding a child

include("example.inc");

if(!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$elements = $dom->get_elements_by_tagname("informaltable");
print_r($elements);
$element = $elements[0];

$newnode = $element->insert_before($element, $element);
$children = $newnode->children();
$attr = $children[1]->set_attribute("align", "left");

echo "<PRE>";
$xmlfile = $dom->dump_mem();
echo htmlentities($xmlfile);
echo "</PRE>";

See also domnode_append_child().

DomNode->is_blank_node

(no version information, might be only in CVS)

DomNode->is_blank_node --  Checks if node is blank

Description

bool DomNode->is_blank_node ( void)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

DomNode->last_child

(no version information, might be only in CVS)

DomNode->last_child --  Returns last child of node

Description

object DomNode->last_child ( void)

Returns the last child of the node.

(PHP >= 4.3 only) If no last child is found, NULL is returned.

See also domnode_first_child(), domnode_next_sibling(), domnode_previous_sibling().

DomNode->next_sibling

(no version information, might be only in CVS)

DomNode->next_sibling --  Returns the next sibling of node

Description

object DomNode->next_sibling ( void)

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 children of a node as shown in the example.

Exemplo 1. Iterate over children

<?php
include("example.inc");

if(!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$elements = $dom->get_elements_by_tagname("tbody");
$element = $elements[0];
$child = $element->first_child();

while($child) {
   print_r($child);
   $child = $child->next_sibling();
}
?>

See also domnode_previous_sibling().

DomNode->node_name

(no version information, might be only in CVS)

DomNode->node_name --  Returns name of node

Description

string DomNode->node_name ( void)

Returns name of the node. The name has different meanings for the different types of nodes as illustrated in the following table.

Tabela 1. Meaning of value

Type Meaning
DomAttribute value of attribute
DomAttribute  
DomCDataSection #cdata-section
DomComment #comment
DomDocument #document
DomDocumentType document type name
DomElement tag name
DomEntity name of entity
DomEntityReference name of entity reference
DomNotation notation name
DomProcessingInstruction target
DomText #text

DomNode->node_type

(no version information, might be only in CVS)

DomNode->node_type --  Returns type of node

Description

int DomNode->node_type ( void)

Returns the type of the node. All possible types are listed in the table in the introduction.

DomNode->node_value

(no version information, might be only in CVS)

DomNode->node_value --  Returns value of a node

Description

string DomNode->node_value ( void)

Returns value of the node. The value has different meanings for the different types of nodes as illustrated in the following table.

Tabela 1. Meaning of value

Type Meaning
DomAttribute value of attribute
DomAttribute  
DomCDataSection content
DomComment content of comment
DomDocument null
DomDocumentType null
DomElement null
DomEntity null
DomEntityReference null
DomNotation null
DomProcessingInstruction entire content without target
DomText content of text

DomNode->owner_document

(no version information, might be only in CVS)

DomNode->owner_document --  Returns the document this node belongs to

Description

object DomNode->owner_document ( void)

This function returns the document the current node belongs to.

The following example will create two identical lists of children.

Exemplo 1. Finding the document of a node

<?php
$doc = domxml_new_doc("1.0");
$node = $doc->create_element("para");
$node = $doc->append_child($node);
$children = $doc->children();
print_r($children);

$doc2 = $node->owner_document();
$children = $doc2->children();
print_r($children);
?>

See also domnode_insert_before().

DomNode->parent_node

(no version information, might be only in CVS)

DomNode->parent_node --  Returns the parent of the node

Description

object DomNode->parent_node ( void)

This function returns the parent node.

(PHP >= 4.3 only) If no parent is found, NULL is returned.

The following example will show two identical lists of children.

Exemplo 1. Finding the document of a node

<?php
$doc = domxml_new_doc("1.0");
$node = $doc->create_element("para");
$node = $doc->append_child($node);
$children = $doc->children();
print_r($children);

$doc2 = $node->parent_node();
$children = $doc2->children();
print_r($children);
?>

DomNode->prefix

(no version information, might be only in CVS)

DomNode->prefix --  Returns name space prefix of node

Description

string DomNode->prefix ( void)

Returns the name space prefix of the node.

DomNode->previous_sibling

(no version information, might be only in CVS)

DomNode->previous_sibling --  Returns the previous sibling of node

Description

object DomNode->previous_sibling ( void)

This function returns the previous sibling of the current node. If there is no previous sibling it returns FALSE (< 4.3) or NULL (>= 4.3). You can use this function to iterate over all children of a node as shown in the example.

See also domnode_next_sibling().

DomNode->remove_child

(no version information, might be only in CVS)

DomNode->remove_child --  Removes child from list of children

Description

object DomNode->remove_child ( object oldchild)

This functions removes a child from a list of children. If child cannot be removed or is not a child the function will return FALSE. If the child could be removed the functions returns the old child.

Exemplo 1. Removing a child

<?php
include("example.inc");

if(!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$elements = $dom->get_elements_by_tagname("tbody");
$element = $elements[0];
$children = $element->child_nodes();
$child = $element->remove_child($children[0]);

echo "<PRE>";
$xmlfile = $dom->dump_mem(true);
echo htmlentities($xmlfile);
echo "</PRE>";
?>

See also domnode_append_child().

DomNode->replace_child

(no version information, might be only in CVS)

DomNode->replace_child --  Replaces a child

Description

object DomNode->replace_child ( object oldnode, object newnode)

(PHP 4.2) This function replaces the child oldnode with 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 succeds the old node is returned.

(PHP 4.3) This function replaces the child oldnode with the passed newnode, even if the new node already is a child of the DomNode. If newnode was already inserted 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 is returned. (This behaviour is according to the W3C specs).

See also domnode_append_child()

DomNode->replace_node

(no version information, might be only in CVS)

DomNode->replace_node --  Replaces node

Description

object DomNode->replace_node ( object newnode)

(PHP 4.2) This function replaces an existing node with the 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 time. This behaviour enforces doing all modifications on the node before the replacement or to refetch the inserted node afterwards with functions like domnode_first_child(), domnode_child_nodes() etc..

(PHP 4.3) This function replaces an existing node with the passed new node. It is not copied anymore. If newnode 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()

DomNode->set_content

(no version information, might be only in CVS)

DomNode->set_content --  Sets content of node

Description

bool DomNode->set_content ( void)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

DomNode->set_name

(no version information, might be only in CVS)

DomNode->set_name --  Sets name of node

Description

bool DomNode->set_name ( void)

Sets name of node.

See also domnode_node_name().

DomNode->set_namespace

(no version information, might be only in CVS)

DomNode->set_namespace --  Sets namespace of a node.

Description

void DomNode->set_namespace ( string uri [, string prefix])

Sets the namespace of a node to uri. If there is already a namespace declaration with the same uri in one of the parent nodes of the node, the prefix of this is taken, otherwise it will take the one provided in the optional parameter prefix or generate a random one.

See also domdocument_create_element_ns(), domnode_add_namespace()

DomNode->unlink_node

(no version information, might be only in CVS)

DomNode->unlink_node --  Deletes node

Description

object DomNode->unlink_node ( void)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

DomProcessingInstruction->data

(no version information, might be only in CVS)

DomProcessingInstruction->data --  Returns data of pi node

Description

string DomProcessingInstruction->data ( void)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

DomProcessingInstruction->target

(no version information, might be only in CVS)

DomProcessingInstruction->target --  Returns target of pi node

Description

string DomProcessingInstruction->target ( void)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

DomXsltStylesheet->process

(no version information, might be only in CVS)

DomXsltStylesheet->process --  Applies the XSLT-Transformation on a DomDocument Object.

Description

object DomXsltStylesheet->process ( object DomDocument [, array xslt_parameters [, bool param_is_xpath]])

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

See also domxml_xslt_stylesheet(), domxml_xslt_stylesheet_file(), domxml_xslt_stylesheet_doc()

DomXsltStylesheet->result_dump_file

(no version information, might be only in CVS)

DomXsltStylesheet->result_dump_file --  Dumps the result from a XSLT-Transformation into a file

Description

string DomXsltStylesheet->result_dump_file ( object DomDocument, string filename)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

This function is only available since PHP 4.3

Since DomXsltStylesheet->process() always returns a 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 output HTML 4 or text data. This function on the contrary honors <xsl:output method="html|text"> and other output control directives. See the example for instruction of how to use it.

Exemplo 1. Saving the result of a XSLT transformation in a file

<?php
$filename = "stylesheet.xsl";
$xmldoc = domxml_open_file("data.xml");
$xsldoc = domxml_xslt_stylesheet_file($filename);
$result =  $xsldoc->process($xmldoc);
print $xsldoc->result_dump_file($result,"filename");     
?>

See also domxml_xslt_result_dump_mem(), domxml_xslt_process()

DomXsltStylesheet->result_dump_mem

(no version information, might be only in CVS)

DomXsltStylesheet->result_dump_mem --  Dumps the result from a XSLT-Transformation back into a string

Description

string DomXsltStylesheet->result_dump_mem ( object DomDocument)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

This function is only available since PHP 4.3

Since DomXsltStylesheet->process() always returns a 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 output HTML 4 or text data. This function on the contrary honors <xsl:output method="html|text"> and other output control directives. See the example for instruction of how to use it.

Exemplo 1. Outputting the result of a XSLT transformation

<?php
$filename = "stylesheet.xsl";
$xmldoc = domxml_open_file("data.xml");
$xsldoc = domxml_xslt_stylesheet_file($filename);
$result =  $xsldoc->process($xmldoc);
print $xsldoc->result_dump_mem($result);     
?>

See also domxml_xslt_result_dump_file(), domxml_xslt_process()

domxml_new_doc

(PHP 4 >= 4.2.1)

domxml_new_doc --  Creates new empty XML document

Description

object domxml_new_doc ( string version)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Creates a new dom document from scratch and returns it.

See also domdocument_add_root()

domxml_open_file

(PHP 4 >= 4.2.1)

domxml_open_file -- Creates a DOM object from XML file

Description

object domxml_open_file ( string filename)

The function parses the XML document in the file named filename and returns an object of class "Dom document", having the properties as listed above. The file is accessed read-only.

Exemplo 1. Opening a xml document from a file

<?php

if(!$dom = domxml_open_file("example.xml")) {
  echo "Error while parsing the document\n";
  exit;
}

$root = $dom->document_element();
?>

See also domxml_open_mem(), domxml_new_doc().

domxml_open_mem

(PHP 4 >= 4.2.1)

domxml_open_mem -- Creates a DOM object of an XML document

Description

object domxml_open_mem ( string str)

The function parses the XML document in str and returns an object of class "Dom document", having the properties as listed above. This function, domxml_open_file() or domxml_new_doc() must be called before any other function calls.

Exemplo 1. Opening a xml document in a string

<?php
include("example.inc");

if(!$dom = domxml_open_mem($xmlstr)) {
  echo "Error while parsing the document\n";
  exit;
}

$root = $dom->document_element();
?>

See also domxml_open_file(), domxml_new_doc().

domxml_version

(PHP 4 >= 4.1.0)

domxml_version --  Get XML library version

Description

string domxml_version ( void)

This function returns the version of the XML library version currently used.

domxml_xmltree

(PHP 4 >= 4.2.1)

domxml_xmltree --  Creates a tree of PHP objects from an XML document

Description

object domxml_xmltree ( string str)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

The function parses the XML document in str and returns a tree PHP objects as the parsed document. This function is isolated from the other functions, which means you cannot access the tree with any of the other functions. Modifying it, for example by adding nodes, makes no sense since there is currently no way to dump it as an XML file. However this function may be valuable if you want to read a file and investigate the content.

domxml_xslt_stylesheet_doc

(PHP 4 >= 4.2.0)

domxml_xslt_stylesheet_doc --  Creates a DomXsltStylesheet Object from a DomDocument Object.

Description

object domxml_xslt_stylesheet_doc ( object DocDocument Object)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

See also domxsltstylesheet->process(), domxml_xslt_stylesheet(), domxml_xslt_stylesheet_file()

domxml_xslt_stylesheet_file

(PHP 4 >= 4.2.0)

domxml_xslt_stylesheet_file --  Creates a DomXsltStylesheet Object from a xsl document in a file.

Description

object domxml_xslt_stylesheet_file ( string xsl file)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

See also domxsltstylesheet->process(), domxml_xslt_stylesheet(), domxml_xslt_stylesheet_doc()

domxml_xslt_stylesheet

(PHP 4 >= 4.2.0)

domxml_xslt_stylesheet --  Creates a DomXsltStylesheet Object from a xml document in a string.

Description

object domxml_xslt_stylesheet ( string xsl document)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

See also domxsltstylesheet->process(), domxml_xslt_stylesheet_file(), domxml_xslt_stylesheet_doc()

xpath_eval_expression

(PHP 4 >= 4.0.4)

xpath_eval_expression --  Evaluates the XPath Location Path in the given string

Description

array xpath_eval_expression ( object xpath_context)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

See also xpath_eval()

xpath_eval

(PHP 4 >= 4.0.4)

xpath_eval --  Evaluates the XPath Location Path in the given string

Description

array xpath_eval ( object xpath context, string xpath expression [, object contextnode])

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

The optional contextnode can be specified for doing relative XPath queries.

See also xpath_new_context()

xpath_new_context

(PHP 4 >= 4.0.4)

xpath_new_context --  Creates new xpath context

Description

object xpath_new_context ( object dom document)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

See also xpath_eval()

xptr_eval

(PHP 4 >= 4.0.4)

xptr_eval --  Evaluate the XPtr Location Path in the given string

Description

int xptr_eval ( [object xpath_context, string eval_str])

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

xptr_new_context

(PHP 4 >= 4.0.4)

xptr_new_context --  Create new XPath Context

Description

string xptr_new_context ( [object doc_handle])

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

XXVI. .NET functions

Introdução

Atenção

Este módulo é EXPERIMENTAL. Isso quer dizer que o comportamento neste módulo --- incluindo suas funções e seus nomes, e TUDO mais que está documentado sobre esse módulo --- poderá mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use este módulo por sua própria conta e risco.

Índice
dotnet_load -- Loads a DOTNET module

dotnet_load

(no version information, might be only in CVS)

dotnet_load -- Loads a DOTNET module

Description

int dotnet_load ( string assembly_name [, string datatype_name [, int codepage]])

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

XXVII. Error Handling and Logging Functions

Introdução

These are functions dealing with error handling and logging. They allow you to define your own error handling rules, as well as modify the way the errors can be logged. This allows you to change and enhance error reporting to suit your needs.

With the logging functions, you can send messages directly to other machines, to an email (or email to pager gateway!), to system logs, etc., so you can selectively log and monitor the most important parts of your applications and websites.

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


Requisitos

Nenhuma biblioteca externa é necessária para compilar esta extensão.


Instalação

Não há nenhuma instalação nescessária para utilizar estas funções, elas fazem parte do núcleo do PHP.


Configuração durante execução

O comportamento dessas funções podem ser modificado pelas configurações do php.ini.

Tabela 1. Errors and Logging Configuration Options

Name Default Changeable
error_reporting E_ALL & ~E_NOTICE PHP_INI_ALL
display_errors "1" PHP_INI_ALL
display_startup_errors "0" PHP_INI_ALL
log_errors "0" PHP_INI_ALL
log_errors_max_len "1024" PHP_INI_ALL
ignore_repeated_errors "0" PHP_INI_ALL
ignore_repeated_source "0" PHP_INI_ALL
report_memleaks "1" PHP_INI_SYSTEM
track_errors "0" PHP_INI_ALL
html_errors "1" PHP_INI_ALL
docref_root "http://www.php.net/" PHP_INI_ALL
docref_ext ".html" PHP_INI_ALL
error_prepend_string NULL PHP_INI_ALL
error_append_string NULL PHP_INI_ALL
error_log NULL PHP_INI_ALL
warn_plus_overloading NULL PHP_INI??
For further details and definition of the PHP_INI_* constants see ini_set().

Here is a short explanation of the configuration directives.

error_reporting integer

Set the error reporting level. The parameter is either an integer representing a bit field, or named constants. The error_reporting levels and constants are described in Predefined Constants, and in php.ini. To set at runtime, use the error_reporting() function. See also the display_errors directive.

In PHP 4 the default value does not show E_NOTICE level errors. You may want to show them during development.

Nota: Enabling E_NOTICE during development has some benefits. For debugging purposes: NOTICE messages will warn you about possibls bugs in your code. For example, use of unassigned values are warned. It is extremely useful to find typos and to save time for debugging. NOTICE messages will warn you about bad style. For example, $arr[item] is better to be written as $arr['item'] since PHP tries to treat "item" as constant. If it is not a constant, PHP assumes it is a string index for the array.

In PHP 3, the default setting is (E_ERROR | E_WARNING | E_PARSE), meaning the same thing. Note, however, that since constants are not supported in PHP 3's php3.ini, the error_reporting setting there must be numeric; hence, it is 7.

display_errors boolean

This determines whether errors should be printed to the screen as part of the HTML output or not.

display_startup_errors boolean

Even when display_errors is on, errors that occur during PHP's startup sequence are not displayed. It's strongly recommended to keep display_startup_errors off, except for debugging.

log_errors boolean

Tells whether script error messages should be logged to the server's error log or error_log. This option is thus server-specific.

Nota: You're strongly advised to use error logging in place of error displaying on production web sites.

log_errors_max_len integer

Set the maximum length of log_errors in kbytes. In error_log information about the source is added. The default is 1024 and 0 allows to not apply any maximum length at all.

ignore_repeated_errors boolean

Do not log repeated messages. Repeated errors must occur in the same file on the same line until ignore_repeated_source is set true.

ignore_repeated_source boolean

Ignore source of message when ignoring repeated messages. When this setting is On you will not log errors with repeated messages from different files or sourcelines.

report_memleaks boolean

If this parameter is set to Off, then memory leaks will not be shown (on stdout or in the log). This has only effect in a debug compile, and if error_reporting includes E_WARNING in the allowed list

track_errors boolean

If enabled, the last error message will always be present in the variable $php_errormsg.

html_errors boolean

Turn off HTML tags in error messages. The new format for html errors produces clickable messages that direct the user to a page describing the error or function in causing the error. These references are affected by docref_root and docref_ext.

docref_root string

The new error format contains a reference to a page describing the error or function in causing the error. In case of manual pages you can download the manual in your language and set this ini directive to the url of your local copy. If your local copy of the manual can be reached by '/manual/' you can simply use docref_root=/manual/. Additional you have to set docref_ext to match the fileextensions of your copy docref_ext=.html. It is possible to use external references. For example you can use docref_root=http://manual/en/ or docref_root="http://landonize.it/?how=url&theme=classic&filter=Landon&url=http%3A%2F%2Fwww.php.net%2F"

Most of the time you want the docref_root value to end with a slash '/'. But see the second example above which does not have nor need it.

docref_ext string

See docref_root.

Nota: The value of docref_ext must begin with a dot '.'.

error_prepend_string string

String to output before an error message.

error_append_string string

String to output after an error message.

error_log string

Name of the file where script errors should be logged. If the special value syslog is used, the errors are sent to the system logger instead. On UNIX, this means syslog(3) and on Windows NT it means the event log. The system logger is not supported on Windows 95. See also: syslog().

warn_plus_overloading boolean

If enabled, this option makes PHP output a warning when the plus (+) operator is used on strings. This is to make it easier to find scripts that need to be rewritten to using the string concatenator instead (.).


Constantes Predefinidas

As constantes listadas abaixo estão sempre disponíveis como parte do núcleo do PHP.

Nota: You may use these constant names in php.ini but not outside of PHP, like in httpd.conf, where you'd use the bitmask values instead.

Tabela 2. Errors and Logging

Value Constant Description Note
1 E_ERROR (integer) Fatal run-time errors. These indicate errors that can not be recovered from, such as a memory allocation problem. Execution of the script is halted.  
2 E_WARNING (integer) Run-time warnings (non-fatal errors). Execution of the script is not halted.  
4 E_PARSE (integer) Compile-time parse errors. Parse errors should only be generated by the parser.  
8 E_NOTICE (integer) Run-time notices. Indicate that the script encountered something that could indicate an error, but could also happen in the normal course of running a script.  
16 E_CORE_ERROR (integer) Fatal errors that occur during PHP's initial startup. This is like an E_ERROR, except it is generated by the core of PHP. PHP 4 only
32 E_CORE_WARNING (integer) Warnings (non-fatal errors) that occur during PHP's initial startup. This is like an E_WARNING, except it is generated by the core of PHP. PHP 4 only
64 E_COMPILE_ERROR (integer) Fatal compile-time errors. This is like an E_ERROR, except it is generated by the Zend Scripting Engine. PHP 4 only
128 E_COMPILE_WARNING (integer) Compile-time warnings (non-fatal errors). This is like an E_WARNING, except it is generated by the Zend Scripting Engine. PHP 4 only
256 E_USER_ERROR (integer) User-generated error message. This is like an E_ERROR, except it is generated in PHP code by using the PHP function trigger_error(). PHP 4 only
512 E_USER_WARNING (integer) User-generated warning message. This is like an E_WARNING, except it is generated in PHP code by using the PHP function trigger_error(). PHP 4 only
1024 E_USER_NOTICE (integer) User-generated notice message. This is like an E_NOTICE, except it is generated in PHP code by using the PHP function trigger_error(). PHP 4 only
2047 E_ALL (integer) All errors and warnings, as supported.  

The above values (either numerical or symbolic) are used to build up a bitmask that specifies which errors to report. You can use the bitwise operators to combine these values or mask out certain types of errors. Note that only '|', '~', '!', and '&' will be understood within php.ini, however, and that no bitwise operators will be understood within php3.ini.


Exemplos

Below we can see an example of using the error handling capabilities in PHP. We define a error handling function which logs the information into a file (using an XML format), and e-mails the developer in case a critical error in the logic happens.

Exemplo 1. Using error handling in a script

<?php
// we will do our own error handling
error_reporting(0);

// user defined error handling function
function userErrorHandler ($errno, $errmsg, $filename, $linenum, $vars) {
    // timestamp for the error entry
    $dt = date("Y-m-d H:i:s (T)");

    // define an assoc array of error string
    // in reality the only entries we should
    // consider are 2,8,256,512 and 1024
    $errortype = array (
                1   =>  "Error",
                2   =>  "Warning",
                4   =>  "Parsing Error",
                8   =>  "Notice",
                16  =>  "Core Error",
                32  =>  "Core Warning",
                64  =>  "Compile Error",
                128 =>  "Compile Warning",
                256 =>  "User Error",
                512 =>  "User Warning",
                1024=>  "User Notice"
                );
    // set of errors for which a var trace will be saved
    $user_errors = array(E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE);
    
    $err = "<errorentry>\n";
    $err .= "\t<datetime>".$dt."</datetime>\n";
    $err .= "\t<errornum>".$errno."</errornum>\n";
    $err .= "\t<errortype>".$errortype[$errno]."</errortype>\n";
    $err .= "\t<errormsg>".$errmsg."</errormsg>\n";
    $err .= "\t<scriptname>".$filename."</scriptname>\n";
    $err .= "\t<scriptlinenum>".$linenum."</scriptlinenum>\n";

    if (in_array($errno, $user_errors))
        $err .= "\t<vartrace>".wddx_serialize_value($vars,"Variables")."</vartrace>\n";
    $err .= "</errorentry>\n\n";
    
    // for testing
    // echo $err;

    // save to the error log, and e-mail me if there is a critical user error
    error_log($err, 3, "/usr/local/php4/error.log");
    if ($errno == E_USER_ERROR)
        mail("phpdev@example.com","Critical User Error",$err);
}


function distance ($vect1, $vect2) {
    if (!is_array($vect1) || !is_array($vect2)) {
        trigger_error("Incorrect parameters, arrays expected", E_USER_ERROR);
        return NULL;
    }

    if (count($vect1) != count($vect2)) {
        trigger_error("Vectors need to be of the same size", E_USER_ERROR);
        return NULL;
    }

    for ($i=0; $i<count($vect1); $i++) {
        $c1 = $vect1[$i]; $c2 = $vect2[$i];
        $d = 0.0;
        if (!is_numeric($c1)) {
            trigger_error("Coordinate $i in vector 1 is not a number, using zero", 
                            E_USER_WARNING);
            $c1 = 0.0;
        }
        if (!is_numeric($c2)) {
            trigger_error("Coordinate $i in vector 2 is not a number, using zero", 
                            E_USER_WARNING);
            $c2 = 0.0;
        }
        $d += $c2*$c2 - $c1*$c1;
    }
    return sqrt($d);
}

$old_error_handler = set_error_handler("userErrorHandler");

// undefined constant, generates a warning
$t = I_AM_NOT_DEFINED;

// define some "vectors"
$a = array(2,3,"foo");
$b = array(5.5, 4.3, -1.6);
$c = array (1,-3);

// generate a user error
$t1 = distance($c,$b)."\n";

// generate another user error
$t2 = distance($b,"i am not an array")."\n";

// generate a warning
$t3 = distance($a,$b)."\n";

?>


Veja Também

See also syslog().

Índice
debug_backtrace --  Generates a backtrace
error_log -- send an error message somewhere
error_reporting -- set which PHP errors are reported
restore_error_handler --  Restores the previous error handler function
set_error_handler --  Sets a user-defined error handler function.
trigger_error --  Generates a user-level error/warning/notice message
user_error --  Generates a user-level error/warning/notice message

debug_backtrace

(PHP 4 >= 4.3.0)

debug_backtrace --  Generates a backtrace

Description

array debug_backtrace ( void)

debug_backtrace() generates a PHP backtrace and returns this information as an associative array. The possible returned elements are listed in the following table:

Tabela 1. Possible returned elements from debug_backtrace()

Name Type Description
function string The current function name. See also __FUNCTION__.
line integer The current line number. See also __LINE__.
file string The current file name. See also __FILE__.
class string The current class name. See also __CLASS__
type string The current class type.
args array If inside a function, this lists the functions arguments. If inside a included file, this lists the included file name(s).

The following is a simple example.

Exemplo 1. debug_backtrace() example

// filename: a.php
<?php

function a_test($str) {

    print "\nHi: $str";

    var_dump(debug_backtrace());
}

a_test('friend');
?>

// filename: b.php
<?php
include_once '/tmp/a.php';
?>

/* Results when executing /tmp/b.php

Hi: friend
array(2) {
  [0]=>
  array(4) {
    ["file"] => string(10) "/tmp/a.php"
    ["line"] => int(10)
    ["function"] => string(6) "a_test"
    ["args"]=>
    array(1) {
      [0] => &string(6) "friend"
    }
  }
  [1]=>
  array(4) {
    ["file"] => string(10) "/tmp/b.php"
    ["line"] => int(2)
    ["args"] => 
    array(1) {
      [0] => string(10) "/tmp/a.php"
    }
    ["function"] => string(12) "include_once"
  }
}
*/

See also trigger_error().

error_log

(PHP 3, PHP 4 )

error_log -- send an error message somewhere

Description

int error_log ( string message [, int message_type [, string destination [, string extra_headers]]])

Sends an error message to the web server's error log, a TCP port or to a file. The first parameter, message, is the error message that should be logged. The second parameter, message_type says where the message should go:

Tabela 1. error_log() log types

0 message is sent to PHP's system logger, using the Operating System's system logging mechanism or a file, depending on what the error_log configuration directive is set to.
1 message is sent by email to the address in the destination parameter. This is the only message type where the fourth parameter, extra_headers is used. This message type uses the same internal function as mail() does.
2 message is sent through the PHP debugging connection. This option is only available if remote debugging has been enabled. In this case, the destination parameter specifies the host name or IP address and optionally, port number, of the socket receiving the debug information.
3 message is appended to the file destination.

Atenção

Remote debugging via TCP/IP is a PHP 3 feature that is not available in PHP 4.

Exemplo 1. error_log() examples

// Send notification through the server log if we can not
// connect to the database.
if (!Ora_Logon ($username, $password)) {
    error_log ("Oracle database not available!", 0);
}

// Notify administrator by email if we run out of FOO
if (!($foo = allocate_new_foo()) {
    error_log ("Big trouble, we're all out of FOOs!", 1,
               "operator@mydomain.com");
}

// other ways of calling error_log():
error_log ("You messed up!", 2, "127.0.0.1:7000");
error_log ("You messed up!", 2, "loghost");
error_log ("You messed up!", 3, "/var/tmp/my-errors.log");

error_reporting

(PHP 3, PHP 4 )

error_reporting -- set which PHP errors are reported

Description

int error_reporting ( [int level])

The error_reporting() function sets the error_reporting directive at runtime. PHP has many levels of errors, using this function sets that level for the duration (runtime) of your script.

error_reporting() sets PHP's error reporting level, and returns the old level. The level parameter takes on either a bitmask, or named constants. Using named constants is strongly encouraged to ensure compatibility for future versions. As error levels are added, the range of integers increases, so older integer-based error levels will not always behave as expected.

Some example uses:

Exemplo 1. error_reporting() examples

<?php

// Turn off all error reporting
error_reporting(0);

// Report simple running errors
error_reporting  (E_ERROR | E_WARNING | E_PARSE);

// Reporting E_NOTICE can be good too (to report uninitialized 
// variables or catch variable name misspellings ...)
error_reporting (E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

// Report all errors except E_NOTICE
// This is the default value set in php.ini
error_reporting (E_ALL ^ E_NOTICE);

// Report all PHP errors (bitwise 63 may be used in PHP 3)
error_reporting (E_ALL);

// Same as error_reporting(E_ALL);
ini_set ('error_reporting', E_ALL);

?>

The available error level constants are listed below. The actual meanings of these error levels are described in the predefined constants.

Tabela 1. error_reporting() level constants and bit values

value constant
1 E_ERROR
2 E_WARNING
4 E_PARSE
8 E_NOTICE
16 E_CORE_ERROR
32 E_CORE_WARNING
64 E_COMPILE_ERROR
128 E_COMPILE_WARNING
256 E_USER_ERROR
512 E_USER_WARNING
1024 E_USER_NOTICE
2047 E_ALL

See also the display_errors directive and ini_set().

restore_error_handler

(PHP 4 >= 4.0.1)

restore_error_handler --  Restores the previous error handler function

Description

void restore_error_handler ( void)

Used after changing the error handler function using set_error_handler(), to revert to the previous error handler (which could be the built-in or a user defined function)

See also error_reporting(), set_error_handler(), trigger_error(), user_error()

set_error_handler

(PHP 4 >= 4.0.1)

set_error_handler --  Sets a user-defined error handler function.

Description

string set_error_handler ( callback error_handler)

Sets a user function (error_handler) to handle errors in a script. Returns the previously defined error handler (if any), or FALSE on error. This function can be used for defining your own way of handling errors during runtime, for example in applications in which you need to do cleanup of data/files when a critical error happens, or when you need to trigger an error under certain conditions (using trigger_error())

The user function needs to accept 2 parameters: the error code, and a string describing the error. From PHP 4.0.2, an additional 3 optional parameters are supplied: the filename in which the error occurred, the line number in which the error occurred, and the context in which the error occurred (an array that points to the active symbol table at the point the error occurred).

Nota: Instead of a function name, an array containing an object reference and a method name can also be supplied. (Since PHP 4.3.0)

Nota: The following error types cannot be handled with a user defined function: E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR and E_COMPILE_WARNING.

The example below shows the handling of internal exceptions by triggering errors and handling them with a user defined function:

Exemplo 1. Error handling with set_error_handler() and trigger_error()

<?php

// redefine the user error constants - PHP 4 only
define ("FATAL",E_USER_ERROR);
define ("ERROR",E_USER_WARNING);
define ("WARNING",E_USER_NOTICE);

// set the error reporting level for this script
error_reporting (FATAL | ERROR | WARNING);

// error handler function
function myErrorHandler ($errno, $errstr, $errfile, $errline) {
  switch ($errno) {
  case FATAL:
    echo "<b>FATAL</b> [$errno] $errstr<br>\n";
    echo "  Fatal error in line ".$errline." of file ".$errfile;
    echo ", PHP ".PHP_VERSION." (".PHP_OS.")<br>\n";
    echo "Aborting...<br>\n";
    exit(1);
    break;
  case ERROR:
    echo "<b>ERROR</b> [$errno] $errstr<br>\n";
    break;
  case WARNING:
    echo "<b>WARNING</b> [$errno] $errstr<br>\n";
    break;
    default:
    echo "Unkown error type: [$errno] $errstr<br>\n";
    break;
  }
}

// function to test the error handling
function scale_by_log ($vect, $scale) {
  if ( !is_numeric($scale) || $scale <= 0 )
    trigger_error("log(x) for x <= 0 is undefined, you used: scale = $scale",
      FATAL);
  if (!is_array($vect)) {
    trigger_error("Incorrect input vector, array of values expected", ERROR);
    return null;
  }
  for ($i=0; $i<count($vect); $i++) {
    if (!is_numeric($vect[$i]))
      trigger_error("Value at position $i is not a number, using 0 (zero)", 
        WARNING);
    $temp[$i] = log($scale) * $vect[$i];
  }
  return $temp;
}

// set to the user defined error handler
$old_error_handler = set_error_handler("myErrorHandler");

// trigger some errors, first define a mixed array with a non-numeric item
echo "vector a\n";
$a = array(2,3,"foo",5.5,43.3,21.11);
print_r($a);

// now generate second array, generating a warning
echo "----\nvector b - a warning (b = log(PI) * a)\n";
$b = scale_by_log($a, M_PI);
print_r($b);

// this is trouble, we pass a string instead of an array
echo "----\nvector c - an error\n";
$c = scale_by_log("not array",2.3);
var_dump($c);

// this is a critical error, log of zero or negative number is undefined
echo "----\nvector d - fatal error\n";
$d = scale_by_log($a, -2.5);

?>
And when you run this sample script, the output will be

vector a
Array
(
    [0] => 2
    [1] => 3
    [2] => foo
    [3] => 5.5
    [4] => 43.3
    [5] => 21.11
)
----
vector b - a warning (b = log(PI) * a)
<b>WARNING</b> [1024] Value at position 2 is not a number, using 0 (zero)<br>
Array
(
    [0] => 2.2894597716988
    [1] => 3.4341896575482
    [2] => 0
    [3] => 6.2960143721717
    [4] => 49.566804057279
    [5] => 24.165247890281
)
----
vector c - an error
<b>ERROR</b> [512] Incorrect input vector, array of values expected<br>
NULL
----
vector d - fatal error
<b>FATAL</b> [256] log(x) for x <= 0 is undefined, you used: scale = -2.5<br>
  Fatal error in line 36 of file trigger_error.php, PHP 4.0.2 (Linux)<br>
Aborting...<br>

It is important to remember that the standard PHP error handler is completely bypassed. error_reporting() settings will have no effect and your error handler will be called regardless - however you are still able to read the current value of error_reporting and act appropriately. Of particular note is that this value will be 0 if the statement that caused the error was prepended by the @ error-control operator.

Also note that it is your responsibility to die() if necessary. If the error-handler function returns, script execution will continue with the next statement after the one that caused an error.

Nota: If errors occur before the script is executed (e.g. on file uploads) the custom error handler cannot be called since it is not registered at that time.

See also error_reporting(), restore_error_handler(), trigger_error(), user_error()

trigger_error

(PHP 4 >= 4.0.1)

trigger_error --  Generates a user-level error/warning/notice message

Description

void trigger_error ( string error_msg [, int error_type])

Used to trigger a user error condition, it can be used by in conjunction with the built-in error handler, or with a user defined function that has been set as the new error handler (set_error_handler()). It only works with the E_USER family of constants, and will default to E_USER_NOTICE.

This function is useful when you need to generate a particular response to an exception at runtime. For example:

if (assert ($divisor == 0))
   trigger_error ("Cannot divide by zero", E_USER_ERROR);

Nota: See set_error_handler() for a more extensive example.

Nota: error_msg is limited to 1024 characters in length. Any additional characters beyond 1024 will be truncated.

See also error_reporting(), set_error_handler(), restore_error_handler(), user_error()

user_error

(PHP 4 )

user_error --  Generates a user-level error/warning/notice message

Description

void user_error ( string error_msg [, int error_type])

This is an alias for the function trigger_error().

See also error_reporting(), set_error_handler(), restore_error_handler(), and trigger_error()

XXVIII. FrontBase Functions

Introdução

These functions allow you to access FrontBase database servers. More information about FrontBase can be found at http://www.frontbase.com/.

Documentation for FrontBase can be found at http://www.frontbase.com/cgi-bin/WebObjects/FrontBase.woa/wa/productsPage?currentPage=Documentation.

Frontbase support has been added to PHP 4.0.6.


Requisitos

You must install the FrontBase database server or at least the fbsql client libraries to use this functions. You can get FrontBase from http://www.frontbase.com/.


Instalação

In order to have these functions available, you must compile PHP with fbsql support by using the --with-fbsql[=DIR] option. If you use this option without specifying the path to fbsql, PHP will search for the fbsql 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 fbsql: --with-fbsql=/path/to/fbsql. This will force PHP to use the client libraries installed by FrontBase, avoiding any conflicts.


Configuração durante execução

O comportamento dessas funções podem ser modificado pelas configurações do php.ini.

Tabela 1. FrontBase configuration options

Name Default Changeable
fbsql.allow_persistent "1" PHP_INI_SYSTEM
fbsql.generate_warnings "0" PHP_INI_SYSTEM
fbsql.autocommit "1" PHP_INI_SYSTEM
fbsql.max_persistent "-1" PHP_INI_SYSTEM
fbsql.max_links "128" PHP_INI_SYSTEM
fbsql.max_connections "128" PHP_INI_SYSTEM
fbsql.max_results "128" PHP_INI_SYSTEM
fbsql.batchSize "1000" PHP_INI_SYSTEM
fbsql.default_host NULL PHP_INI_SYSTEM
fbsql.default_user "_SYSTEM" PHP_INI_SYSTEM
fbsql.default_password "" PHP_INI_SYSTEM
fbsql.default_database "" PHP_INI_SYSTEM
fbsql.default_database_password "" PHP_INI_SYSTEM
For further details and definition of the PHP_INI_* constants see ini_set().


Tipos Resource


Constantes Predefinidas

As contantes abaixo são definidas por esta extensão e somente estarão disponíveis quando a extensão foi compilada com o PHP ou carregada dinamicamente durante a execução.

FBSQL_ASSOC (integer)

FBSQL_NUM (integer)

FBSQL_BOTH (integer)

FBSQL_LOCK_DEFERRED (integer)

FBSQL_LOCK_OPTIMISTIC (integer)

FBSQL_LOCK_PESSIMISTIC (integer)

FBSQL_ISO_READ_UNCOMMITTED (integer)

FBSQL_ISO_READ_COMMITTED (integer)

FBSQL_ISO_REPEATABLE_READ (integer)

FBSQL_ISO_SERIALIZABLE (integer)

FBSQL_ISO_VERSIONED (integer)

FBSQL_UNKNOWN (integer)

FBSQL_STOPPED (integer)

FBSQL_STARTING (integer)

FBSQL_RUNNING (integer)

FBSQL_STOPPING (integer)

FBSQL_NOEXEC (integer)

FBSQL_LOB_DIRECT (integer)

FBSQL_LOB_HANDLE (integer)

Índice
fbsql_affected_rows --  Get number of affected rows in previous FrontBase operation
fbsql_autocommit -- Enable or disable autocommit
fbsql_change_user --  Change logged in user of the active connection
fbsql_close -- Close FrontBase connection
fbsql_commit -- Commits a transaction to the database
fbsql_connect -- Open a connection to a FrontBase Server
fbsql_create_blob -- Create a BLOB
fbsql_create_clob -- Create a CLOB
fbsql_create_db -- Create a FrontBase database
fbsql_data_seek -- Move internal result pointer
fbsql_database_password --  Sets or retrieves the password for a FrontBase database
fbsql_database -- Get or set the database name used with a connection
fbsql_db_query -- Send a FrontBase query
fbsql_db_status -- Get the status for a given database
fbsql_drop_db -- Drop (delete) a FrontBase database
fbsql_errno --  Returns the numerical value of the error message from previous FrontBase operation
fbsql_error --  Returns the text of the error message from previous FrontBase operation
fbsql_fetch_array --  Fetch a result row as an associative array, a numeric array, or both
fbsql_fetch_assoc --  Fetch a result row as an associative array
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 result
fbsql_fetch_object -- Fetch a result row as an object
fbsql_fetch_row -- Get a result row as an enumerated array
fbsql_field_flags --  Get the flags associated with the specified field in a result
fbsql_field_len --  Returns the length of the specified field
fbsql_field_name --  Get the name of the specified field in a result
fbsql_field_seek --  Set result pointer to a specified field offset
fbsql_field_table --  Get name of the table the specified field is in
fbsql_field_type --  Get the type of the specified field in a result
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 connection
fbsql_insert_id --  Get the id generated from the previous INSERT operation
fbsql_list_dbs --  List databases available on a FrontBase server
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 the next result
fbsql_num_fields -- Get number of fields in result
fbsql_num_rows -- Get number of rows in result
fbsql_password -- Get or set the user password used with a connection
fbsql_pconnect --  Open a persistent connection to a FrontBase Server
fbsql_query -- Send a FrontBase query
fbsql_read_blob -- Read a BLOB from the database
fbsql_read_clob -- Read a CLOB from the database
fbsql_result -- Get result data
fbsql_rollback -- Rollback a transaction to the database
fbsql_select_db -- Select a FrontBase database
fbsql_set_lob_mode --  Set the LOB retrieve mode for a FrontBase result set
fbsql_set_transaction --  Set the transaction locking and isolation
fbsql_start_db -- Start a database on local or remote server
fbsql_stop_db -- Stop a database on local or remote server
fbsql_tablename -- Get table name of field
fbsql_username -- Get or set the host user used with a connection
fbsql_warnings -- Enable or disable FrontBase warnings

fbsql_affected_rows

(PHP 4 >= 4.0.6)

fbsql_affected_rows --  Get number of affected rows in previous FrontBase operation

Description

int fbsql_affected_rows ( [resource link_identifier])

fbsql_affected_rows() returns the number of rows affected by the last INSERT, UPDATE or DELETE query associated with link_identifier. If the link identifier isn't specified, the last link opened by fbsql_connect() is assumed.

Nota: If you are using transactions, you need to call fbsql_affected_rows() after your INSERT, UPDATE, or DELETE query, not after the commit.

If the last query was a DELETE query with no WHERE clause, all of the records will have been deleted from the table but this function will return zero.

Nota: When using UPDATE, 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 actually equal the number of rows matched, only the number of rows that were literally affected by the query.

If the last query failed, this function will return -1.

See also: fbsql_num_rows().

fbsql_autocommit

(PHP 4 >= 4.0.6)

fbsql_autocommit -- Enable or disable autocommit

Description

bool fbsql_autocommit ( resource link_identifier [, bool OnOff])

fbsql_autocommit() returns the current autocommit status. if the optional OnOff parameter is given the auto commit status will be changed. With OnOff set to TRUE each statement will be committed automatically, if no errors was found. With OnOff set to FALSE the user must commit or rollback the transaction using either fbsql_commit() or fbsql_rollback().

See also: fbsql_commit() and fbsql_rollback()

fbsql_change_user

(no version information, might be only in CVS)

fbsql_change_user --  Change logged in user of the active connection

Description

resource fbsql_change_user ( string user, string password [, string database [, resource link_identifier]])

fbsql_change_user() changes the logged in user of the current active connection, or the connection given by the optional parameter link_identifier. If a database is specified, this will default or current database after the user has been changed. If the new user and password authorization fails, the current connected user stays active.

fbsql_close

(PHP 4 >= 4.0.6)

fbsql_close -- Close FrontBase connection

Description

boolean fbsql_close ( [resource link_identifier])

Returns: TRUE on success, FALSE on error.

fbsql_close() closes the connection to the FrontBase server that's associated with the specified link identifier. If link_identifier isn't specified, the last opened link is used.

Using fbsql_close() isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution.

Exemplo 1. fbsql_close() example

<?php
    $link = fbsql_connect ("localhost", "_SYSTEM", "secret")
        or die ("Could not connect");
    print ("Connected successfully");
    fbsql_close ($link);
?>

See also: fbsql_connect() and fbsql_pconnect().

fbsql_commit

(PHP 4 >= 4.0.6)

fbsql_commit -- Commits a transaction to the database

Description

bool fbsql_commit ( [resource link_identifier])

Retorna TRUE em caso de sucesso ou FALSE em falhas.

fbsql_commit() ends the current transaction by writing all inserts, updates and deletes to the disk and unlocking all row and table locks held by the transaction. This command is only needed if autocommit is set to false.

See also: fbsql_autocommit() and fbsql_rollback()

fbsql_connect

(PHP 4 >= 4.0.6)

fbsql_connect -- Open a connection to a FrontBase Server

Description

resource fbsql_connect ( [string hostname [, string username [, string password]]])

Returns a positive FrontBase link identifier on success, or an error message on failure.

fbsql_connect() establishes a connection to a FrontBase server. The following defaults are assumed for missing optional parameters: hostname = 'NULL', username = '_SYSTEM' and password = empty password.

If a second call is made to fbsql_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned.

The link to the server will be closed as soon as the execution of the script ends, unless it's closed earlier by explicitly calling fbsql_close().

Exemplo 1. fbsql_connect() example

<?php

    $link = fbsql_connect ("localhost", "_SYSTEM", "secret")
        or die ("Could not connect");
    print ("Connected successfully");
    fbsql_close ($link);

?>

See also fbsql_pconnect() and fbsql_close().

fbsql_create_blob

(PHP 4 >= 4.2.0)

fbsql_create_blob -- Create a BLOB

Description

string fbsql_create_blob ( string blob_data [, resource link_identifier])

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 update commands to store the blob in the database.

Exemplo 1. fbsql_create_blob() example

<?php
    $link = fbsql_pconnect ("localhost", "_SYSTEM", "secret")
        or die ("Could not connect");
    $filename = "blobfile.bin";
    $fp = fopen($filename, "rb");
    $blobdata = fread($fp, filesize($filename));
    fclose($fp);
    
    $blobHandle = fbsql_create_blob($blobdata, $link);
    
    $sql = "INSERT INTO BLOB_TABLE (BLOB_COLUMN) VALUES ($blobHandle);";
    $rs = fbsql_query($sql, $link);
?>

See also: fbsql_create_clob(), fbsql_read_blob(), fbsql_read_clob(), and fbsql_set_lob_mode().

fbsql_create_clob

(PHP 4 >= 4.2.0)

fbsql_create_clob -- Create a CLOB

Description

string fbsql_create_clob ( string clob_data [, resource link_identifier])

Returns: A resource handle to the newly created CLOB.

fbsql_create_clob() creates a clob from clob_data. The returned resource handle can be used with insert and update commands to store the clob in the database.

Exemplo 1. fbsql_create_clob() example

<?php
    $link = fbsql_pconnect ("localhost", "_SYSTEM", "secret")
        or die ("Could not connect");
    $filename = "clob_file.txt";
    $fp = fopen($filename, "rb");
    $clobdata = fread($fp, filesize($filename));
    fclose($fp);
    
    $clobHandle = fbsql_create_clob($clobdata, $link);
    
    $sql = "INSERT INTO CLOB_TABLE (CLOB_COLUMN) VALUES ($clobHandle);";
    $rs = fbsql_query($sql, $link);
?>

See also: fbsql_create_blob(), fbsql_read_blob(), fbsql_read_clob(), and fbsql_set_lob_mode().

fbsql_create_db

(PHP 4 >= 4.0.6)

fbsql_create_db -- Create a FrontBase database

Description

bool fbsql_create_db ( string database name [, resource link_identifier])

fbsql_create_db() attempts to create a new database on the server associated with the specified link identifier.

Exemplo 1. fbsql_create_db() example

<?php
    $link = fbsql_pconnect ("localhost", "_SYSTEM", "secret")
        or die ("Could not connect");
    if (fbsql_create_db ("my_db")) {
        print("Database created successfully\n");
    } else {
        printf("Error creating database: %s\n", fbsql_error ());
    }
?>

See also: fbsql_drop_db().

fbsql_data_seek

(PHP 4 >= 4.0.6)

fbsql_data_seek -- Move internal result pointer

Description

bool fbsql_data_seek ( resource result_identifier, int row_number)

Retorna TRUE em caso de sucesso ou FALSE em falhas.

fbsql_data_seek() moves the internal row pointer of the FrontBase result associated with the specified result identifier to point to the specified row number. The next call to fbsql_fetch_row() would return that row.

Row_number starts at 0.

Exemplo 1. fbsql_data_seek() example

<?php
    $link = fbsql_pconnect ("localhost", "_SYSTEM", "secret")
        or die ("Could not connect");

    fbsql_select_db ("samp_db")
        or die ("Could not select database");

    $query = "SELECT last_name, first_name FROM friends;";
    $result = fbsql_query ($query)
        or die ("Query failed");

    # fetch rows in reverse order

    for ($i = fbsql_num_rows ($result) - 1; $i >=0; $i--) {
        if (!fbsql_data_seek ($result, $i)) {
            printf ("Cannot seek to row %d\n", $i);
            continue;
        }

        if(!($row = fbsql_fetch_object ($result)))
            continue;

        printf("%s %s<BR>\n", $row->last_name, $row->first_name);
    }

    fbsql_free_result ($result);
?>

fbsql_database_password

(PHP 4 >= 4.0.6)

fbsql_database_password --  Sets or retrieves the password for a FrontBase database

Description

string fbsql_database_password ( resource link_identifier [, string database_password])

Returns: The database password associated with the link identifier.

fbsql_database_password() sets and retrieves the database password used by the connection. if a database is protected by a database password, the user must call 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 link identifier is specified, the last opened link is assumed. If no link is open, the function will try to establish a link as if fbsql_connect() was called, and use it.

This function does not change the database password in the database nor can it be used to retrive the database password for a database.

Exemplo 1. fbsql_create_clob() example

<?php
    $link = fbsql_pconnect ("localhost", "_SYSTEM", "secret")
        or die ("Could not connect");
    fbsql_database_password($link, "secret db password");
    fbsql_select_db($database, $link);
?>

See also: fbsql_connect(), fbsql_pconnect() and fbsql_select_db().

fbsql_database

(PHP 4 >= 4.0.6)

fbsql_database -- Get or set the database name used with a connection

Description

string fbsql_database ( resource link_identifier [, string database])

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

fbsql_db_query

(PHP 4 >= 4.0.6)

fbsql_db_query -- Send a FrontBase query

Description

resource fbsql_db_query ( string database, string query [, resource link_identifier])

Returns: A positive FrontBase result identifier to the query result, or FALSE on error.

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 server and if no such link is found it'll try to create one as if fbsql_connect() was called with no arguments

See also fbsql_connect().

fbsql_db_status

(PHP 4 >= 4.1.0)

fbsql_db_status -- Get the status for a given database

Description

int fbsql_db_status ( string database_name [, resource link_identifier])

Returns: An integer value with the current status.

fbsql_db_status() requests the current status of the database specified by database_name. If the link_identifier is omitted the default link_identifier will be used.

The return value can be one of the following constants:

  • FALSE - The exec handler for the host was invalid. This error will occur when the link_identifier connects directly to a database by using a port number. FBExec can be available on the server but no connection has been made for it.

  • FBSQL_UNKNOWN - The Status is unknown.

  • FBSQL_STOPPED - The database is not running. Use fbsql_start_db() to start the database.

  • FBSQL_STARTING - The database is starting.

  • FBSQL_RUNNING - The database is running and can be used to perform SQL operations.

  • FBSQL_STOPPING - The database is stopping.

  • FBSQL_NOEXEC - FBExec is not running on the server and it is not possible to get the status of the database.

See also: fbsql_start_db() and fbsql_stop_db().

fbsql_drop_db

(PHP 4 >= 4.0.6)

fbsql_drop_db -- Drop (delete) a FrontBase database

Description

bool fbsql_drop_db ( string database_name [, resource link_identifier])

Retorna TRUE em caso de sucesso ou FALSE em falhas.

fbsql_drop_db() attempts to drop (remove) an entire database from the server associated with the specified link identifier.

fbsql_errno

(PHP 4 >= 4.0.6)

fbsql_errno --  Returns the numerical value of the error message from previous FrontBase operation

Description

int fbsql_errno ( [resource link_identifier])

Returns the error number from the last fbsql function, or 0 (zero) if no error occurred.

Errors coming back from the fbsql database backend don't issue warnings. Instead, use fbsql_errno() to retrieve the error code. Note that this function only returns the error code from the most recently executed fbsql function (not including fbsql_error() and fbsql_errno()), so if you want to use it, make sure you check the value before calling another fbsql function.

<?php
fbsql_connect("marliesle");
echo fbsql_errno().": ".fbsql_error()."<BR>";
fbsql_select_db("nonexistentdb");
echo fbsql_errno().": ".fbsql_error()."<BR>";
$conn = fbsql_query("SELECT * FROM nonexistenttable;");
echo fbsql_errno().": ".fbsql_error()."<BR>";
?>

See also: fbsql_error() and fbsql_warnings().

fbsql_error

(PHP 4 >= 4.0.6)

fbsql_error --  Returns the text of the error message from previous FrontBase operation

Description

string fbsql_error ( [resource link_identifier])

Returns the error text from the last fbsql function, or '' (the empty string) if no error occurred.

Errors coming back from the fbsql database backend don't issue warnings. Instead, use fbsql_error() to 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 fbsql_errno()), so if you want to use it, make sure you check the value before calling another fbsql function.

<?php
fbsql_connect("marliesle");
echo fbsql_errno().": ".fbsql_error()."<BR>";
fbsql_select_db("nonexistentdb");
echo fbsql_errno().": ".fbsql_error()."<BR>";
$conn = fbsql_query("SELECT * FROM nonexistenttable;");
echo fbsql_errno().": ".fbsql_error()."<BR>";
?>

See also: fbsql_errno() and fbsql_warnings().

fbsql_fetch_array

(PHP 4 >= 4.0.6)

fbsql_fetch_array --  Fetch a result row as an associative array, a numeric array, or both

Description

array fbsql_fetch_array ( resource result [, int result_type])

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

fbsql_fetch_array() is an extended version of fbsql_fetch_row(). In addition to storing the data in the numeric indices of the result array, it also stores the data in associative indices, using the field names as keys.

If two or more columns of the result have the same field names, the last column will take precedence. To access the other column(s) of the same name, you must the numeric index of the column or make an alias for the column.

select t1.f1 as foo t2.f1 as bar from t1, t2

An important thing to note is that using fbsql_fetch_array() is NOT significantly slower than using fbsql_fetch_row(), while it provides a significant added value.

The optional second argument result_type in fbsql_fetch_array() is a constant and can take the following values: FBSQL_ASSOC, FBSQL_NUM, and FBSQL_BOTH.

For further details, see also fbsql_fetch_row() and fbsql_fetch_assoc().

Exemplo 1. fbsql_fetch_array() example

<?php 
fbsql_connect ($host, $user, $password);
$result = fbsql_db_query ("database","select user_id, fullname from table");
while ($row = fbsql_fetch_array ($result)) {
    echo "user_id: ".$row["user_id"]."<br>\n";
    echo "user_id: ".$row[0]."<br>\n";
    echo "fullname: ".$row["fullname"]."<br>\n";
    echo "fullname: ".$row[1]."<br>\n";
}
fbsql_free_result ($result);
?>

fbsql_fetch_assoc

(PHP 4 >= 4.0.6)

fbsql_fetch_assoc --  Fetch a result row as an associative array

Description

array fbsql_fetch_assoc ( resource result)

Returns an associative array that corresponds to the fetched row, or FALSE if there are no more rows.

fbsql_fetch_assoc() is equivalent to calling fbsql_fetch_array() with FBSQL_ASSOC for the optional second parameter. It only returns an associative array. This is the way fbsql_fetch_array() originally worked. If you need the numeric indices as well as the associative, use fbsql_fetch_array().

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() and have it return the numeric indices as well.

An important thing to note is that using fbsql_fetch_assoc() is NOT significantly slower than using fbsql_fetch_row(), while it provides a significant added value.

For further details, see also fbsql_fetch_row() and fbsql_fetch_array().

Exemplo 1. fbsql_fetch_assoc() example

<?php 
fbsql_connect ($host, $user, $password);
$result = fbsql_db_query ("database","select * from table");
while ($row = fbsql_fetch_assoc ($result)) {
    echo $row["user_id"];
    echo $row["fullname"];
}
fbsql_free_result ($result);
?>

fbsql_fetch_field

(PHP 4 >= 4.0.6)

fbsql_fetch_field --  Get column information from a result and return as an object

Description

object fbsql_fetch_field ( resource result [, int field_offset])

Returns an object containing field information.

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 retrieved by fbsql_fetch_field() is retrieved.

The properties of the object are:

  • name - column name

  • table - name of the table the column belongs to

  • max_length - maximum length of the column

  • not_null - 1 if the column cannot be NULL

  • type - the type of the column

Exemplo 1. fbsql_fetch_field() example

<?php 
fbsql_connect ($host, $user, $password)
    or die ("Could not connect");
$result = fbsql_db_query ("database", "select * from table")
    or die ("Query failed");
# get column metadata
$i = 0;
while ($i < fbsql_num_fields ($result)) {
    echo "Information for column $i:<BR>\n";
    $meta = fbsql_fetch_field ($result);
    if (!$meta) {
        echo "No information available<BR>\n";
    }
    echo "<PRE>
max_length:   $meta->max_length
name:         $meta->name
not_null:     $meta->not_null
table:        $meta->table
type:         $meta->type
</PRE>";
    $i++;
}
fbsql_free_result ($result);
?>

See also fbsql_field_seek().

fbsql_fetch_lengths

(PHP 4 >= 4.0.6)

fbsql_fetch_lengths --  Get the length of each output in a result

Description

array fbsql_fetch_lengths ( [resource result])

Returns: An array that corresponds to the lengths of each field in the last row fetched by fbsql_fetch_row(), or FALSE on error.

fbsql_fetch_lengths() stores the lengths of each result column in the last row returned by fbsql_fetch_row(), fbsql_fetch_array() and fbsql_fetch_object() in an array, starting at offset 0.

See also: fbsql_fetch_row().

fbsql_fetch_object

(PHP 4 >= 4.0.6)

fbsql_fetch_object -- Fetch a result row as an object

Description

object fbsql_fetch_object ( resource result [, int result_type])

Returns an object with properties that correspond to the fetched row, or FALSE if there are no more rows.

fbsql_fetch_object() is similar to fbsql_fetch_array(), with one difference - an object is returned, instead of an array. Indirectly, that means that you can only access the data by the field names, and not by their offsets (numbers are illegal property names).

The optional argument result_type is a constant and can take the following values: FBSQL_ASSOC, FBSQL_NUM, and FBSQL_BOTH.

Speed-wise, the function is identical to fbsql_fetch_array(), and almost as quick as fbsql_fetch_row() (the difference is insignificant).

Exemplo 1. fbsql_fetch_object() example

<?php 
fbsql_connect ($host, $user, $password);
$result = fbsql_db_query ("database", "select * from table");
while ($row = fbsql_fetch_object ($result)) {
    echo $row->user_id;
    echo $row->fullname;
}
fbsql_free_result ($result);
?>

See also: fbsql_fetch_array() and fbsql_fetch_row().

fbsql_fetch_row

(PHP 4 >= 4.0.6)

fbsql_fetch_row -- Get a result row as an enumerated array

Description

array fbsql_fetch_row ( resource result)

Returns: An array that corresponds to the fetched row, or FALSE if there are no more rows.

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 in an array offset, starting at offset 0.

Subsequent call to fbsql_fetch_row() would return the next row in the result set, or FALSE if there are no more rows.

See also: fbsql_fetch_array(), fbsql_fetch_object(), fbsql_data_seek(), fbsql_fetch_lengths(), and fbsql_result().

fbsql_field_flags

(PHP 4 >= 4.0.6)

fbsql_field_flags --  Get the flags associated with the specified field in a result

Description

string fbsql_field_flags ( resource result, int field_offset)

fbsql_field_flags() returns the field flags of the specified field. The flags are reported as a single word per flag separated by a single space, so that you can split the returned value using explode().

fbsql_field_len

(PHP 4 >= 4.0.6)

fbsql_field_len --  Returns the length of the specified field

Description

int fbsql_field_len ( resource result, int field_offset)

fbsql_field_len() returns the length of the specified field.

fbsql_field_name

(PHP 4 >= 4.0.6)

fbsql_field_name --  Get the name of the specified field in a result

Description

string fbsql_field_name ( resource result, int field_index)

fbsql_field_name() returns the name of the specified field index. result must be a valid result identifier and field_index is the numerical offset of the field.

Nota: field_index starts at 0.

e.g. The index of the third field would actually be 2, the index of the fourth field would be 3 and so on.

Exemplo 1. fbsql_field_name() example

// The users table consists of three fields: 
//   user_id
//   username
//   password.

$res = fbsql_db_query("users", "select * from users", $link);

echo fbsql_field_name($res, 0) . "\n";
echo fbsql_field_name($res, 2);

The above example would produce the following output:

user_id
password

fbsql_field_seek

(PHP 4 >= 4.0.6)

fbsql_field_seek --  Set result pointer to a specified field offset

Description

bool fbsql_field_seek ( resource result, int field_offset)

Seeks to the specified field offset. If the next call to fbsql_fetch_field() doesn't include a field offset, the field offset specified in fbsql_field_seek() will be returned.

See also: fbsql_fetch_field().

fbsql_field_table

(PHP 4 >= 4.0.6)

fbsql_field_table --  Get name of the table the specified field is in

Description

string fbsql_field_table ( resource result, int field_offset)

Returns the name of the table that the specified field is in.

fbsql_field_type

(PHP 4 >= 4.0.6)

fbsql_field_type --  Get the type of the specified field in a result

Description

string fbsql_field_type ( resource result, int field_offset)

fbsql_field_type() is similar to the fbsql_field_name() function. The arguments are identical, but the field type is returned instead. The field type will be one of "int", "real", "string", "blob", and others as detailed in the FrontBase documentation.

Exemplo 1. fbsql_field_type() example

<?php 

fbsql_connect ("localhost", "_SYSTEM", "");
fbsql_select_db ("wisconsin");
$result = fbsql_query ("SELECT * FROM onek;");
$fields = fbsql_num_fields ($result);
$rows   = fbsql_num_rows ($result);
$i = 0;
$table = fbsql_field_table ($result, $i);
echo "Your '".$table."' table has ".$fields." fields and ".$rows." records <BR>";
echo "The table has the following fields <BR>"; 
while ($i < $fields) {
    $type  = fbsql_field_type  ($result, $i);
    $name  = fbsql_field_name  ($result, $i);
    $len   = fbsql_field_len   ($result, $i);
    $flags = fbsql_field_flags ($result, $i);
    echo $type." ".$name." ".$len." ".$flags."<BR>";
    $i++;
}
fbsql_close();

?>

fbsql_free_result

(PHP 4 >= 4.0.6)

fbsql_free_result -- Free result memory

Description

bool fbsql_free_result ( resource result)

fbsql_free_result() will free all memory associated with the result identifier result.

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 memory is automatically freed at the end of the script's execution.

fbsql_get_autostart_info

(PHP 4 >= 4.1.0)

fbsql_get_autostart_info -- No description given yet

Description

array fbsql_get_autostart_info ( [resource link_identifier])

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

fbsql_hostname

(PHP 4 >= 4.0.6)

fbsql_hostname -- Get or set the host name used with a connection

Description

string fbsql_hostname ( resource link_identifier [, string host_name])

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

fbsql_insert_id

(PHP 4 >= 4.0.6)

fbsql_insert_id --  Get the id generated from the previous INSERT operation

Description

int fbsql_insert_id ( [resource link_identifier])

fbsql_insert_id() returns the ID generated for an column defined as DEFAULT UNIQUE by the previous INSERT query using the given link_identifier. If link_identifier isn't specified, the last opened link is assumed.

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.

Nota: The value of the FrontBase SQL function LAST_INSERT_ID() always contains the most recently generated DEFAULT UNIQUE value, and is not reset between queries.

fbsql_list_dbs

(PHP 4 >= 4.0.6)

fbsql_list_dbs --  List databases available on a FrontBase server

Description

resource fbsql_list_dbs ( [resource link_identifier])

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

Exemplo 1. fbsql_list_dbs() example

$link = fbsql_connect('localhost', 'myname', 'secret');
$db_list = fbsql_list_dbs($link);

while ($row = fbsql_fetch_object($db_list)) {
    echo $row->Database . "\n";
}

The above example would produce the following output:

database1
database2
database3
...

Nota: The above code would just as easily work with fbsql_fetch_row() or other similar functions.

fbsql_list_fields

(PHP 4 >= 4.0.6)

fbsql_list_fields -- List FrontBase result fields

Description

resource fbsql_list_fields ( string database_name, string table_name [, resource link_identifier])

fbsql_list_fields() retrieves information about the given tablename. Arguments are the database name and the table name. A result pointer is returned which can be used with fbsql_field_flags(), fbsql_field_len(), fbsql_field_name(), and fbsql_field_type().

A result identifier is a positive integer. The function returns FALSE if an error occurs. A string describing the error will be placed in $phperrmsg, and unless the function was called as @fbsql() then this error string will also be printed out.

Exemplo 1. fbsql_list_fields() example

$link = fbsql_connect('localhost', 'myname', 'secret');

$fields = fbsql_list_fields("database1", "table1", $link);
$columns = fbsql_num_fields($fields);

for ($i = 0; $i < $columns; $i++) {
    echo fbsql_field_name($fields, $i) . "\n";;
}

The above example would produce the following output:

field1
field2
field3
...

fbsql_list_tables

(PHP 4 >= 4.0.6)

fbsql_list_tables -- List tables in a FrontBase database

Description

resource fbsql_list_tables ( string database [, resource link_identifier])

fbsql_list_tables() takes a database name and returns a result pointer much like the fbsql_db_query() function. The fbsql_tablename() function should be used to extract the actual table names from the result pointer.

fbsql_next_result

(PHP 4 >= 4.0.6)

fbsql_next_result --  Move the internal result pointer to the next result

Description

bool fbsql_next_result ( resource result_id)

When sending more than one SQL statement to the server or executing a stored procedure with multiple 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 existing result set and prepare to fetch the words from the new result set. The function will return TRUE if an additional result set was available or FALSE otherwise.

Exemplo 1. fbsql_next_result() example

<?php
    $link = fbsql_connect ("localhost", "_SYSTEM", "secret");
    fbsql_select_db("MyDB", $link);
    $SQL = "Select * from table1; select * from table2;";
    $rs = fbsql_query($SQL, $link);
    do {
        while ($row = fbsql_fetch_row($rs)) {
        }
    } while (fbsql_next_result($rs));
    fbsql_free_result($rs);
    fbsql_close ($link);
?>

fbsql_num_fields

(PHP 4 >= 4.0.6)

fbsql_num_fields -- Get number of fields in result

Description

int fbsql_num_fields ( resource result)

fbsql_num_fields() returns the number of fields in a result set.

See also: fbsql_db_query(), fbsql_query(), fbsql_fetch_field(), and fbsql_num_rows().

fbsql_num_rows

(PHP 4 >= 4.0.6)

fbsql_num_rows -- Get number of rows in result

Description

int fbsql_num_rows ( resource result)

fbsql_num_rows() returns the number of rows in a result set. This command is only valid for SELECT statements. To retrieve the number of rows returned from a INSERT, UPDATE or DELETE query, use fbsql_affected_rows().

Exemplo 1. fbsql_num_rows() example

<?php

$link = fbsql_connect("localhost", "username", "password"); 
fbsql_select_db("database", $link);

$result = fbsql_query("SELECT * FROM table1;", $link); 
$num_rows = fbsql_num_rows($result); 

echo "$num_rows Rows\n";

?>

See also: fbsql_affected_rows(), fbsql_connect(), fbsql_select_db(), and fbsql_query().

fbsql_password

(PHP 4 >= 4.0.6)

fbsql_password -- Get or set the user password used with a connection

Description

string fbsql_password ( resource link_identifier [, string password])

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

fbsql_pconnect

(PHP 4 >= 4.0.6)

fbsql_pconnect --  Open a persistent connection to a FrontBase Server

Description

resource fbsql_pconnect ( [string hostname [, string username [, string password]]])

Returns: A positive FrontBase persistent link identifier on success, or FALSE on error.

fbsql_pconnect() establishes a connection to a FrontBase server. The following defaults are assumed for missing optional parameters: host = 'localhost', username = "_SYSTEM" and password = empty password.

fbsql_pconnect() acts very much like fbsql_connect() with two major differences.

To set Frontbase server port number, use fbsql_select_db().

First, when connecting, the function would first try to find a (persistent) link that's already open with the same host, username and password. If one is found, an identifier for it will be returned instead of opening a new connection.

Second, the connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use.

This type of links is therefore called 'persistent'.

fbsql_query

(PHP 4 >= 4.0.6)

fbsql_query -- Send a FrontBase query

Description

resource fbsql_query ( string query [, resource link_identifier])

fbsql_query() sends a query to the currently active database on the server that's associated with the specified link identifier. If link_identifier isn't specified, the last opened link is assumed. If no link is open, the function tries to establish a link as if fbsql_connect() was called with no arguments, and use it.

Nota: The query string shall always end with a semicolon.

fbsql_query() returns TRUE (non-zero) or FALSE to indicate whether or not the query succeeded. A return value of TRUE means that the query was legal and could be executed by the server. It does not indicate anything about the number of rows affected or returned. It is perfectly possible for a query to succeed but affect no rows or return no rows.

The following query is syntactically invalid, so fbsql_query() fails and returns FALSE:

Exemplo 1. fbsql_query() example

<?php
$result = fbsql_query ("SELECT * WHERE 1=1")
    or die ("Invalid query");
?>

The following query is semantically invalid if my_col is not a column in the table my_tbl, so fbsql_query() fails and returns FALSE:

Exemplo 2. fbsql_query() example

<?php
$result = fbsql_query ("SELECT my_col FROM my_tbl")
    or die ("Invalid query");
?>

fbsql_query() will also fail and return FALSE if you don't have permission to access the table(s) referenced by the query.

Assuming the query succeeds, you can call fbsql_num_rows() to find out how many rows were returned for a SELECT statement or fbsql_affected_rows() to find out how many rows were affected by a DELETE, INSERT, REPLACE, or UPDATE statement.

For SELECT statements, fbsql_query() returns a new result identifier that you can pass to fbsql_result(). When you are done with the result set, you can free the resources associated with it by calling fbsql_free_result(). Although, the memory will automatically be freed at the end of the script's execution.

See also: fbsql_affected_rows(), fbsql_db_query(), fbsql_free_result(), fbsql_result(), fbsql_select_db(), and fbsql_connect().

fbsql_read_blob

(PHP 4 >= 4.2.0)

fbsql_read_blob -- Read a BLOB from the database

Description

string fbsql_read_blob ( string blob_handle [, resource link_identifier])

Returns: A string containing the BLOB specified by blob_handle.

fbsql_read_blob() reads BLOB data from the database. If a select statement contains BLOB and/or BLOB columns FrontBase will return the data directly when data is fetched. This default behavior can be changed with fbsql_set_lob_mode() so the fetch functions will return handles to BLOB and CLOB data. If a handle is fetched a user must call fbsql_read_blob() to get the actual BLOB data from the database.

Exemplo 1. fbsql_read_blob() example

<?php
    $link = fbsql_pconnect ("localhost", "_SYSTEM", "secret")
        or die ("Could not connect");
    $sql = "SELECT BLOB_COLUMN FROM BLOB_TABLE;";
    $rs = fbsql_query($sql, $link);
    $row_data = fbsql_fetch_row($rs);
    // $row_data[0] will now contain the blob data for teh first row
    fbsql_free_result($rs);
    
    $rs = fbsql_query($sql, $link);
    fbsql_set_lob_mode($rs, FBSQL_LOB_HANDLE);
    $row_data = fbsql_fetch_row($rs);
    // $row_data[0] will now contain a handle to the BLOB data in the first row
    $blob_data = fbsql_read_blob($row_data[0]);
    fbsql_free_result($rs);
    
?>

See also: fbsql_create_blob(), fbsql_read_blob(), fbsql_read_clob(), and fbsql_set_lob_mode().

fbsql_read_clob

(PHP 4 >= 4.2.0)

fbsql_read_clob -- Read a CLOB from the database

Description

string fbsql_read_clob ( string clob_handle [, resource link_identifier])

Returns: A string containing the CLOB specified by clob_handle.

fbsql_read_clob() reads CLOB data from the database. If a select statement contains BLOB and/or CLOB columns FrontBase will return the data directly when data is fetched. This default behavior can be changed with fbsql_set_lob_mode() so the fetch functions will return handles to BLOB and CLOB data. If a handle is fetched a user must call fbsql_read_clob() to get the actual CLOB data from the database.

Exemplo 1. fbsql_read_clob() example

<?php
    $link = fbsql_pconnect ("localhost", "_SYSTEM", "secret")
        or die ("Could not connect");
    $sql = "SELECT CLOB_COLUMN FROM CLOB_TABLE;";
    $rs = fbsql_query($sql, $link);
    $row_data = fbsql_fetch_row($rs);
    // $row_data[0] will now contain the clob data for teh first row
    fbsql_free_result($rs);
    
    $rs = fbsql_query($sql, $link);
    fbsql_set_lob_mode($rs, FBSQL_LOB_HANDLE);
    $row_data = fbsql_fetch_row($rs);
    // $row_data[0] will now contain a handle to the CLOB data in the first row
    $clob_data = fbsql_read_clob($row_data[0]);
    fbsql_free_result($rs);
    
?>

See also: fbsql_create_blob(), fbsql_read_blob(), fbsql_read_clob(), and fbsql_set_lob_mode().

fbsql_result

(PHP 4 >= 4.0.6)

fbsql_result -- Get result data

Description

mixed fbsql_result ( resource result, int row [, mixed field])

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 field's name (tabledname.fieldname). If the column name has been aliased ('select foo as bar from...'), use the alias instead of the column name.

When working on large result sets, you should consider using one of the functions that fetch an entire row (specified below). As these functions return the contents of multiple cells in one function call, they're MUCH quicker than fbsql_result(). Also, note that specifying a numeric offset for the field argument is much quicker than specifying a fieldname or tablename.fieldname argument.

Calls to fbsql_result() should not be mixed with calls to other functions that deal with the result set.

Recommended high-performance alternatives: fbsql_fetch_row(), fbsql_fetch_array(), and fbsql_fetch_object().

fbsql_rollback

(PHP 4 >= 4.0.6)

fbsql_rollback -- Rollback a transaction to the database

Description

bool fbsql_rollback ( [resource link_identifier])

Retorna TRUE em caso de sucesso ou FALSE em falhas.

fbsql_rollback() ends the current transaction by rolling back all statements issued since last commit. This command is only needed if autocommit is set to false.

See also: fbsql_autocommit() and fbsql_commit()

fbsql_select_db

(PHP 4 >= 4.0.6)

fbsql_select_db -- Select a FrontBase database

Description

bool fbsql_select_db ( string database_name [, resource link_identifier])

Returns: TRUE on success, FALSE on error.

fbsql_select_db() sets the current active database on the server that's associated with the specified link identifier. If no link identifier is specified, the last opened link is assumed. If no link is open, the function will try to establish a link as if fbsql_connect() was called, and use it.

The client contacts FBExec to obtain the port number to 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. The FrontBase server can be stared as FRontBase -FBExec=No -port=<port number> <database name>.

Every subsequent call to fbsql_query() will be made on the active database.

if the database is protected with a database password, the user must call fbsql_database_password() before selecting the database.

See also: fbsql_connect(), fbsql_pconnect(), fbsql_database_password() and fbsql_query().

fbsql_set_lob_mode

(PHP 4 >= 4.2.0)

fbsql_set_lob_mode --  Set the LOB retrieve mode for a FrontBase result set

Description

bool fbsql_set_lob_mode ( resource result, string database_name)

Returns: TRUE on success, FALSE on error.

fbsql_set_lob_mode() sets the mode for retrieving LOB data from the database. When BLOB and CLOB data is stored in FrontBase it can be stored direct or indirect. Direct stored LOB data will always be fetched no matter the setting of the lob mode. If the LOB data is less than 512 bytes it will always be stored directly.

  • FBSQL_LOB_DIRECT - LOB data is retrieved directly. When data is fetched from the database with fbsql_fetch_row(), and other fetch functions, all CLOB and BLOB columns will be returned as ordinary columns. This is the default value on a new FrontBase result.

  • FBSQL_LOB_HANDLE - LOB data is retrieved as handles to the data. When data is fetched from the database with fbsql_fetch_row (), and other fetch functions, LOB data will be returned as a handle to the data if the data is stored indirect or the data if it is stored direct. If a handle is returned it will be a 27 byte string formatted as "@'000000000000000000000000'".

See also: fbsql_create_blob(), fbsql_create_clob(), fbsql_read_blob(), and fbsql_read_clob().

fbsql_set_transaction

(PHP 4 >= 4.2.0)

fbsql_set_transaction --  Set the transaction locking and isolation

Description

void fbsql_set_transaction ( resource link_identifier, int Locking, int Isolation)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

fbsql_start_db

(PHP 4 >= 4.0.6)

fbsql_start_db -- Start a database on local or remote server

Description

bool fbsql_start_db ( string database_name [, resource link_identifier])

Retorna TRUE em caso de sucesso ou FALSE em falhas.

fbsql_start_db()

See also: fbsql_db_status() and fbsql_stop_db().

fbsql_stop_db

(PHP 4 >= 4.0.6)

fbsql_stop_db -- Stop a database on local or remote server

Description

bool fbsql_stop_db ( string database_name [, resource link_identifier])

Retorna TRUE em caso de sucesso ou FALSE em falhas.

fbsql_stop_db()

See also: fbsql_db_status() and fbsql_start_db().

fbsql_tablename

(PHP 4 >= 4.2.0)

fbsql_tablename -- Get table name of field

Description

string fbsql_tablename ( resource result, int i)

fbsql_tablename() takes a result pointer returned by the fbsql_list_tables() function as well as an integer index and returns the name of a table. The fbsql_num_rows() function may be used to determine the number of tables in the result pointer.

Exemplo 1. fbsql_tablename() example

<?php 
fbsql_connect ("localhost", "_SYSTEM", "");
$result = fbsql_list_tables ("wisconsin");
$i = 0;
while ($i < fbsql_num_rows ($result)) {
    $tb_names[$i] = fbsql_tablename ($result, $i);
    echo $tb_names[$i] . "<BR>";
    $i++;
}
?>

fbsql_username

(PHP 4 >= 4.0.6)

fbsql_username -- Get or set the host user used with a connection

Description

string fbsql_username ( resource link_identifier [, string username])

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

fbsql_warnings

(PHP 4 >= 4.0.6)

fbsql_warnings -- Enable or disable FrontBase warnings

Description

bool fbsql_warnings ( [bool OnOff])

Returns TRUE if warnings is turned on otherwise FALSE.

fbsql_warnings() enables or disables FrontBase warnings.

XXIX. filePro functions

Introdução

These functions allow read-only access to data stored in filePro databases.

filePro is a registered trademark of fP Technologies, Inc. You can find more information about filePro at http://www.fptech.com/.


Instalação

filePro support in PHP is not enabled by default. To enable the bundled read-only filePro support you need to use the--enable-filepro configuration option when compiling PHP.

Índice
filepro_fieldcount -- Find out how many fields are in a filePro database
filepro_fieldname -- Gets the name of a field
filepro_fieldtype -- Gets the type of a field
filepro_fieldwidth -- Gets the width of a field
filepro_retrieve -- Retrieves data from a filePro database
filepro_rowcount -- Find out how many rows are in a filePro database
filepro -- Read and verify the map file

filepro_fieldcount

(PHP 3, PHP 4 )

filepro_fieldcount -- Find out how many fields are in a filePro database

Description

int filepro_fieldcount ( void)

Returns the number of fields (columns) in the opened filePro database.

See also filepro().

filepro_fieldname

(PHP 3, PHP 4 )

filepro_fieldname -- Gets the name of a field

Description

string filepro_fieldname ( int field_number)

Returns the name of the field corresponding to field_number.

filepro_fieldtype

(PHP 3, PHP 4 )

filepro_fieldtype -- Gets the type of a field

Description

string filepro_fieldtype ( int field_number)

Returns the edit type of the field corresponding to field_number.

filepro_fieldwidth

(PHP 3, PHP 4 )

filepro_fieldwidth -- Gets the width of a field

Description

int filepro_fieldwidth ( int field_number)

Returns the width of the field corresponding to field_number.

filepro_retrieve

(PHP 3, PHP 4 )

filepro_retrieve -- Retrieves data from a filePro database

Description

string filepro_retrieve ( int row_number, int field_number)

Returns the data from the specified location in the database.

Nota: Quando o safe-mode está ativo, o PHP verifica se o(s) arquivo(s) e/ou diretório(s) que serão afetados por esta operação tem o mesmo UID (proprietário) do script que está sendo executado.

filepro_rowcount

(PHP 3, PHP 4 )

filepro_rowcount -- Find out how many rows are in a filePro database

Description

int filepro_rowcount ( void)

Returns the number of rows in the opened filePro database.

Nota: Quando o safe-mode está ativo, o PHP verifica se o(s) arquivo(s) e/ou diretório(s) que serão afetados por esta operação tem o mesmo UID (proprietário) do script que está sendo executado.

See also filepro().

filepro

(PHP 3, PHP 4 )

filepro -- Read and verify the map file

Description

bool filepro ( string directory)

This reads and verifies the map file, storing the field count and info.

No locking is done, so you should avoid modifying your filePro database while it may be opened in PHP.

Nota: Quando o safe-mode está ativo, o PHP verifica se o(s) arquivo(s) e/ou diretório(s) que serão afetados por esta operação tem o mesmo UID (proprietário) do script que está sendo executado.

XXX. Filesystem (Sistema de arquivos)

Introdução


Requisitos

Nenhuma biblioteca externa é necessária para compilar esta extensão.


Instalação

Não há nenhuma instalação nescessária para utilizar estas funções, elas fazem parte do núcleo do PHP.


Configuração durante execução

O comportamento dessas funções podem ser modificado pelas configurações do php.ini.

Tabela 1. Opções de configuração do Filesystem e Streams

Nome Padrão Alterável
allow_url_fopen "1" PHP_INI_ALL
user_agent NULL PHP_INI_ALL
default_socket_timeout "60" PHP_INI_ALL
from NULL ??
auto_detect_line_endings "Off" PHP_INI_ALL

Descrição resumida das diretivas de configuração.

allow_url_fopen boolean

Esta opção ativa o dispositivo URL fopen wrappers que permite o acesso a objetos URL como arquivos. São disponibilizados por padrão wrappers para acesso de arquivos remotos utilizando os protocolos FTP ou HTTP, e algumas estensões como a zlib podem registar wrappers adicionais.

Nota: Esta opção foi introduzida imediatamente antes da liberação da versão 4.0.3. Até essa versão e incluindo a 4.0.3, você somente podia desabilitar este recurso na compilação, usando a opção --disable-url-fopen-wrapper.

Atenção

Nas versões Windows anterioes a PHP 4.3, as funções seguintes não suportavam acesso de arquivos remotos: include(), include_once(), require(), require_once() e as funções imagecreatefromXXX da extensão Referência XLI, Image functions.

user_agent string

Define o user agent que o PHP irá enviar.

default_socket_timeout integer

Timeout padrão (em segundos) para streams baseados em socket.

Nota: Esta opção de configuração foi incluida no PHP 4.3.

from="joe@example.com" string

Define a senha do FTP anonimo (seu endereço de e-mail).

auto_detect_line_endings boolean

Quando ativo, o PHP irá examinar os dados lidos por fgets() e file() para verificar se está sendo utilizado a convensão de fim de linha Unix, MS-DOS ou Macintosh.

Isto ativa a interoperabilidade do PHP com sistemas Macintosh, mas seu padrão é Off, porque isso causa uma pequena perda de performance na detecção da convenção de fim de linha num primeiro momento e porque as pessoas que utilizam o fim de linha como separadores de itens sob sistemas Unix podem experimentar problemas de falta de compatibilidade.

Nota: Esta opção de configuração foi introduzida no PHP 4.3.


Tipos Resource


Constantes Predefinidas

Esta extensão não possui nenhuma constante.


Veja Também

Para funções relacionadas, veja também as seções Deritório e Execução de Programas.

Para uma lista e descrição dos vários wrappers URL que podem ser utilizados como arquivos remotos, veja em Apêndice I.

Índice
basename -- Retorna a parte nome do arquivo do caminho/path
chgrp -- Modifica o grupo do arquivo
chmod -- Modifica as permissões do arquivo
chown -- Modifica o dono do arquivo
clearstatcache -- Limpa as informações em cache de arquivos
copy -- Copia arquivo
delete -- Veja unlink() ou unset()
dirname -- Retorna o componente diretório de um caminho/path
disk_free_space -- Retorna o espaço disponivel no diretório
disk_total_space -- Retorna o tamanho total do diretório
diskfreespace -- Sinônimo de disk_free_space()
fclose -- Fecha um ponteiro de arquivo aberto
feof -- Testa pelo fim-de-arquivo (eof) em um ponteiro de arquivo
fflush -- Força a liberação do buffer para um arquivo
fgetc -- Le um caracter do ponteiro de arquivo
fgetcsv -- Le uma linha do ponteiro de arquivos e a interpreta por campos CSV
fgets -- Le uma linha de um ponteiro de arquivo
fgetss -- Ler uma linha de um ponteiro de arquivo e retira as tags HTML
file_exists -- Checa se um arquivo existe
file_get_contents -- Le todo o conteúdo de um arquivo para uma string
file -- Le um arquivo inteiro para um array
fileatime -- Obtém o último horário de acesso do arquivo
filectime -- Ler o tempo de modificação do inode do arquivo
filegroup -- Le o grupo do arquivo
fileinode -- Le o inode do arquivo
filemtime -- Le o tempo de modificação do arquivo
fileowner -- Le o dono (owner) do arquivo
fileperms -- Ler as permissões do arquivo
filesize -- Ler o tamanho do arquivo
filetype -- Le o tipo de arquivo (file type)
flock -- Monitor de travamento de arquivos portátil
fnmatch -- Verifica se um nome de arquivo bate com padrão (wildcards)
fopen -- Abri um arquivo ou uma URL
fpassthru -- Imprime todo os dados restantes de um ponteiro de arquivo
fputs -- Escrever para um ponteiro de arquivo
fread -- Leitura binary-safe de arquivo
fscanf -- Interpreta a leitura de um arquivo de acordo com um formato
fseek -- Procura (seeks) em um ponteiro de arquivo
fstat --  Ler a informação sobre um arquivo usando um ponteiro de arquivo aberto
ftell -- Diz ao ponteiro de arquivo a posição de leitura/gravação
ftruncate --  Corta um arquivo para um tamanho especificado.
fwrite -- Gravação em arquivos binary-safe
glob -- Localiza diretórios/arquivos que combinem com o padrão
is_dir -- Diz se o caminho é um diretório
is_executable -- Diz se um arquivo é executável
is_file -- Diz se o arquivo é um arquivo comum (não é diretório)
is_link -- Diz se o arquivo é um link simbólico (symbolic link)
is_readable --  Diz se o arquivo é legivel (readable)
is_uploaded_file -- Diz se o arquivo foi uploaded via HTTP POST
is_writable -- Diz se pode-se escrever para o arquivo(writable)
is_writeable -- Diz se pode-se escrever para o arquivo(writable)
link -- Criando um hard link
linkinfo -- Ler informações sobre um link
lstat -- Obtem informações sobre um arquivo ou link simbólico
mkdir -- Criar um diretório
move_uploaded_file -- Move um arquivo carregado para uma nova localização
parse_ini_file -- Interpreta um arquivo de configuração
pathinfo -- Retorna informação sobre o path de um arquivo
pclose -- Fecha um processo de um ponteiro de arquivo
popen -- Abre um processo como ponteiro de arquivo
readfile -- Le o conteúdo de um arquivo
readlink -- Retornar o alvo de um link simbólico
realpath -- Retorna o path absoluto canonicalizado
rename -- Renomear um arquivo
rewind -- Reinicializa a posição do ponteiro de arquivos para o início
rmdir -- Remove um diretório
set_file_buffer -- Sinônimo de stream_set_write_buffer()
stat -- Obtem informações sobre um arquivo
symlink -- Cria um link simbólico
tempnam -- Cria um nome de arquivo único
tmpfile -- Cria um arquivo temporário
touch -- Muda o tempo de modificação do arquivo
umask -- Modificar a umask atual
unlink -- Deleta um arquivo

basename

(PHP 3, PHP 4 )

basename -- Retorna a parte nome do arquivo do caminho/path

Descrição

string basename ( string path [, string sufixo])

Dado uma string contendo um caminho para um arquivo, essa função irá retornar o nome base do arquivo. Se o nome do arquivo termina com o sufixo, este também será retirado.

No Windows, tanto a barra (/) quanto a barra invertida (\) são usadas como caracter de separacao do caminho. Em outros ambientes, somente a barra (/).

Exemplo 1. exemplo do basename()

$caminho = "/home/httpd/html/index.php";
$arquivo = basename ($caminho);        // $arquivo = "index.php"
$arquivo = basename ($caminho,".php"); // $arquivo = "index"

Nota: O parametro sufixo foi adicionado no PHP 4.1.0.

Veja também: dirname()

chgrp

(PHP 3, PHP 4 )

chgrp -- Modifica o grupo do arquivo

Descrição

int chgrp ( string arquivo, mixed grupo)

Tenta modificar o grupo do arquivo para o grupo (nome ou número). Somente o superusuário pode mudar o grupo de um arquivo arbitrário; outros usuários somente podem mudar o grupo de um arquivo para qualquer grupo qual o usuário pertença.

Retorna TRUE em caso de sucesso ou FALSE em falhas.

Veja também chown() e chmod().

chmod

(PHP 3, PHP 4 )

chmod -- Modifica as permissões do arquivo

Descrição

int chmod ( string arquivo, int modo)

Tenta mudar as permissões do arquivo especificado por arquivo para o dado em modo.

Note que modo não é necessariamente um número octal, então strings (como "g+w") não funcionarão. Para garantir que a operação seja bem sucedida é necessário prefixar modo com zero (0):

chmod ("/arquivo/diretorio", 755);   // decimal; provavelmente incorreto
chmod ("/arquivo/diretorio", "u+rwx,go+rx"); // string; incorreto
chmod ("/arquivo/diretorio", 0755);  // octal; representação correta do modo

Retorna TRUE em caso de sucesso ou FALSE em falhas.

Veja também chown() e chgrp().

chown

(PHP 3, PHP 4 )

chown -- Modifica o dono do arquivo

Descrição

int chown ( string arquivo, mixed usuario)

Tenta modificar o dono do arquivo para o usuario (nome ou número). Somente o superusuário pode modificar o dono de um arquivo.

Retorna TRUE em caso de sucesso ou FALSE em falhas.

Veja também chmod().

clearstatcache

(PHP 3, PHP 4 )

clearstatcache -- Limpa as informações em cache de arquivos

Descrição

void clearstatcache ( void)

Quando você chama stat(), lstat() ou qualquer uma das funções afetadas (listadas abaixo), o PHP mantém em cache as informações que essas funções retornam para melhoria de performance. Entretanto, em certos casos você pode precisar limpar as informações cacheadas. Por exemplo, se um mesmo arquivo é verificado várias vezes em um único script, e esse arquivo corre o risco de ser apagado ou modificado durante a operação do script, você precisa limpar os dados do cache. Nesses casos, você pode utilizar a função clearstatcache() para limpar todas as informações que o PHP mantém sobre um arquivo.

Nota: Esta função guarda infomações sobre arquivos específicos, de forma que você somente precisa chamar clearstatcache() se você estiver realizando várias operações sobre o mesmo arquivo e necessita que a informação sobre esse arquivo em particular não seja cacheada.

As funções afetadas são stat(), lstat(), file_exists(), is_writable(), is_readable(), is_executable(), is_file(), is_dir(), is_link(), filectime(), fileatime(), filemtime(), fileinode(), filegroup(), fileowner(), filesize(), filetype(), e fileperms().

copy

(PHP 3, PHP 4 )

copy -- Copia arquivo

Descrição

int copy ( string origem, string destino)

Faz uma cópia de um arquivo. Retorna TRUE se a copia é obtida com sucesso, caso contrário FALSE.

Exemplo 1. exemplo do copy()

if (!copy($arquivo, $arquivo.'.bak')) {
    print ("erro copiando arquivo $arquivo...<br>\n");
}

Nota: A partir do PHP 4.0.3, ambos origem e destino podem ser URLs se "fopen wrappers" estiver ativo. Veja fopen() para mais detalhes. Se dest é uma URL, a operação de cópia pode falhar se o wrapper não suportar a sobrescrita de arquivos existentes.

Atenção

Se o arquivo destino já existir, ele será sobrescrito.

See also move_uploaded_file(), rename(), e a seção do manual sobre manipulação de uploads de arquivos.

delete

(no version information, might be only in CVS)

delete -- Veja unlink() ou unset()

Descrição

void delete ( string file)

Esta é uma seção falsa do manual, criada para satisfazer as pessoas que estão procurando por unlink() ou unset() no lugar errado.

Veja também: unlink() para deletar arquivos, unset() para apagar váriaveis.

dirname

(PHP 3, PHP 4 )

dirname -- Retorna o componente diretório de um caminho/path

Descrição

string dirname ( string path)

Dada uma string contendo um caminho para um arquivo, esta função irá retornar o nome do diretório.

No Windows, tanto barra (/) quanto a barra invertida (\) são usadas como caracter separador no path. Em outros ambientes é utilizado a barra (/).

Exemplo 1. exemplo do dirname()

$path = "/etc/passwd";
$file = dirname ($path); // $file = "/etc"

Nota: A partir do PHP 4.0.3, dirname() foi modificada para ser conformante com o POSIX. Essencialemente, isto significa que se não há barras no path, um ponto ('.') é retornado, indicando o diretório atual. Antes, a string retornada era o path com todos os /componente removidos. Ou seja, você receberá uma barra ou ponto de dirname() em situações onde a funcionalidade anterior devolveria uma string vazia.

Veja também: basename(), pathinfo() e realpath().

disk_free_space

(PHP 4 >= 4.1.0)

disk_free_space -- Retorna o espaço disponivel no diretório

Descrição

float disk_free_space ( string diretorio)

Dado uma string contendo um diretório, esta função retornará o numero de bytes disponíveis no sistema de arquivos ou partição de disco.

Exemplo 1. exemplo de disk_free_space()

$df = disk_free_space("/"); // $df contém o número de bytes.
                            // disponível em "/"

disk_total_space

(PHP 4 >= 4.1.0)

disk_total_space -- Retorna o tamanho total do diretório

Descrição

float disk_total_space ( string diretorio)

Dado uma string contendo um diretório, esta função retornará o numero total de bytes do sistema de arquivos ou a partição de disco.

Exemplo 1. disk_total_space() example

$df = disk_total_space("/"); // $df contém o numero total de
                             // bytes disponíveis em "/"

diskfreespace

(PHP 3>= 3.0.7, PHP 4 )

diskfreespace -- Sinônimo de disk_free_space()

Descrição

float diskfreespace ( string diretório)

Este é um sinônimo obsoleto para a função disk_free_space(). Ultilize aquela função ao invez.

fclose

(PHP 3, PHP 4 )

fclose -- Fecha um ponteiro de arquivo aberto

Descrição

bool fclose ( int fp)

O arquivo apontado por fp é fechado.

Retorna TRUE em caso de sucesso ou FALSE em falhas.

O ponteiro para o arquivo tem que ser válido e tem que apontar para um arquivo aberto por fopen() ou fsockopen().

Exemplo 1. Exemplo fclose()

<?php

  $fp = fopen('qualquerarquivo.txt', 'r');
  
  fclose($fp);
  
?>

feof

(PHP 3, PHP 4 )

feof -- Testa pelo fim-de-arquivo (eof) em um ponteiro de arquivo

Descrição

int feof ( int fp)

Retorna TRUE se o ponteiro estiver no fim do arquivo (eof) ou um erro ocorrer. Caso contrário retorna FALSE.

O ponteiro para o arquivo tem que ser válido e tem que apontar para um arquivo aberto com sucesso por fopen(), popen() ou fsockopen().

fflush

(PHP 4 >= 4.0.1)

fflush -- Força a liberação do buffer para um arquivo

Descrição

int fflush ( int fp)

Esta função força a escrita de toda saída cacheada no buffer do arquivo apontado pelo recurso fp. Retorna TRUE se obtiver sucesso e caso contrário FALSE.

O ponteiro de arquivo tem que ser válido e apontar para um arquivo que foi aberto com sucesso por fopen(), popen() ou fsockopen().

fgetc

(PHP 3, PHP 4 )

fgetc -- Le um caracter do ponteiro de arquivo

Descrição

string fgetc ( int fp)

Retorna uma string contendo somente um caracter lido do arquivo apontado por fp. Retorna FALSE no fim do arquivo (eof).

O ponteiro de arquivo tem que ser válido e apontar para um arquivo aberto com sucesso por fopen(), popen(), ou fsockopen().

Veja também fread(), fopen(), popen(), fsockopen() e fgets().

fgetcsv

(PHP 3>= 3.0.8, PHP 4 )

fgetcsv -- Le uma linha do ponteiro de arquivos e a interpreta por campos CSV

Descrição

array fgetcsv ( int fp, int length [, string delimiter [, string enclosure]])

Similar à fgets() exceto que fgetcsv() interpreta a linha que lê por campos no formato CSV e retorna um vetor (array) contendo os campos lidos. O terceiro parâmetro delimiter (opcional) tem como padrão a vígula. A opção enclosure não pode ser null, e está limitada a um caracter. Se enclosure tiver mais que um carcater, somente o primeiro será utilizado.

Nota: O parâmetro enclosure foi acrescentado no PHP 4.3.0.

O parâmetro fp tem que ser um ponteiro de arquivo válido para um arquivo aberto com sucesso por fopen(), popen() ou fsockopen().

length tem que ser maior do que a maior linha a ser encontrada no arquivo CSV (incluindo caracteres de terminação de linha).

fgetcsv() retorna FALSE ao encontrar um erro, incluindo fim de arquivo (eof).

Nota: Uma linha em branco em um arquivo CSV será retornada como um array contendo um único campo nulo (null), e não será tratado como um erro.

Exemplo 1. Lê e imprime todo o conteúdo de um arquivo CSV

<?php
$row = 1;
$fp = fopen ("test.csv","r");
while ($data = fgetcsv ($fp, 1000, ",")) {
    $num = count ($data);
    print "<p> $num campos na linha $row: <br>";
    $row++;
    for ($c=0; $c < $num; $c++) {
        print $data[$c] . "<br>";
    }
}
fclose ($fp);
?>

Veja também explode(), file() e pack()

fgets

(PHP 3, PHP 4 )

fgets -- Le uma linha de um ponteiro de arquivo

Descrição

string fgets ( int fp [, int length])

Retorna uma string com até length - 1 bytes lidos do arquivo apontado por fp. A leitura acaba quando length - 1 bytes foram lidos, encontra-se um fim de linha (newline) (que é incluido no valor retornado) ou no fim de arquivo (eof) (o que acontecer primeiro). Se nenhum length for informado, o default é 1Kb, ou 1024 bytes.

Se um erro ocorrer, retorna FALSE.

Equívocos comuns:

Pessoas acostumadas a semântica do fgets em 'C' devem notar a diferenca em como o fim do arquivo (EOF) é retornado.

O ponteiro para o arquivo deve ser válido e deve apontar para um arquivo aberto com sucesso por fopen(), popen() ou fsockopen().

Um simples exemplo segue:

Exemplo 1. Lendo um arquivo linha a linha

$fd = fopen ("/tmp/arquivodeentrada.txt", "r");
while (!feof ($fd)) {
    $buffer = fgets($fd, 4096);
    echo $buffer;
}
fclose ($fd);

Nota: O parâmetro length se tornou opcional a partir do PHP 4.2.0, e se omitido, tem default para 1024 bytes para o comprimento da linha. A partir do PHP 4.3, omitindo length fará continuar a leitura a partir do stream até encontrar o fim da linha. Se a maioria das linhas no arquivo forem todar maiores que 8 Kb, haverá mais eficiência de recursos se seus scripts informarem o comprimento máximo das linhas.

Nota: Esta função é binary safe a partir do PHP 4.3. Versões anteriores não são seguras para dados binários.

Nota: Se você está tendo problemas com o PHP no reconhecimento do final de linha quando criando ou lendo arquivos num computador Macintosh, você pode habilitar a opção auto_detect_line_endings.

Veja também fread(), fopen(), popen(), fgetc(), fsockopen() e socket_set_timeout().

fgetss

(PHP 3, PHP 4 )

fgetss -- Ler uma linha de um ponteiro de arquivo e retira as tags HTML

Descrição

string fgetss ( int fp, int length [, string allowable_tags])

Idêntico a fgets(), exceto que fgetss tenta retirar qualquer tag HTML ou PHP do texto que ele lê.

Você pode utilizar o terceiro parâmetro opcional para especificar quais tags não devem ser retiradas.

Nota: allowable_tags foi adicionado no PHP 3.0.13, PHP 4.0.0.

Nota: Se você está tendo problemas com o PHP no reconhecimento do final de linha quando criando ou lendo arquivos num computador Macintosh, você pode habilitar a opção auto_detect_line_endings.

Veja também fgets(), fopen(), fsockopen(), popen() e strip_tags().

file_exists

(PHP 3, PHP 4 )

file_exists -- Checa se um arquivo existe

Descrição

bool file_exists ( string nomedoarquivo)

Retorna TRUE se o arquivo expecificado por nomedoarquivo existe; FALSE caso contrário.

Esta função não irá funcionar em arquivos remotos; o arquivo para ser examinado tem que ser accessivel pelo filesystem do servidor.

Os resultados desta função são guardados em cache. Veja clearstatcache() para mais detalhes.

Utilizando compartilhamentos Windows: No Windows, use //computername/share/filename ou \\\\computername\share\filename para checar arquivos em compartilhamentos de rede.

Exemplo 1. Testando se um arquivo existe

<?php
$filename = '/caminho/para/qualquer.txt';

if (file_exists($filename)) {
    print "O arquivo $filename existe";
} else {
    print "O arquivo $filename não existe";
}
?>

Veja também is_readable(), is_writable(), is_file() e file().

file_get_contents

(PHP 4 >= 4.3.0)

file_get_contents -- Le todo o conteúdo de um arquivo para uma string

Descrição

string file_get_contents ( string filename [, int use_include_path])

Idêntico a readfile(), exceto que file_get_contents() retorna o arquivo em uma string.

Nota: Esta função é compatível com dados binários

Dica: Você pode usar uma URL com esta função se fopen wrappers estiver habilitado. Veja fopen() para mais detalhes em como especificar o nome do arquivo e Apêndice I para uma lista de protololos URL suportados.

Veja também: fgets(), file(), fread(), include() e readfile().

file

(PHP 3, PHP 4 )

file -- Le um arquivo inteiro para um array

Descrição

array file ( string filename [, int use_include_path])

Idêntico a readfile(), exceto que file() retorna o arquivo em um array. Cada elemento do array corresponde a uma linha no arquivo, inclusive com o caracter de nova linha. Em caso de falha, file() retorna FALSE.

Nota: Cada linha do array resultante terá os caracteres de fim de linha, então você precisa utilizar trim() se não quiser esses caracteres presentes.

Nota: Se você está tendo problemas com o PHP no reconhecimento do final de linha quando criando ou lendo arquivos num computador Macintosh, você pode habilitar a opção auto_detect_line_endings.

Você pode usar o parâmetro opcional use_include_path como "1", se você deseja procurar o arquivo no include_path também.

<?php
// Le um arquivo em um array. Nesse exemplo você pode obter via HTTP para obter
// o código fonte HTML de uma URL.
$lines = file ('http://www.exemplo.com/');

// Roda através do array, mostrando o fonte HTML com numeração de linhas.
foreach ($lines as $line_num => $line) {
    echo "Linha #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br>\n";
}

// Outro exemplo, onde obtemos a página web inteira como uma string. Veja também file_get_contents().
$html = implode ('', file ('http://www.exemplo.com/'));
?>

Nota: A partir do PHP 4.3.0, você pode utilizar file_get_contents() para retornar o conteúdo de um arquivo como uma string.

Dica: Você pode usar uma URL com esta função se fopen wrappers estiver habilitado. Veja fopen() para mais detalhes em como especificar o nome do arquivo e Apêndice I para uma lista de protololos URL suportados.

Veja também readfile(), fopen(), fsockopen(), and popen(), file_get_contents() e include().

fileatime

(PHP 3, PHP 4 )

fileatime -- Obtém o último horário de acesso do arquivo

Descrição

int fileatime ( string nomedoarquivo)

Retorna a data e hora em que o arquivo foi acessado pela última vez, ou FALSE em caso de erro. O tempo que é retornado é um timestamp UNIX.

Os resultados desta função são guardados em cache. Veja clearstatcache() para mais detalhes.

Nota: O atime do arquivo supostamente deve mudar quando os blocos de informação do arquivo forem lidos. Isto pode ser caro em termos de performance quando uma aplicação freqüentemente acessa um número muito grande de arquivos ou diretórios. Alguns filesystems Unix podem ser montados com updates dos atimes desabilitados para aumentar a performance destas aplicações; USENET news spools é um exemplo comum. Nestes filesystems esta função é inútil.

Esta função não funcionará em arquivos remotos; o arquivo a ser examinado tem que ser acessível pelo filesystem do servidor.

filectime

(PHP 3, PHP 4 )

filectime -- Ler o tempo de modificação do inode do arquivo

Descrição

int filectime ( string nomedoarquivo)

Retorna o tempo em que o arquivo foi modificado pela última vez, ou FALSE em caso de erro. O tempo é retornado como um timestamp Unix.

Os resultados desta função são guardados em cache. Veja clearstatcache() para mais detalhes.

Nota: Na maior parte dos filesystems Unix, um arquivo é considerado modificado quando a informação do inode é modificada; isto é, quando as permissões, dono (owner), grupo (group), ou outra metadata do inode é modificada. Veja também filemtime() (o que é o que você deseja usar quando criando rodapés com informações sobre última vez que o arquivo foi modificado em web pages) e fileatime().

Note também que em alguns textos Unix o ctime do arquivo é referido como sendo o tempo de criação do tempo do arquivo. Isto é errado. Não há tempo de criação de arquivos Unix na maior parte dos filesystems Unix.

Esta função não irá funcionar em arquivos remotos; o arquivo a ser examinado tem que ser acessivel pelo filesystem do servidor.

filegroup

(PHP 3, PHP 4 )

filegroup -- Le o grupo do arquivo

Descrição

int filegroup ( string nomedoarquivo)

Retorna o group ID do arquivo, ou FALSE no caso de um erro. O group ID é retornado em um formato numérico. Use posix_getgrgid() para resolver para o nome do grupo.

O resultado desta função é guardado em cache. Veja clearstatcache() para mais detalhes.

Nota: Esta função não irá funcionar em arquivos remotos; o arquivo a ser examinado tem que ser acessivel através do filesystem do servidor.

fileinode

(PHP 3, PHP 4 )

fileinode -- Le o inode do arquivo

Descrição

int fileinode ( string nomedoarquivo)

Retorna o número do inode do arquivo, ou FALSE em caso de erro.

Os resultados desta função são guardados em cache. Veja clearstatcache() para mais detalhes.

Esta função não funcionará em arquivos remotos; o arquivo a ser examinado tem que ser acessivel pelo filesystem do servidor.

filemtime

(PHP 3, PHP 4 )

filemtime -- Le o tempo de modificação do arquivo

Descrição

int filemtime ( string nomedoarquivo)

Retorna a data/hora em que o arquivo foi modificado pela última vez, ou FALSE em caso de erro. O tempo é retornado como um timestamp Unix.

Os resultados desta função são guardados em cache. Veja clearstatcache() para mais detalhes.

Esta função não funcionará em arquivos remotos; o arquivo a ser examinado tem que ser acessivel pelo filesystem do servidor.

Nota: Esta função retorna o tempo quando os blocos de informação do arquivo são escritos, isto é, o tempo de quando o conteúdo do arquivo foi mudado. Utilize date() no resultado desta função para obter uma versão imprimível da data (para a utilização em rodapés).

Veja também filectime() e touch().

fileowner

(PHP 3, PHP 4 )

fileowner -- Le o dono (owner) do arquivo

Descrição

int fileowner ( string nomedoarquivo)

Retorna o ID do usuário(user ID) do dono (owner) do arquivo, ou FALSE caso um erro. O ID do usuário é retornado no formato numérico, use posix_getpwuid() para obter o username do usuário.

Os resultados desta função são guardados em cache. Veja clearstatcache() para mais detalhes.

Esta função não funcionará em arquivos remotos; o arquivo a ser examinado tem que ser acessivel pelo filesystem do servidor.

fileperms

(PHP 3, PHP 4 )

fileperms -- Ler as permissões do arquivo

Descrição

int fileperms ( string filename)

Retorna as permissões do arquivo, ou FALSE em caso de erro.

Esta função não funcionará em arquivos remotos; o arquivo a ser examinado tem que ser acessivel pelo filesystem do servidor.

Os resultados desta função são guardados em cache. Veja clearstatcache() para mais detalhes.

filesize

(PHP 3, PHP 4 )

filesize -- Ler o tamanho do arquivo

Descrição

int filesize ( string nomedoarquivo)

Retorna o tamanho do arquivo, ou FALSE em caso de erro.

Os resultados desta função são guardados em cache. Veja clearstatcache() para mais detalhes.

This function will not work on remote files; the file to be examined must be accessible via the server's filesystem.

filetype

(PHP 3, PHP 4 )

filetype -- Le o tipo de arquivo (file type)

Descrição

string filetype ( string nomedoarquivo)

Retorna o tipo do arquivo(file type). Valores possiveis são fifo, char, dir, block, link, file e unknown (desconhecido).

Retorna FALSE se um erro ocorrer.

Os resultados desta função são guardados em cache. Veja clearstatcache() para mais detalhes.

Esta função não funcionará em arquivos remotos; o arquivo a ser examinado tem que ser acessivel pelo filesystem do servidor.

Veja também: is_dir(), is_file(), is_link(), file_exists() e stat().

flock

(PHP 3>= 3.0.7, PHP 4 )

flock -- Monitor de travamento de arquivos portátil

Descrição

bool flock ( int fp, int operation [, int &wouldblock])

O PHP suporta uma maneira portável de lock arquivos inteiros em uma advisory way (que significa que todos os programas acessando tem que usar o mesmo tipo de travamento ou não irá funcionar).

flock() opera em fp, que tem que ser um ponteiro de arquivo aberto com sucesso. operacao é um dos seguintes valores:

  • Para obter um lock compartilhado (leitura), utilize operation como LOCK_SH (ou use 1 se a versão do PHP for anterior a 4.0.1).

  • Para obter um lock exclusivo (gravação), utilize operacao como LOCK_EX (ou use 2 se a versão do PHP for anterior a 4.0.1).

  • Para retirar um lock (compartilhado ou exclusivo), uyilize operacao como LOCK_UN (ou use 3 se a versão do PHP for anterior a 4.0.1).

  • Se você não quer usar flock() para bloquear enquanto travando, adicione LOCK_NB (4 se a versão do PHP for anterior a 4.0.1) a operacao.

flock() permite a você fazer um simples modelo leitura/gravação (reader/writer) que pode ser usado em virtualmente todas as plataformas (incluindo a maior parte dos Unixes e até mesmo Windows). O terceiro argumento opcional é usado como TRUE se a lock irá bloquear (EWOULDBLOCK errno condition).

flock() retorna TRUE em caso de sucesso e FALSE em caso de erro (por exemplo quando um lock não pode ser obtido).

Nota: Uma vez que flock() requer um ponteiro de arquivo, você precisa utilizar um lock de arquivo especial para proteger i acessi a um arquivo ao qual você pretende truncar quando abrindo no modo de escrita (com um argumento "w" ou "w+" em fopen()).

Atenção

flock() não funcionará em NFS ou em qualquer outro sistema de arquivos em rede. Verifique a documentação do seu sistema operacional para mais detalhes.

Na maior parte dos sistemas operacionais flock() é implementada no nível do processo. Quando utilizando um servidor com uma API de multiprocessamento (como ISAPI), você não pode confiar em flock() para proteger os arquivos contra outros scripts PHP rodando em threads paralelas da mesma instância do servidor!

flock() não é suportado em sistemas de arquivos antiquados como a FAT e seus derivados, e sempre retornará FALSE sob esses ambientes (especialmente para usuários do Windows 98).

fnmatch

(PHP 4 >= 4.3.0)

fnmatch -- Verifica se um nome de arquivo bate com padrão (wildcards)

Descrição

array fnmatch ( string pattern, string string [, int flags])

fnmatch() checa se a string se encaixa com o pattern.

Isto é especialmente útil para nomes de arquivos, mas também pode ser utilizado em strings. O usuário comum poderá utilizar curingas shell na sua forma mais simples ('?' e '*') com fnmatch() em vez de ereg() ou preg_match() para pesquisas realizadas em código, numa forma mais inteligível para usuários não programadores.

Exemplo 1. Verificando um nome de cor com um padrão shell

if(fnmatch("*gr[ae]y", $color)) {
  echo "alguma forma da palavra gray ...";
}

Veja também glob(), ereg(), preg_match() e a manpage UNIX de fnmatch(3) para nomes de flags (já que não estão documentadas aqui ).

fopen

(PHP 3, PHP 4 )

fopen -- Abri um arquivo ou uma URL

Descrição

int fopen ( string filename, string mode [, int use_include_path [, resource zcontext]])

fopen() conecta um recurso nomeado, especificado em filename para um stream. Se filename está na forma "protocolo://...", é assumido que seja uma URL e o PHP irá procurar por um manipulador de protocolo (também conhecido como wrapper) conforme o prefixo. Se nenhum wrapper para o protocolo estiver registrado, o PHP irá emitir um alerta para ajudá-lo a rastrear problemas potenciais em seu script, presumindo que filename é um nome de arquivo comum.

Se o PHP decidir que filename se refere a um arquivo local, então ele tentará abrir o stream para aquele arquivo. Esse arquivo precisa ser acessível pelo PHP, então você precisa certificar-se que as permissões de acesso que garantam esse acesso. Se você está com safe_mode ativado ou open_basedir, essas restrições serão aplicadas.

Se o PHP decidir que filename se refere a um protocolo registrado, e que o protocolo está registrado como um URL de rede, o PHP irá verificar se allow_url_fopen está ativado. Se ele estiver desligado, o PHP irá emitir um alerta e a chamada a fopen irá falhar.

Nota: A lista de protocolos registrados pode ser encontrada em Apêndice I.

mode especifica a tipo de acesso que você requer na stream. Ele pode ser um dos seguintes:

  • 'r' - Abrir somente para leitura; coloca o ponteiro de arquivo no começo do arquivo.

  • 'r+' - Abrir para leitura e gravação; colocar o ponteiro de arquivo no começo do arquivo.

  • 'w' - Abrir somente para gravação; colocar o ponteiro de arquivo no começo do arquivo e truncar o arquivo para tamanho zero. Se o arquivo não existir, tentar cria-lo.

  • 'w+' - Abrir para leitura e escrita; colocar o ponteiro de arquivo no início do arquivo e truncar o arquivo para tamanho zero. Se o arquivo não existir, tentar cria-lo.

  • 'a' - Abrir o arquivo somente para escrita; colocar o ponteiro de arquivo no fim do arquivo. Se o arquivo não existe, tentar cria-lo.

  • 'a+' - Abrir o arquivo para leitura e gravação; colocar o ponteiro no fim do arquivo. Se o arquivo não existe, tentar cria-lo.

Nota: O mode pode conter a letra 'b'. Isto é útil somente em sistemas que diferenciam entre arquivos binários e texto (por exemplo Windows. É inútil em Unix). Se não necessário, será ignorado. Você é encorajado a incluir o modo 'b' de forma a tornar seus scripts mais portáveis.

Você pode usar o terceiro pparâmetro opcional como "1", se você quiser procurar pelo arquivo no include_path também.

O quarto parâmetro zcontext (opcional) é utilizado especificamente para ajuste de parâmetros e callbacks.

Se a abertura falhar, a função retorna FALSE.

Exemplo 1. exemplo do fopen()

<?php
$fp = fopen ("/home/rasmus/file.txt", "r");
$fp = fopen ("/home/rasmus/file.gif", "wb");
$fp = fopen ("http://www.example.com/", "r");
$fp = fopen ("ftp://user:password@example.com/", "w");
?>

Se você está tendo problemas com a leitura e gravação para arquivos e você está usando a versão de modulo de servidor do PHP, lembre-se de que os arquivos e diretórios que você está usando precisam ser acessíveis ao processo do servidor HTTP.

Na plataforma Windows, tenha cuidado para usar uma segunda barra invertida (escape) nos caminhos de arquivos, ou usar a barra normal.

<?php
$fp = fopen ("c:\\data\\info.txt", "r");
?>

Veja também: Apêndice I, fclose(), fgets(), fsockopen(), file(), file_exists(), is_readable(), socket_set_timeout() e popen().

fpassthru

(PHP 3, PHP 4 )

fpassthru -- Imprime todo os dados restantes de um ponteiro de arquivo

Descrição

int fpassthru ( int fp)

Lê até o fim do arquivo (EOF) do ponteiro de arquivo dado e imprime os resultados para a buffer de saída.

Se um error ocorrer, a função fpassthru() retorna FALSE.

O ponteiro de arquivo tem que ser válido e apontar para um arquivo aberto com sucesso por fopen(), popen() ou fsockopen(). Você pode precisar chamar rewind() para reiniciar o ponteiro do arquivo para o início do arquivo caso você já tenha escrito dados no arquivo. O arquivo é fechado quando fpassthru() acaba de ler (deixando fp sem utilidade).

Se você somente quiser jogar o conteúdo de um arquivo para o buffer de saída, sem primeiro modificar ou procurar por um detalhe qualquer, você pode querer usar a função readfile(), que vai economizar uma chamada a função fopen().

Nota: Quando utilizando fpassthru() em um arquivo binário em sistemas Windows, você precisa verificar se abriu o arquivo em modo binário, acrescentando um b no modo informado na chamada de fopen().

Você é encorajado a utilizar o modo b quando trabalhando com arquivos binários, mesmo que seu sistema não requira isso, de forma que seus scripts se tornem mais portáveis.

Veja também readfile(), fopen(), popen() e fsockopen()

fputs

(PHP 3, PHP 4 )

fputs -- Escrever para um ponteiro de arquivo

Descrição

int fputs ( int fp, string str [, int comprimento])

fputs() é uma função sinônima (alias) para fwrite(), e é identica em todas as maneiras. Note que o parametro comprimento é opcional e se não for especificado a string inteira será escrita.

fread

(PHP 3, PHP 4 )

fread -- Leitura binary-safe de arquivo

Descrição

string fread ( int fp, int comprimento)

fread() lê até comprimento bytes. A leitura é interrompida quando comprimento bytes foram lidos ou o fim do arquivo (eof) foi alcançado, o que ocorrer primeiro.

<?php
// ler o conteúdo do arquivo para uma string
$nomedoarquivo = "/usr/local/algo.txt";
$fd = fopen ($nomedoarquivo, "r");
$conteudo = fread ($fd, filesize ($nomedoarquivo));
fclose ($fd);
?>

Nota: Em sistemas que diferenciam entre arquivos binários e texto (por exemplo Windows) o arquivo tem que ser aberto com 'b' incluído como parametro na função fopen().

<?php
$nomedoarquivo = "c:\\arquivos\\algumaimg.gif";
$fd = fopen ($nomedoarquivo, "rb");
$conteudo = fread ($fd, filesize ($nomedoarquivo));
fclose ($fd);
?>

Veja também fwrite(), fopen(), fsockopen(), popen(), fgets(), fgetss(), fscanf(), file() e fpassthru().

fscanf

(PHP 4 >= 4.0.1)

fscanf -- Interpreta a leitura de um arquivo de acordo com um formato

Descrição

mixed fscanf ( int handle, string formato [, string var1])

A função fscanf() é semelhante a sscanf(), mas usa como entrada um arquivo associado com handle e interpreta a entrada de acordo com o formato especificado. Se somente dois parametros forem passados para a função, os valores interpretados serão retornados como um array. De outro modo, se parametros opcionais são passados a função irá retornar o número de valores utilizados. Os parametros opcionais tem que ser passados por referência.

Qualquer espaço em branco na string formato baterá quaisquer outros espaços no stream de entrada. Isto significa que qualquer tabulação \t na string formato poderá bater com um caracter de espaço simples no stream de entrada.

Exemplo 1. Exemplo do fscanf()

$fp = fopen ("users.txt","r");
while ($userinfo = fscanf ($fp, "%s\t%s\t%s\n")) {
    list ($name, $profission, $countrycode) = $userinfo;
    //... fazer algo com os valores
}
fclose($fp);

Exemplo 2. users.txt

javier  argonauta        pe
hiroshi escultor         jp
robert  tradutor us
luigi   florista it

Veja também fread(), fgets(), fgetss(), sscanf(), printf() e sprintf().

fseek

(PHP 3, PHP 4 )

fseek -- Procura (seeks) em um ponteiro de arquivo

Descrição

int fseek ( int fp, int offset [, int whence])

Modifica o indicador de posição do arquivo referenciado por fp. A nova posição é obtida, medindo em bytes do início do arquivo, é obtida ao adicionar offset a posição especificada por whence, cujo valor é definido como se segue:

SEEK_SET - Use a posição igual à offset bytes.
SEEK_CUR - Use a posição para a localização atual mais offset.
SEEK_END - Use a posição para o fim do arquivo (eof) mais offset. (Para mover para uma posição anterior ao fim de arquivo, você precisa passar um valor negativo em offset.)

Se whence não é especificado é presumido ser SEEK_SET.

Em caso de sucesso, retorna 0; caso contrário, retorna -1. Note que fazer um seek depois do fim do arquivo (eof) é considerado um erro.

Não pode ser usado em ponteiros de arquivo retornados por fopen() se for usado o formato "http://" ou "ftp://".

Nota: O argumento whence foi adicionado depois do PHP 4.0.0.

Veja também ftell() e rewind().

fstat

(PHP 4 )

fstat --  Ler a informação sobre um arquivo usando um ponteiro de arquivo aberto

Descrição

array fstat ( int fp)

Mantém estatísticas do arquivo aberto pelo ponteiro de arquivos fp. Esta função é similar a função stat() exceto que ela opera em um ponteiro de arquivo aberto ao invéz de um nome de arquivo.

Retorna um array com as estatísticas do arquico com os seguintes elementos:

  1. device

  2. inode

  3. número de links

  4. user id do dono (owner)

  5. group id (owner)

  6. tipo de device se inode device *

  7. tamanho em bytes

  8. tempo do último acesso

  9. tempo da última modificação(modification)

  10. tempo da última mudança(change)

  11. tamanho do bloco para o filesystem I/O *

  12. número de blocos alocados

* - somente válido em sistemas suportando o tipo st_blksize--outros sistemas (por exemplo Windows) retornam -1

Os resultados desta função são guardados em cache. Veja clearstatcache() para mais detalhes.

ftell

(PHP 3, PHP 4 )

ftell -- Diz ao ponteiro de arquivo a posição de leitura/gravação

Descrição

int ftell ( int fp)

Retorna a posição do ponteiro de arquivo referenciado por fp; por exemplo o seu offset no file stream.

Se um error ocorrer, retorna FALSE.

O ponteiro de arquivo tem que ser válidoe apontar para um arquivo aberto com sucesso por fopen() ou popen().

Veja também fopen(), popen(), fseek() e rewind().

ftruncate

(PHP 4 )

ftruncate --  Corta um arquivo para um tamanho especificado.

Descrição

int ftruncate ( int fp, int comprimento)

Pega o ponteiro de arquivo, fp, e corta o arquivo no comprimento especificado. O arquivo final terá os comprimento bytes iniciais idênticos ao arquivo original. Esta função retorna TRUE em caso de sucesso e FALSE em caso de falha.

fwrite

(PHP 3, PHP 4 )

fwrite -- Gravação em arquivos binary-safe

Descrição

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

fwrite() grava os conteúdos de string para o stream de arquivo apontado por fp. Se o argumento comprimento é dado, a gravação irá parar depois de que comprimento bytes foram escritos ou o fim da string é alcançada, o que ocorrer primeiro.

fwrite() retorna o número de bytes gravados, ou FALSE em caso de erro.

Note que se o argumento comprimento é dado, então a opção de configuração magic_quotes_runtime será ignorada e nenhuma barra será retirada do string.

Nota: Em sistemas que diferenciam entre arquivos binários e texto (por exemplo Windows) o arquivo tem que ser aberto com 'b' incluído no parametro mode do fopen().

Exemplo 1. Exemplo fwrite

<?php
$filename = 'teste.txt';
$somecontent = "Acrescentando isto no arquivo\n";

// Tendo certeza que o arquivo existe e que há permissão de escrita primeiro.
if (is_writable($filename)) {

    // Em nosso exemplo, nós estamos abrindo $filename em modo de append (acréscimo).
    // O ponteiro do arquivo estará no final dele desde
    // que será aqui que $somecontent será escrito com fwrite().
    if (!$fp = fopen($filename, 'a')) {
         print "Erro abrindo arquivo ($filename)";
         exit;
    }

    // Escrevendo $somecontent para o arquivo aberto.
    if (!fwrite($fp, $somecontent)) {
        print "Erro escrevendo no arquivo ($filename)";
        exit;
    }

    print "Sucesso: escrito ($somecontent) no arquivo ($filename)";

    fclose($fp);

} else {
    print "The file $filename is not writable";
}
?>

Veja também fread(), fopen(), fsockopen(), popen() e fputs().

glob

(PHP 4 >= 4.3.0)

glob -- Localiza diretórios/arquivos que combinem com o padrão

Descrição

array glob ( string pattern [, int flags])

A função glob() procura por todos os caminhos de arquivos que batem com o padrão pattern de acordo com as regras do sistema operacional. Nenhuma expansão ou substituição de variável é realizada.

Retorna um array contendo os arquivos/diretórios localizados ou FALSE em caso de erro.

Exemplo 1. Maneira conveniente de como glob() pode substituir opendir() e similares.

foreach (glob("*.txt") as $filename) {
    echo "Tamanho de $filename " . filesize($filename) . "\n";
}

Resultado possível do exemplo acima:

Tamanho de funclist.txt 44686
Tamanho de funcsummary.txt 267625
Tamanho de quickref.txt 137820

Veja também opendir(), readdir(), closedir(), fnmatch() e a manpage UNIX de glob(3) para os nomes das flags (uma vez que elas não estão documentadas aqui).

is_dir

(PHP 3, PHP 4 )

is_dir -- Diz se o caminho é um diretório

Descrição

bool is_dir ( string filename)

Retorna TRUE se o filename existe e é um diretório. Se filename for um caminho relativo, o mesmo será checado relativo ao diretório atual.

Os resultados desta função são guardados em cache. Veja clearstatcache() para mais detalhes.

Esta função não funcionará em arquivos remotos. O diretório a ser examinado tem que ser acessível pelo filesystem do servidor.

Veja também chdir(), dir, opendir(), is_file() and is_link().

is_executable

(PHP 3, PHP 4 )

is_executable -- Diz se um arquivo é executável

Descrição

bool is_executable ( string nomedoarquivo)

Retorna TRUE se no nomedoarquivo existe e é executável.

Os resultados desta função são guardados em cache. Veja clearstatcache() para mais detalhes.

Esta função não funcionará em arquivos remotos; o arquivo a ser examinado tem que ser acessivel pelo filesystem do servidor.

Nota: Esta função não está disponível no Win32.

Veja também is_file() e is_link().

is_file

(PHP 3, PHP 4 )

is_file -- Diz se o arquivo é um arquivo comum (não é diretório)

Descrição

bool is_file ( string nomedoarquivo)

Retorna TRUE se o nome do nomedoarquivo existe e é um arquivo comum.

Os resultados desta função são guardados em cache. Veja clearstatcache() para mais detalhes.

Esta função não funciona em arquivos remotosO arquivo a ser examinado precisa ser acessível pelo sistema de arquivos do servidor.

Veja também is_dir() e is_link().

is_link

(PHP 3, PHP 4 )

is_link -- Diz se o arquivo é um link simbólico (symbolic link)

Descrição

bool is_link ( string arquivo)

Retorna TRUE se o nomedoarquivo existe e é um link simbólico (symbolic link).

Os resultados desta função são guardados em cache. Veja clearstatcache() para mais detalhes.

Veja também is_dir(), is_file() e readlink().

Esta função não funcionará em arquivos remotos; o arquivo a ser examinado tem que ser acessivel pelo filesystem do servidor.

is_readable

(PHP 3, PHP 4 )

is_readable --  Diz se o arquivo é legivel (readable)

Descrição

bool is_readable ( string nomedoarquivo)

Retorna TRUE se o nomedoraquivo existe e é legível (readable).

Lembre-se que o PHP deve estar acessando o arquivo como o mesmo usuário que o servidor de web roda (frequentemente 'nobody'). Limitações do safemode não são levadas em consideração.

Os resultados desta função são guardados em cache. Veja clearstatcache() para mais detalhes.

Esta função não funcionará em arquivos remotos; o arquivo a ser examinado tem que ser acessivel pelo filesystem do servidor.

Veja também is_writable().

is_uploaded_file

(PHP 3>= 3.0.17, PHP 4 >= 4.0.3)

is_uploaded_file -- Diz se o arquivo foi uploaded via HTTP POST

Descrição

bool is_uploaded_file ( string filename)

Retorna TRUE se o arquivo com o nome filename foi uploaded via HTTP POST. Isto é útil para ter certeza que um usuário malicioso, não está tentando confundir o script em trabalhar em arquivos que não deve estar trabalhando --- por exemplo, /etc/passwd.

Este tipo de confirmação é importante principalmente se existe alguma chance que qualquer coisa feita com os arquivos carregados poderiam revelar o seu conteúdo para o usuário, ou mesmo para outros usuários no mesmo sistema.

is_uploaded_file() está disponível somente em versões do PHP 3 depois da 3.0.16 e em versões do PHP 4 posteriores a 4.0.2. Se você ainda está utilizando uma versão anterior, você pode utilizar o seguinte código para se proteger:

Nota: O exemplo seguinte não funcionará em versões do PHP posteriores a 4.0.2. Isto depende de uma funcionalidade interna do PHP que mudou depois dessa versão.

<?php
/* Teste de arquivo carregado pelo usuário */
function is_uploaded_file($filename) {
    if (!$tmp_file = get_cfg_var('upload_tmp_dir')) {
        $tmp_file = dirname(tempnam('', ''));
    }
    $tmp_file .= '/' . basename($filename);
    /* Pode haver uma barra no final do php.ini... */
    return (ereg_replace('/+', '/', $tmp_file) == $filename);
}

/* Utilize isto se por acaso você não tiver
 * move_uploaded_file() em versões antigas: */
if (is_uploaded_file($HTTP_POST_FILES['userfile'])) {
    copy($HTTP_POST_FILES['userfile'], "/place/to/put/uploaded/file");
} else {
    echo "Possível ataque de carregamento de arquivo: filename '$HTTP_POST_FILES[userfile]'.";
}
?>

Veja também move_uploaded_file() e a seção Manipulando upload de arquivos para um exemplo de utilização desta função.

is_writable

(PHP 4 )

is_writable -- Diz se pode-se escrever para o arquivo(writable)

Descrição

bool is_writable ( string arquivo)

Retorna TRUE se o nomedoarquivo existe e pode ser escrito para. O argumento nomedoarquivo pode ser um nome de diretório, deixando você saber se o diretório pode ser escrito para (writeable).

Lembre-se que o PHP deve estar acessando o arquivo como o mesmo usuário que o servidor de web roda (frequentemente 'nobody'). Limitações do safemode não são levadas em consideração.

Os resultados desta função são guardados em cache. Veja clearstatcache() para mais detalhes.

Esta função não funcionará em arquivos remotos; o arquivo a ser examinado tem que ser acessível pelo filesystem do servidor.

Veja também is_readable().

is_writeable

(PHP 3, PHP 4 )

is_writeable -- Diz se pode-se escrever para o arquivo(writable)

Descrição

bool is_writeable ( string nomedoarquivo)

Esta é uma função sinônima (alias) para is_writable()

link

(PHP 3, PHP 4 )

link -- Criando um hard link

Descrição

int link ( string alvo, string link)

link() cria um hard link.

Veja também symlink() para criar soft links, e readlink() assim como linkinfo().

linkinfo

(PHP 3, PHP 4 )

linkinfo -- Ler informações sobre um link

Descrição

int linkinfo ( string path)

linkinfo() retorna o campo st_dev da structure em C do UNIX retornado pela chamada do sistema (system call) lstat. Esta função é usada para verificar se um link (apontado por path) realmente existe (usando o mesmo metodo que a macro S_ISLNK definida em stat.h). Retorna 0 ou FALSE em caso de erro.

Veja também symlink(), link(), e readlink().

lstat

(PHP 3>= 3.0.4, PHP 4 )

lstat -- Obtem informações sobre um arquivo ou link simbólico

Descrição

array lstat ( string nomedoarquivo)

Pega as estatísticas do arquivo ou link simbólico com o nome de nomedoarquivo. Esta função é identica a stat() exceto que se o parametro nomedoarquivo é um link simbólico o status do link simbólico é retornado e não o status do arquivo apontando pelo link simbólico.

Retorna um array com as estatísticas do arquivo com os seguintes elementos:

  1. device

  2. inode

  3. inode protection mode

  4. number of links

  5. user id of owner

  6. group id owner

  7. device type if inode device *

  8. size in bytes

  9. time of last access

  10. time of last modification

  11. time of last change

  12. blocksize for filesystem I/O *

  13. number of blocks allocated

* - somente válido em sistemas supportando o tipo st_blksize --- outros sistemas (por exemplo Windows) retornam -1.

lstat() não pode ser utilizado em arquivos remotos.

Os resultados desta função são guardados em cache. Veja clearstatcache() para mais detalhes.

mkdir

(PHP 3, PHP 4 )

mkdir -- Criar um diretório

Descrição

int mkdir ( string pathname, int mode)

Tenta criar o diretório pathname.

Note que você provavelmente quer especificar o mode como um número octal, o que significa que ele deve ter o zero inicial. O mode é também modificado pela umaks atual, o que você pode mudar usando umask().

mkdir ("/path/to/my/dir", 0700);

Retorna TRUE em caso de sucesso ou FALSE em falhas.

Veja também rmdir().

move_uploaded_file

(PHP 4 >= 4.0.3)

move_uploaded_file -- Move um arquivo carregado para uma nova localização

Descrição

bool move_uploaded_file ( string nomedoarquivo, string destino)

Esta função primeiro checa o arquivo informado nomedoarquivo é um arquivo válido uploadeado (significando que ele foi carregado pelo mecanismo do PHP de HTTP POST). Se o arquivo é válido, ele será movido para o nomedoarquivo dado pelo destino.

Se nomedoarquivo não é um arquivo carregado válido, então não haverá nenhuma ação e move_uploaded_file() irá retornar FALSE.

Se nomedoarquivo é um arquivo uploadeado válido e não pode ser movido por alguma razão, nenhuma ação irá ocorrer, e move_uploaded_file() irá retornar FALSE. Adicionalmente, um aviso será emitido.

Este tipo de confirmação é importante principalmente se existe alguma chance que qualquer coisa feita com os arquivos carregados poderem revelar o seu conteúdo para o usuário, ou mesmo para outros usuários no mesmo sistema.

Nota: Quando o safe-mode está ativo, o PHP verifica se o(s) arquivo(s) e/ou diretório(s) que serão afetados por esta operação tem o mesmo UID (proprietário) do script que está sendo executado.

Nota: move_uploaded_file() não é afetado pelas restrições de UIN normais so safe-mode. Isto não é inseguro porque move_uploaded_file() somente opera sobre arquivos carregados pelo PHP.

Atenção

Se o arquivo destino já existir, então ele será sobrescrito.

Veja também is_uploaded_file() e a seção Manipulando o upload de arquivos para um exemplo de utilização desta função.

parse_ini_file

(PHP 4 )

parse_ini_file -- Interpreta um arquivo de configuração

Descrição

array parse_ini_file ( string nomedoarquivo [, bool processar_secoes])

parse_ini_file() carrega o arquivo INI informado no nomedoarquivo, e retorna as configurações dele em um array associativo. Ao usar processar_secoes como TRUE, você receberá um array multidimensional, com os nomes das seções e os parametros incluidos. O padrão (default) para processar_secoes é FALSE.

Nota: Esta função não tem nada a ver com o arquivo php.ini. Este já é processado na hora que você executa o script. Esta função pode ser usada para ler os arquivos de configuração de sua própria aplicação.

Nota: Se o arquivo INI tem qualquer caracter não alfanumérico, eles precisam estar delimitados por aspas (").

Nota: Desde o PHP 4.2.1, esta função é afetada por safe_mode e open_basedir.

A estrutura do arquivo ini é similar a do php.ini.

Atenção

Se o arquivo INI que você está tentando interpretar estiver mal formado, o PHP pára.

Exemplo 1. Conteúdo de exemplo.ini

; Este é um arquivo de configuração de exemplo
; Comentário começam com ';', como no php.ini

[primeira_secao]
um = 1
cinco = 5

[segunda_secao]
path = /usr/local/bin
URL = "http://www.example.com/~username"

Exemplo 2. exemplo de parse_ini_file()

<?php

// Parse sem as seções
$ini_array = parse_ini_file("exemplo.ini");
print_r($ini_array);

// Parse com as seções
$ini_array = parse_ini_file("exemplo.ini", TRUE);
print_r($ini_array);

?>

Irá produzir:

Array
(
    [um] => 1
    [cinco] => 5
    [path] => /usr/local/bin
    [URL] => http://www.example.com/~username
)
Array
(
    [primeira_secao] => Array
        (
            [um] => 1
            [cinco] => 5
        )

    [segunda_secao] => Array
        (
            [path] => /usr/local/bin
            [URL] => http://www.example.com/~username
        )

)

pathinfo

(PHP 4 >= 4.0.3)

pathinfo -- Retorna informação sobre o path de um arquivo

Descrição

array pathinfo ( string path)

pathinfo() retorna um array associatico contendo informações sobre o path. O seguinte elementos do array são retornados: dirname, basename e extension.

Exemplo 1. Exemplo de pathinfo()

<?php

$partes_do_path = pathinfo("/www/htdocs/index.html");

echo $partes_do_path["dirname"] . "\n";
echo $partes_do_path["basename"] . "\n";
echo $partes_do_path["extension"] . "\n";

?>

Produzirá:

/www/htdocs
index.html
html

Nota: Para informações na recuperação da informação do diretório atual, leia a seção variáveis predefinidas reservadas.

Veja também dirname(), basename(), parse_url() e realpath().

pclose

(PHP 3, PHP 4 )

pclose -- Fecha um processo de um ponteiro de arquivo

Descrição

int pclose ( int fp)

Fecha um ponteiro de arquivo a uma pipe aberta por popen().

O ponteiro de arquivo tem que ser válido e tem que ser retornado por uma chamada bem sucedida a função popen().

Retorna o status da finalização do processo que estava rodando.

Veja também popen().

popen

(PHP 3, PHP 4 )

popen -- Abre um processo como ponteiro de arquivo

Descrição

int popen ( string command, string mode)

Abre uma pipe para um processo executado ao se dar um fork para o comando dado por command.

Retorna um ponteiro de arquivo identico ao retornado por fopen(), exceto que ele é unidirecional (somente pode ser usado para leitura ou gravação) e tem que ser fechado com pclose. Este ponteiro pode ser usado com fgets(), fgetss() e fputs().

Caso um erro ocorra retorna FALSE.

Nota: Se você está procurando por suporte bidirecional (via dupla), utilize proc_open().

<?php
$fp = popen ("/bin/ls", "r");
?>

Nota: Se o commando a ser executado não for encontradom um recurso válido será retornado. Isso pode parecer esquisito, mas tem sentido: permite que você acesse a mensagem de erro retornado pelo sistema operacional.

<?php
error_reporting(E_ALL);

/* Add redirection so we can get stderr. */
$fp = popen('/path/to/spooge 2>&1', 'r');
echo "'$fp'; " . gettype($fp) . "\n";
$read = fread($fp, 2096);
echo $read;
pclose($fp);
?>

Veja também pclose(), fopen() e proc_open().

readfile

(PHP 3, PHP 4 )

readfile -- Le o conteúdo de um arquivo

Descrição

int readfile ( string nomedoarquivo [, int use_include_path])

Lê um arquivo e escreve o seu conteúdo para o buffer de saída(output buffer).

Retorna o número de bytes lido do arquivo. Se um error ocorrer, retorna FALSE e ao menos que a função seja chamada como @readfile, uma mensagem de erro será impressa.

Dica: Você pode usar uma URL com esta função se fopen wrappers estiver habilitado. Veja fopen() para mais detalhes em como especificar o nome do arquivo e Apêndice I para uma lista de protololos URL suportados.

Você pode usar o segundo parametro opcional e o setar para "1", se você quiser procurar o arquivo no include_path, também.

Veja também fpassthru(), file(), fopen(), include(), require(), virtual() e Apêndice I.

readlink

(PHP 3, PHP 4 )

readlink -- Retornar o alvo de um link simbólico

Descrição

string readlink ( string path)

readlink() faz o mesmo que a função do C readlink e retorna os conteúdos do path do link simbólico ou 0 em caso de erro.

Veja também symlink(), readlink() e linkinfo().

realpath

(PHP 4 )

realpath -- Retorna o path absoluto canonicalizado

Descrição

string realpath ( string path)

realpath() expande todos os links simbólicos e resolve referencias para '/./', '/../' e extra caracteres '/' na entrada pelo path e retorna o path absoluto canonicalizado . O path resultante não conterá nenhum link simbólico ou componentes '/./' e '/../'.

realpath() retorna FALSE em caso de falha, por exemplo, se o caminho não existir.

Exemplo 1. exemplo de realpath()

$real_path = realpath ("../../index.php");

Veja também: basename(), dirname() e pathinfo().

rename

(PHP 3, PHP 4 )

rename -- Renomear um arquivo

Descrição

bool rename ( string nomeantigo, string novonome)

Tenta renomear nomeantigo para novonome.

Retorna TRUE em caso de sucesso ou FALSE em falhas.

Exemplo 1. Exemplo de rename()

<?php
  rename("/tmp/tmp_file.txt", "/home/user/login/docs/my_file.txt");
?>

rewind

(PHP 3, PHP 4 )

rewind -- Reinicializa a posição do ponteiro de arquivos para o início

Descrição

int rewind ( int fp)

Muda o indicador de ponteiro de arquivo fp para o início do stream do arquivo.

Se um erro ocorrer, retornará 0. Em sucesso, retorna 1.

O ponteiro de arquivo tem que ser válido e tem que apontar para um arquivo aberto com sucesso por fopen().

Nota: Se voc6e abriu um arquivo no modo acréscimo (append - "a"), qualque dado que escrever no arquivo será sempre anexado no final, não importando a posição do ponteiro.

Veja também fseek() e ftell().

rmdir

(PHP 3, PHP 4 )

rmdir -- Remove um diretório

Descrição

int rmdir ( string nomedodir)

Tenta remover o diretório com o nome de nomedodir. O diretório tem que estar vazio e as permissões relevantes autorizarem a esta operação. Retorna TRUE em caso de sucesso ou FALSE em falhas.

Veja também mkdir() e unlink().

set_file_buffer

set_file_buffer -- Sinônimo de stream_set_write_buffer()

Descrição

Esta função é um apelido para stream_set_write_buffer().

stat

(PHP 3, PHP 4 )

stat -- Obtem informações sobre um arquivo

Descrição

array stat ( string nomedoarquivo)

Pegar estatísticas sobre o arquivo com o nome de nomedoarquivo.

Retorna um array com as estatísticas do arquivo com os seguintes elementos:

  1. device

  2. inode

  3. inode protection mode

  4. número de links

  5. user id owner

  6. group id owner

  7. device type if inode device *

  8. tamanho em bytes

  9. time of last access

  10. time of last modification

  11. time of last change

  12. blocksize for filesystem I/O *

  13. number of blocks allocated

* - somente válido em sistemas supportando o tipo st_blksize--outros sistemas (por exemplo Windows) retornam -1.

Retorna FALSE em caso de erro.

stat() não pode ser utilizado em arquivos remotos.

Os resultados desta função são guardados em cache. Veja clearstatcache() para mais detalhes.

symlink

(PHP 3, PHP 4 )

symlink -- Cria um link simbólico

Descrição

int symlink ( string alvo, string link)

symlink() cria um link simbólico do alvo existente com o nome especificado em link.

Veja também link() para criar hard links, e readlink() junto com linkinfo().

tempnam

(PHP 3, PHP 4 )

tempnam -- Cria um nome de arquivo único

Descrição

string tempnam ( string dir, string prefix)

Cria um nome de arquivo temporário único no diretório especificado. Se o diretório não existe, tempnam() pode gerar o nome de arquivo no diretório temporário do sistema. Retorna o nome gerado.

Antes do PHP 4.0.6 o comportamento da função tempnam() era dependente do sistema. No Windows a váriavel de ambiente do sistema TMP irá sobreescrever o parâmetro dir; no Linux a váriavel de ambiente TMPDIR tem precedência, enquanto SVR4 irá sempre usar o parâmetro dir se o diretório para o qual ele aponta existe. Consulte a documentação do seu sistema para a função tempnam(3) na dúvida.

Retorna o nome do novo arquivo temporário, ou a string FALSE string em caso de erro.

Exemplo 1. exemplo de tempnam()

$tmpfname = tempnam ("/tmp", "FOO");

$fp = fopen($tmpfname, "w");
fwrite($fp, "writing to tempfile");
fclose($fp);

// fazer alguma coisa

unlink($tmpfname);

Nota: O comportamento desta função mudou na versão 4.0.3. O arquivo temporário é também criado para evitar uma condição de corrida (race) onde o arquivo pode aparecer no filesystem entre o tempo que a string foi gerada e antes que o script tem tempo para criar o arquivo. Note que você precisa remover o arquivo caso não vá mais utilizá-lo, pois isso não é feito automaticamente.

Veja também tmpfile() e unlink().

tmpfile

(PHP 3>= 3.0.13, PHP 4 )

tmpfile -- Cria um arquivo temporário

Descrição

int arqtmp ( void)

Cria um arquivo temporário com um nome único em modo de gravação, retornando o handle do arquivo em modo similar ao retornado por fopen(). O arquivo é automáticamente apagado quando fechado (usando fclose()), ou quando o script acaba.

Para detalhes consulte a documentação do seu sistem na função tmpfile(3), assim como o header stdio.h.

Exemplo 1. exemplo de tmpfile()

$temp = tmpfile();
fwrite($temp, "escrevendo no arquivo temporario");
fclose($temp); // isto remove o arquivo

Veja também tempnam().

touch

(PHP 3, PHP 4 )

touch -- Muda o tempo de modificação do arquivo

Descrição

int touch ( string filename [, int time [, int atime]])

Tenta mudar o tempo de acesso e modificação do arquivo filename para o valor informado em time. Se a opção time não é informada, o hora atual será usado. Isto é o equivalente ao que comando (Unix) utime faz. Se a terceira opção atime for passada, o tempo de acesso do arquivo informado será modificado para o valor de atime. Note que a data/hora do último acesso do arquivo sempre é alterado, independentemente do número de parâmetros.

Se o arquivo não existe, ele é criado.

Retorna TRUE em caso de sucesso ou FALSE em falhas.

Exemplo 1. exemplo da função touch()

if (touch ($nomedoarquivo)) {
    print "o tempo do $nomedoarquivo foi modificado
           para o dia e hora de atuais";
} else {
    print "Desculpe, não foi possivel modificar o tempo de $nomedoarquivo";
}

umask

(PHP 3, PHP 4 )

umask -- Modificar a umask atual

Descrição

int umask ( [int mask])

umask() modifica o umask do PHP para o mask & 0777 e retorna o umask antigo. Quando o PHP está sendo utilizado como um módulo do servidor, o umask é restaurado ao final de cada pedido.

umask() sem argumentos simplesmente retorna o umask atual.

unlink

(PHP 3, PHP 4 )

unlink -- Deleta um arquivo

Descrição

int unlink ( string nomedoarquivo)

Deleta nomedoarquivo. Similar a função C no Unix unlink().

Retorna TRUE em caso de sucesso ou FALSE em falhas.

Veja também rmdir() para remover diretórios.

XXXI. Forms Data Format functions

Introdução

Forms Data Format (FDF) is a format for handling forms within PDF documents. You should read the documentation at http://partners.adobe.com/asn/developer/acrosdk/forms.html for more information on what FDF is and how it is used in general.

The general idea of FDF is similar to HTML forms. The difference is basically the format how data is transmitted to the server when the submit button is pressed (this is actually the Form Data Format) and the format of the form itself (which is the Portable Document Format, PDF). Processing the FDF data is one of the features provided by the fdf functions. But there is more. One may as well take an existing PDF form and populated the input fields with data without modifying the form itself. In such a case one would create a FDF document (fdf_create()) set the values of each input field (fdf_set_value()) and associate it with a PDF form (fdf_set_file()). Finally it has to be sent to the browser with MimeType application/vnd.fdf. The Acrobat reader plugin of your browser recognizes the MimeType, reads the associated PDF form and fills in the data from the FDF document.

If you look at an FDF-document with a text editor you will find a catalogue object with the name FDF. Such an object may contain a number of entries like Fields, F, Status etc.. The most commonly used entries are Fields which points to a list of input fields, and F which contains the filename of the PDF-document this data belongs to. Those entries are referred to in the FDF documentation as /F-Key or /Status-Key. Modifying this entries is done by functions like fdf_set_file() and fdf_set_status(). Fields are modified with fdf_set_value(), fdf_set_opt() etc..


Requisitos

You need the FDF toolkit SDK available from http://partners.adobe.com/asn/developer/acrosdk/forms.html. As of PHP 4.3 you need at least SDK version 5.0. The FDF toolkit library is available in binary form only, platforms supported by Adobe are Win32, Linux, Solaris and AIX.


Instalação

You must compile PHP with --with-fdftk[=DIR].

Nota: If you run into problems configuring PHP with fdftk support, check whether the header file fdftk.h and the library libfdftk.so are at the right place. The configure script supports both the directory structure of the FDF SDK distribution and the usual DIR/include / DIR/lib layout, so you can point it either directly to the unpacked distribution directory or put the header file and the appropriate library for your platform into e.g. /usr/local/include and /usr/local/lib and configure with --with-fdftk=/usr/local.

Note to Win32 Users: In order to enable this module on a Windows environment, you must copy fdftk.dll from the DLL folder of the PHP/Win32 binary package to the SYSTEM32 folder of your windows machine. (Ex: C:\WINNT\SYSTEM32 or C:\WINDOWS\SYSTEM32)


Configuração durante execução

Esta extenção não define nenhum parâmetro de configuração no php.ini.


Tipos Resource

fdf

Most fdf functions require a fdf resource as their first parameter. A fdf resource is a handle to an opened fdf file. fdf resources may be obtained using fdf_create(), fdf_open() and fdf_open_string().


Constantes Predefinidas

As contantes abaixo são definidas por esta extensão e somente estarão disponíveis quando a extensão foi compilada com o PHP ou carregada dinamicamente durante a execução.

FDFValue (integer)

FDFStatus (integer)

FDFFile (integer)

FDFID (integer)

FDFFf (integer)

FDFSetFf (integer)

FDFClearFf (integer)

FDFFlags (integer)

FDFSetF (integer)

FDFClrF (integer)

FDFAP (integer)

FDFAS (integer)

FDFAction (integer)

FDFAA (integer)

FDFAPRef (integer)

FDFIF (integer)

FDFEnter (integer)

FDFExit (integer)

FDFDown (integer)

FDFUp (integer)

FDFFormat (integer)

FDFValidate (integer)

FDFKeystroke (integer)

FDFCalculate (integer)

FDFNormalAP (integer)

FDFRolloverAP (integer)

FDFDownAP (integer)


Exemplos

The following examples shows just the evaluation of form data.

Exemplo 1. Evaluating a FDF document

<?php
// Open fdf from input string provided by the extension
// The pdf form contained several input text fields with the names
// volume, date, comment, publisher, preparer, and two checkboxes
// show_publisher and show_preparer.
$fdf = fdf_open_string($HTTP_FDF_DATA);
$volume = fdf_get_value($fdf, "volume");
echo "The volume field has the value '<B>$volume</B>'<BR>";

$date = fdf_get_value($fdf, "date");
echo "The date field has the value '<B>$date</B>'<BR>";

$comment = fdf_get_value($fdf, "comment");
echo "The comment field has the value '<B>$comment</B>'<BR>";

if(fdf_get_value($fdf, "show_publisher") == "On") {
  $publisher = fdf_get_value($fdf, "publisher");
  echo "The publisher field has the value '<B>$publisher</B>'<BR>";
} else
  echo "Publisher shall not be shown.<BR>";

if(fdf_get_value($fdf, "show_preparer") == "On") {
  $preparer = fdf_get_value($fdf, "preparer");
  echo "The preparer field has the value '<B>$preparer</B>'<BR>";
} else
  echo "Preparer shall not be shown.<BR>";
fdf_close($fdf);
?>

Índice
fdf_add_doc_javascript -- Adds javascript code to the FDF document
fdf_add_template -- Adds a template into the FDF document
fdf_close -- Close an FDF document
fdf_create -- Create a new FDF document
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_get_attachment -- Extracts uploaded file embedded in the FDF
fdf_get_encoding -- Get the value of the /Encoding key
fdf_get_file -- Get the value of the /F key
fdf_get_status -- Get the value of the /STATUS key
fdf_get_value -- Get the value of a field
fdf_get_version -- Gets version number for FDF api or file
fdf_header -- Sets FDF-specific output headers
fdf_next_field_name -- Get the next field name
fdf_open_string -- Read a FDF document from a string
fdf_open -- Open a FDF document
fdf_save_string -- Returns the FDF document as a string
fdf_save -- Save a FDF document
fdf_set_ap -- Set the appearance of a field
fdf_set_encoding -- Sets FDF character encoding
fdf_set_file -- Set PDF document to display FDF data in
fdf_set_flags -- Sets a flag of a field
fdf_set_javascript_action -- Sets an javascript action of a field
fdf_set_opt -- Sets an option of a field
fdf_set_status -- Set the value of the /STATUS key
fdf_set_submit_form_action -- Sets a submit form action of a field
fdf_set_target_frame -- Set target frame for form display
fdf_set_value -- Set the value of a field
fdf_set_version -- Sets version number for a FDF file

fdf_add_doc_javascript

(PHP 4 >= 4.3.0)

fdf_add_doc_javascript -- Adds javascript code to the FDF document

Description

bool fdf_add_doc_javascript ( resource fdfdoc, string script_name, string script_code)

Adds a script to the FDF, which Acrobat then adds to the doc-level scripts of a document, once the FDF is imported into it. It is strongly suggested to use '\r' for linebreaks within script_code.

Exemplo 1. Adding JavaScript code to a FDF

<?php
$fdf = fdf_create();
fdf_add_doc_javascript($fdf, "PlusOne", "function PlusOne(x)\r{\r  return x+1;\r}\r");
fdf_save($fdf);
?>

will create a FDF like this:

%FDF-1.2
%âãÏÓ
1 0 obj
<< 
/FDF << /JavaScript << /Doc [ (PlusOne)(function PlusOne\(x\)\r{\r  return x+1;\r}\r)] >> >> 
>> 
endobj
trailer
<<
/Root 1 0 R 

>>
%%EOF

fdf_add_template

(PHP 3>= 3.0.13, PHP 4 )

fdf_add_template -- Adds a template into the FDF document

Description

bool fdf_add_template ( int fdfdoc, int newpage, string filename, string template, int rename)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

fdf_close

(PHP 3>= 3.0.6, PHP 4 )

fdf_close -- Close an FDF document

Description

bool fdf_close ( resource fdf_document)

The fdf_close() function closes the FDF document.

See also fdf_open().

fdf_create

(PHP 3>= 3.0.6, PHP 4 )

fdf_create -- Create a new FDF document

Description

resource fdf_create ( void)

The fdf_create() creates a new FDF document. This function is needed if one would like to populate input fields in a PDF document with data.

Exemplo 1. Populating a PDF document

<?php
$outfdf = fdf_create();
fdf_set_value($outfdf, "volume", $volume, 0);

fdf_set_file($outfdf, "http:/testfdf/resultlabel.pdf");
fdf_save($outfdf, "outtest.fdf");
fdf_close($outfdf);
Header("Content-type: application/vnd.fdf");
$fp = fopen("outtest.fdf", "r");
fpassthru($fp);
unlink("outtest.fdf");
?>

See also fdf_close(), fdf_save(), fdf_open().

fdf_errno

(PHP 4 >= 4.3.0)

fdf_errno -- Return error code for last fdf operation

Description

int fdf_errno ( void)

fdf_errno() returns the error code set by the last fdf_...() function call. This is zero for a successfull operation or a non-zero error code on failure. A textual description may be obtained using the fdf_error() function.

See also fdf_error().

fdf_error

(PHP 4 >= 4.3.0)

fdf_error -- Return error description for fdf error code

Description

string fdf_error ( [int error_code])

fdf_error() returns a textual description for the fdf error code given in error_code. The function uses the internal error code set by the last operation if no error_code is given, so fdf_error() is a convenient shortcut for fdf_error(fdf_errno()).

See also fdf_errno().

fdf_get_ap

(PHP 4 >= 4.3.0)

fdf_get_ap -- Get the appearance of a field

Description

bool fdf_get_ap ( resource fdf_document, string field, int face, string filename)

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, FDFRolloverAP and FDFDownAP. The appearance is stored in filename.

fdf_get_attachment

(PHP 4 >= 4.3.0)

fdf_get_attachment -- Extracts uploaded file embedded in the FDF

Description

array fdf_get_attachment ( resource fdf_document, string fieldname, string savepath)

Extracts a file uploaded by means of the "file selection" field fieldname and stores it under savepath. savepath may be the name of a plain file or an existing directory in which the file is to be created under its original name. Any existing file under the same name will be overwritten.

Nota: There seems to be no other way to find out the original filename but to store the file using a directory as savepath and check for the basename it was stored under.

The returned array contains the following fields:

  • path - path were the file got stored

    size - size of the stored file in bytes

    type - mimetype if given in the FDF

Exemplo 1. Storing an uploaded file

<?php 
  $fdf = fdf_open_string($HTTP_FDF_DATA);
  $data = fdf_get_attachment($fdf, "filename", "/tmpdir");
  echo "The uploaded file is stored in $data[path]";
?>

fdf_get_encoding

(PHP 4 >= 4.3.0)

fdf_get_encoding -- Get the value of the /Encoding key

Description

string fdf_get_encoding ( resource fdf_document)

The fdf_get_encoding() returns the value of the /Encoding key. An empty string is returned if the default PDFDocEncoding/Unicode scheme is used.

See also fdf_set_encoding().

fdf_get_file

(PHP 3>= 3.0.6, PHP 4 )

fdf_get_file -- Get the value of the /F key

Description

string fdf_get_file ( resource fdf_document)

The fdf_set_file() returns the value of the /F key.

See also fdf_set_file().

fdf_get_status

(PHP 3>= 3.0.6, PHP 4 )

fdf_get_status -- Get the value of the /STATUS key

Description

string fdf_get_status ( resource fdf_document)

The fdf_get_status() returns the value of the /STATUS key.

See also fdf_set_status().

fdf_get_value

(PHP 3>= 3.0.6, PHP 4 )

fdf_get_value -- Get the value of a field

Description

string fdf_get_value ( resource fdf_document, string fieldname [, int which])

The fdf_get_value() function returns the value for the requested fieldname.

Elements of an array field can be retrieved by passing the optional which, starting at zero. For non-array fields the optional parameter which will be ignored.

Nota: Array support and optional which parameter were added in PHP 4.3.

See also fdf_set_value().

fdf_get_version

(PHP 4 >= 4.3.0)

fdf_get_version -- Gets version number for FDF api or file

Description

string fdf_get_version ( [resource fdf_document])

This function will return the fdf version for the given fdf_document, or the toolkit api version number if no parameter is given.

For the current FDF toolkit 5.0 the api version number is '5.0' and the document version number is either '1.2', '1.3' or '1.4'.

See also fdf_set_version().

fdf_header

(PHP 4 >= 4.3.0)

fdf_header -- Sets FDF-specific output headers

Description

bool fdf_header ( void)

This is a convenience function to set appropriate HTTP headers for FDF output. It sets the Content-type: to application/vnd.fdf.

fdf_next_field_name

(PHP 3>= 3.0.6, PHP 4 )

fdf_next_field_name -- Get the next field name

Description

string fdf_next_field_name ( resource fdf_document [, string fieldname])

The fdf_next_field_name() function returns the name of the field after the field in fieldname or the field name of the first field if the second parameter is NULL.

Exemplo 1. Detecting all fieldnames in a FDF

<?php
  $fdf = fdf_open($HTTP_FDF_DATA);
  for($field = fdf_next_field_name($fdf); 
     $field != ""; 
     $field = fdf_next_field_name($fdf, $field)) {
    echo "field: $field\n";
  } 
?>

See also fdf_enum_fields() and fdf_get_value().

fdf_open_string

(PHP 4 >= 4.3.0)

fdf_open_string -- Read a FDF document from a string

Description

resource fdf_open_string ( string fdf_data)

The fdf_open_string() function reads form data from a string. fdf_data must contain the data as returned from a PDF form or created using fdf_create() and fdf_save_string().

You can fdf_open_string() together with $HTTP_FDF_DATA to process fdf form input from a remote client.

Exemplo 1. Accessing the form data

<?php
$fdf = fdf_open_string($HTTP_FDF_DATA);
...
fdf_close($fdf);
?>

See also fdf_open(), fdf_close(), fdf_create() and fdf_save_string().

fdf_open

(PHP 3>= 3.0.6, PHP 4 )

fdf_open -- Open a FDF document

Description

resource fdf_open ( string filename)

The fdf_open() function opens a file with form data. This file must contain the data as returned from a PDF form or created using fdf_create() and fdf_save().

You can process the results of a PDF form POST request by writing the data recieved in $HTTP_FDF_DATA to a file and open it using fdf_open(). Starting with PHP 4.3 you can also use fdf_open_string() which handles temporary file creation and cleanup for you.

Exemplo 1. Accessing the form data

<?php
// Save the FDF data into a temp file
$fdffp = fopen("test.fdf", "w");
fwrite($fdffp, $HTTP_FDF_DATA, strlen($HTTP_FDF_DATA));
fclose($fdffp);

// Open temp file and evaluate data
$fdf = fdf_open("test.fdf");
...
fdf_close($fdf);
?>

See also fdf_open_string(), fdf_close(), fdf_create() and fdf_save().

fdf_save_string

(PHP 4 >= 4.3.0)

fdf_save_string -- Returns the FDF document as a string

Description

string fdf_save_string ( resource fdf_document)

The fdf_save_string() function returns the FDF document as a string.

Exemplo 1. Retrieving FDF as a string

<?php
$fdf = fdf_create();
fdf_set_value($fdf, "foo", "bar");
$str = fdf_save_string($fdf);
fdf_close($fdf);
echo $str;
?>

will output something like

%FDF-1.2
%âãÏÓ
1 0 obj
<< 
/FDF << /Fields 2 0 R >> 
>> 
endobj
2 0 obj
[ 
<< /T (foo)/V (bar)>> 
]
endobj
trailer
<<
/Root 1 0 R 

>>
%%EOF

See also fdf_save(), fdf_open_string(), fdf_create() and fdf_close().

fdf_save

(PHP 3>= 3.0.6, PHP 4 )

fdf_save -- Save a FDF document

Description

bool fdf_save ( resource fdf_document [, string filename])

The fdf_save() function saves a FDF document. The resulting FDF will be written to filename. Without a filename fdf_save() will write the FDF to the default PHP output stream.

See also fdf_save_string(), fdf_create() and fdf_close().

fdf_set_ap

(PHP 3>= 3.0.6, PHP 4 )

fdf_set_ap -- Set the appearance of a field

Description

bool fdf_set_ap ( resource fdf_document, string field_name, int face, string filename, int page_number)

The fdf_set_ap() function sets the appearance of a field (i.e. the value of the /AP key). The possible values of face are FDFNormalAP, FDFRolloverAP and FDFDownAP.

fdf_set_encoding

(PHP 4 >= 4.1.0)

fdf_set_encoding -- Sets FDF character encoding

Description

bool fdf_set_encoding ( resource fdf_document, string encoding)

fdf_set_encoding() sets the character encoding in FDF document fdf_document. encoding should be the valid encoding name. Currently the following values are supported: "Shift-JIS", "UHC", "GBK","BigFive". An empty string resets the encoding to the default PDFDocEncoding/Unicode scheme.

fdf_set_file

(PHP 3>= 3.0.6, PHP 4 )

fdf_set_file -- Set PDF document to display FDF data in

Description

bool fdf_set_file ( resource fdf_document, string url [, string target_frame])

The fdf_set_file() selects a different PDF document to display the form results in then the form it originated from. The url needs to be given as an absolute URL.

The frame to display the document in may be selected using the optional parameter target_frame or the function fdf_set_target_frame().

Exemplo 1. Passing FDF data to a second form

<?php
  /* set content type for Adobe FDF */
  fdf_header();

  /* start new fdf */
  $fdf = fdf_create();
    
  /* set field "foo" to value "bar" */
  $fdf_set_value($fdf, "foo", "bar");

  /* tell client to display FDF data using "fdf_form.pdf" */
  fdf_set_file($fdf, "http://www.example.com/fdf_form.pdf");

  /* output fdf */
  fdf_save();

  /* clean up */
  fdf_close();
?>

See also fdf_get_file() and fdf_set_target_frame().

fdf_set_flags

(PHP 4 >= 4.0.2)

fdf_set_flags -- Sets a flag of a field

Description

bool fdf_set_flags ( resource fdf_document, string fieldname, int whichFlags, int newFlags)

The fdf_set_flags() sets certain flags of the given field fieldname.

See also fdf_set_opt().

fdf_set_javascript_action

(PHP 4 >= 4.0.2)

fdf_set_javascript_action -- Sets an javascript action of a field

Description

bool fdf_set_javascript_action ( resource fdf_document, string fieldname, int trigger, string script)

fdf_set_javascript_action() sets a javascript action for the given field fieldname.

See also fdf_set_submit_form_action().

fdf_set_opt

(PHP 4 >= 4.0.2)

fdf_set_opt -- Sets an option of a field

Description

bool fdf_set_opt ( resource fdf_document, string fieldname, int element, string str1, string str2)

The fdf_set_opt() sets options of the given field fieldname.

See also fdf_set_flags().

fdf_set_status

(PHP 3>= 3.0.6, PHP 4 )

fdf_set_status -- Set the value of the /STATUS key

Description

bool fdf_set_status ( resource fdf_document, string status)

The fdf_set_status() sets the value of the /STATUS key. When a client recieves a FDF with a status set it will present the value in an alert box.

See also fdf_get_status().

fdf_set_submit_form_action

(PHP 4 >= 4.0.2)

fdf_set_submit_form_action -- Sets a submit form action of a field

Description

bool fdf_set_submit_form_action ( resource fdf_document, string fieldname, int trigger, string script, int flags)

The fdf_set_submit_form_action() sets a submit form action for the given field fieldname.

See also fdf_set_javascript_action().

fdf_set_target_frame

(PHP 4 >= 4.3.0)

fdf_set_target_frame -- Set target frame for form display

Description

bool fdf_set_target_frame ( resource fdf_document, string frame_name)

Sets the target frame to display a result PDF defined with fdf_save_file() in.

See also fdf_save_file().

fdf_set_value

(PHP 3>= 3.0.6, PHP 4 )

fdf_set_value -- Set the value of a field

Description

bool fdf_set_value ( resource fdf_document, string fieldname, mixed value [, int isName])

The fdf_set_value() function sets the value for a field named fieldname. The value will be stored as a string unless it is an array. In this case all array elements will be stored as a value array.

Nota: In older versions of the fdf toolkit last parameter determined if the field value was to be converted to a PDF Name (isName = 1) or set to a PDF String (isName = 0). The value is no longer used in the current toolkit version 5.0. For compatibility reasons it is still supported as an optional parameter beginning with PHP 4.3, but ignored internaly.

Support for value arrays was added in PHP 4.3.

See also fdf_get_value() and fdf_remove_item().

fdf_set_version

(PHP 4 >= 4.3.0)

fdf_set_version -- Sets version number for a FDF file

Description

string fdf_set_version ( resource fdf_document, string version)

This function will set the fdf version for the given fdf_document. Some features supported by this 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'.

See also fdf_get_version().

XXXII. FriBiDi functions

Introdução

FriBiDi is a free implementation of the Unicode Bidirectional Algorithm.


Requisitos

You must download and install the FriBiDi package.


Instalação

To enable FriBiDi support in PHP you must compile --with-fribidi[=DIR] where DIR is the FriBiDi install directory.


Configuração durante execução


Tipos Resource


Constantes Predefinidas

As contantes abaixo são definidas por esta extensão e somente estarão disponíveis quando a extensão foi compilada com o PHP ou carregada dinamicamente durante a execução.

FRIBIDI_CHARSET_UTF8 (integer)

FRIBIDI_CHARSET_8859_6 (integer)

FRIBIDI_CHARSET_8859_8 (integer)

FRIBIDI_CHARSET_CP1255 (integer)

FRIBIDI_CHARSET_CP1256 (integer)

FRIBIDI_CHARSET_ISIRI_3342 (integer)

Índice
fribidi_log2vis -- Convert a logical string to a visual one

fribidi_log2vis

(PHP 4 >= 4.0.4)

fribidi_log2vis -- Convert a logical string to a visual one

Description

string fribidi_log2vis ( string str, string direction, int charset)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

XXXIII. FTP functions

Introdução

The functions in this extension implement client access to file servers speaking the File Transfer Protocol (FTP) as defined in http://www.faqs.org/rfcs/rfc959.html.


Requisitos

Nenhuma biblioteca externa é necessária para compilar esta extensão.


Instalação

In order to use FTP functions with your PHP configuration, you should add the --enable-ftp option when installing PHP 4 or --with-ftp when using PHP 3.

The windows version of PHP has built in support for this extension. You do not need to load any additional extension in order to use these functions.


Configuração durante execução

Esta extenção não define nenhum parâmetro de configuração no php.ini.


Tipos Resource

This extension uses one resource type, which is the link identifier of the FTP connection, returned by ftp_connect().


Constantes Predefinidas

As contantes abaixo são definidas por esta extensão e somente estarão disponíveis quando a extensão foi compilada com o PHP ou carregada dinamicamente durante a execução.

FTP_ASCII (integer)

FTP_TEXT (integer)

FTP_BINARY (integer)

FTP_IMAGE (integer)

FTP_TIMEOUT_SEC (integer)

See ftp_set_option() for information.

The following constants were introduced in PHP 4.3.0.

FTP_AUTOSEEK (integer)

See ftp_set_option() for information.

FTP_AUTORESUME (integer)

Automatically determine resume position and start position for GET and PUT requests (only works if FTP_AUTOSEEK is enabled)

FTP_FAILED (integer)

Asynchronous transfer has failed

FTP_FINISHED (integer)

Asynchronous transfer has finished

FTP_MOREDATA (integer)

Asynchronous transfer is still active


Exemplos

Exemplo 1. FTP example

<?php
// set up basic connection
$conn_id = ftp_connect($ftp_server); 

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass); 

// check connection
if ((!$conn_id) || (!$login_result)) { 
        echo "FTP connection has failed!";
        echo "Attempted to connect to $ftp_server for user $ftp_user_name"; 
        exit; 
    } else {
        echo "Connected to $ftp_server, for user $ftp_user_name";
    }

// upload the file
$upload = ftp_put($conn_id, $destination_file, $source_file, FTP_BINARY); 

// check upload status
if (!$upload) { 
        echo "FTP upload has failed!";
    } else {
        echo "Uploaded $source_file to $ftp_server as $destination_file";
    }

// close the FTP stream 
ftp_close($conn_id); 
?>

Índice
ftp_cdup -- Changes to the parent directory
ftp_chdir -- Changes directories on a FTP server
ftp_chmod -- Set permissions on a file via FTP
ftp_close -- Closes an FTP connection
ftp_connect -- Opens an FTP connection
ftp_delete -- Deletes a file on the FTP server
ftp_exec -- Requests execution of a program on the FTP server
ftp_fget -- Downloads a file from the FTP server and saves to an open file
ftp_fput -- Uploads from an open file to the FTP server
ftp_get_option -- Retrieves various runtime behaviours of the current FTP stream
ftp_get -- Downloads a file from the FTP server
ftp_login -- Logs in to an FTP connection
ftp_mdtm -- Returns the last modified time of the given file
ftp_mkdir -- Creates a directory
ftp_nb_continue -- Continues retrieving/sending a file (non-blocking)
ftp_nb_fget -- Retrieves a file from the FTP server and writes it to an open file (non-blocking)
ftp_nb_fput -- Stores a file from an open file to the FTP server (non-blocking)
ftp_nb_get -- Retrieves a file from the FTP server and writes it to a local file (non-blocking)
ftp_nb_put -- Stores a file on the FTP server (non-blocking)
ftp_nlist -- Returns a list of files in the given directory
ftp_pasv -- Turns passive mode on or off
ftp_put -- Uploads a file to the FTP server
ftp_pwd -- Returns the current directory name
ftp_quit -- Closes an FTP connection
ftp_rawlist -- Returns a detailed list of files in the given directory
ftp_rename -- Renames a file on the FTP server
ftp_rmdir -- Removes a directory
ftp_set_option -- Set miscellaneous runtime FTP options
ftp_site -- Sends a SITE command to the server
ftp_size -- Returns the size of the given file
ftp_ssl_connect -- Opens an Secure SSL-FTP connection
ftp_systype -- Returns the system type identifier of the remote FTP server

ftp_cdup

(PHP 3>= 3.0.13, PHP 4 )

ftp_cdup -- Changes to the parent directory

Description

bool ftp_cdup ( resource ftp_stream)

Changes to the parent directory.

Retorna TRUE em caso de sucesso ou FALSE em falhas.

ftp_chdir

(PHP 3>= 3.0.13, PHP 4 )

ftp_chdir -- Changes directories on a FTP server

Description

bool ftp_chdir ( resource ftp_stream, string directory)

Changes to the specified directory.

Returns TRUE on success or FALSE on error.

ftp_chmod

(no version information, might be only in CVS)

ftp_chmod -- Set permissions on a file via FTP

Description

string ftp_chmod ( resource ftp_stream, int mode, string filename)

Sets the permissions on the remote file specified by filename to mode given as an octal value.

Returns the new file permissions on success or FALSE on error.

See Also: chmod()

ftp_close

(PHP 4 >= 4.2.0)

ftp_close -- Closes an FTP connection

Description

void ftp_close ( resource ftp_stream)

ftp_close() closes ftp_stream and releases the resource. After calling this function, you can no longer use the FTP connection and must create a new one with ftp_connect().

See also ftp_connect()

ftp_connect

(PHP 3>= 3.0.13, PHP 4 )

ftp_connect -- Opens an FTP connection

Description

resource ftp_connect ( string host [, int port [, int timeout]])

Returns a FTP stream on success or FALSE on error.

ftp_connect() opens an FTP connection to the specified host. The port parameter specifies an alternate port to connect to. If it is omitted or set to zero, then the default FTP port, 21, will be used.

The timeout parameter specifies the timeout for all subsequent network operations. If omitted, the default value is 90 seconds. The timeout can be changed and queried at any time with ftp_set_option() and ftp_get_option().

Nota: The timeout parameter became available in PHP 4.2.0.

ftp_delete

(PHP 3>= 3.0.13, PHP 4 )

ftp_delete -- Deletes a file on the FTP server

Description

bool ftp_delete ( resource ftp_stream, string path)

ftp_delete() deletes the file specified by path from the FTP server.

Retorna TRUE em caso de sucesso ou FALSE em falhas.

ftp_exec

(PHP 4 >= 4.0.3)

ftp_exec -- Requests execution of a program on the FTP server

Description

bool ftp_exec ( resource ftp_stream, string command)

Sends a SITE EXEC command request to the FTP server. Returns the output of the command if successful; otherwise returns FALSE.

ftp_fget

(PHP 3>= 3.0.13, PHP 4 )

ftp_fget -- Downloads a file from the FTP server and saves to an open file

Description

bool ftp_fget ( resource ftp_stream, resource handle, string remote_file, int mode [, int resumepos])

ftp_fget() retrieves remote_file from the FTP server, and writes it to the given file pointer, handle. The transfer mode specified must be either FTP_ASCII or FTP_BINARY.

Nota: The resumepos parameter was added in PHP 4.3.0.

Retorna TRUE em caso de sucesso ou FALSE em falhas.

See also ftp_get().

ftp_fput

(PHP 3>= 3.0.13, PHP 4 )

ftp_fput -- Uploads from an open file to the FTP server

Description

bool ftp_fput ( resource ftp_stream, string remote_file, resource handle, int mode [, int startpos])

ftp_fput() uploads the data from the file pointer handle until the end of the file is reached. The results are stored in remote_file on the FTP server. The transfer mode specified must be either FTP_ASCII or FTP_BINARY.

Nota: The startpos parameter was added in PHP 4.3.0.

Retorna TRUE em caso de sucesso ou FALSE em falhas.

ftp_get_option

(PHP 4 >= 4.2.0)

ftp_get_option -- Retrieves various runtime behaviours of the current FTP stream

Description

mixed ftp_get_option ( resource ftp_stream, int option)

Nota: This function is only available in CVS.

Returns the value on success or FALSE if the given option is not supported. In the latter case, a warning message is also thrown.

This function returns the value for the requested option from the specified ftp_stream . Currently, the following options are supported:

Tabela 1. Supported runtime FTP options

FTP_TIMEOUT_SEC Returns the current timeout used for network related operations.

Exemplo 1. ftp_get_option() example

// Get the timeout of the given FTP stream
$timeout = ftp_get_option($conn_id, FTP_TIMEOUT_SEC);

ftp_get

(PHP 3>= 3.0.13, PHP 4 )

ftp_get -- Downloads a file from the FTP server

Description

bool ftp_get ( resource ftp_stream, string local_file, string remote_file, int mode [, int resumepos])

ftp_get() retrieves remote_file from the FTP server, and saves it to local_file locally. The transfer mode specified must be either FTP_ASCII or FTP_BINARY.

Nota: The resumepos parameter was added in PHP 4.3.0.

Retorna TRUE em caso de sucesso ou FALSE em falhas.

See also ftp_fget() and ftp_async_get().

ftp_login

(PHP 3>= 3.0.13, PHP 4 )

ftp_login -- Logs in to an FTP connection

Description

bool ftp_login ( resource ftp_stream, string username, string password)

Logs in to the given FTP stream.

Retorna TRUE em caso de sucesso ou FALSE em falhas.

ftp_mdtm

(PHP 3>= 3.0.13, PHP 4 )

ftp_mdtm -- Returns the last modified time of the given file

Description

int ftp_mdtm ( resource ftp_stream, string remote_file)

ftp_mdtm() checks the last modified time for a file, and returns it as a UNIX timestamp. If an error occurs, or the file does not exist, -1 is returned.

Returns a UNIX timestamp on success, or -1 on error.

Nota: Not all servers support this feature!

Nota: ftp_mdtm() does not work with directories.

ftp_mkdir

(PHP 3>= 3.0.13, PHP 4 )

ftp_mkdir -- Creates a directory

Description

string ftp_mkdir ( resource ftp_stream, string directory)

Creates the specified directory.

Returns the newly created directory name on success or FALSE on error.

ftp_nb_continue

(PHP 4 >= 4.3.0)

ftp_nb_continue -- Continues retrieving/sending a file (non-blocking)

Description

bool ftp_nb_continue ( resource ftp_stream)

Continues retrieving/sending a file nbronously

Returns FTP_FAILED or FTP_FINISHED or FTP_MOREDATA.

ftp_nb_fget

(PHP 4 >= 4.3.0)

ftp_nb_fget -- Retrieves a file from the FTP server and writes it to an open file (non-blocking)

Description

bool ftp_nb_fget ( resource ftp_stream, resource handle, string remote_file, int mode [, int resumepos])

ftp_nb_fget() retrieves remote_file from the FTP server, and writes it to the given file pointer, handle. The transfer mode specified must be either FTP_ASCII or FTP_BINARY. The difference between this function and the ftp_fget() is that this function retrieves the file asynchronously, so your program can perform other operations while the file is being downloaded.

Retorna TRUE em caso de sucesso ou FALSE em falhas.

See also ftp_nb_get().

ftp_nb_fput

(PHP 4 >= 4.3.0)

ftp_nb_fput -- Stores a file from an open file to the FTP server (non-blocking)

Description

bool ftp_nb_fput ( resource ftp_stream, string remote_file, resource handle, int mode [, int startpos])

ftp_nb_fput() uploads the data from the file pointer handle until it reaches the end of the file. The results are stored in remote_file on the FTP server. The transfer mode specified must be either FTP_ASCII or FTP_BINARY. The difference between this function and the ftp_fput() is that this function uploads the file asynchronously, so your program can perform other operations while the file is being downloaded.

Retorna TRUE em caso de sucesso ou FALSE em falhas.

See also ftp_nb_put(), ftp_nb_continue(), ftp_put() and ftp_fput().

ftp_nb_get

(PHP 4 >= 4.3.0)

ftp_nb_get -- Retrieves a file from the FTP server and writes it to a local file (non-blocking)

Description

bool ftp_nb_get ( resource ftp_stream, string local_file, string remote_file, int mode [, int resumepos])

ftp_nb_get() retrieves remote_file from the FTP server, and saves it to local_file locally. The transfer mode specified must be either FTP_ASCII or FTP_BINARY. The difference between this function and the ftp_get() is that this function retrieves the file asynchronously, so your program can perform other operations while the file is being downloaded.

Retorna TRUE em caso de sucesso ou FALSE em falhas.

Exemplo 1. ftp_nb_get() example

// Initate the download
$ret = ftp_nb_get($my_connection, "test", "README", FTP_BINARY);
while ($ret == FTP_MOREDATA) {
   
   // Do whatever you want
   echo ".";

   // Continue downloading...
   $ret = ftp_nb_continue ($my_connection);
}
if ($ret != FTP_FINISHED) {
   echo "There was an error downloading the file...";
   exit(1);
}

Exemplo 2. Resuming a download with ftp_nb_get()

// Initate 
$ret = ftp_nb_get ($my_connection, "test", "README", FTP_BINARY, 
                      filesize("test"));
// OR: $ret = ftp_nb_get ($my_connection, "test", "README", 
//                           FTP_BINARY, FTP_AUTORESUME);
while ($ret == FTP_MOREDATA) {
   
   // Do whatever you want
   echo ".";

   // Continue downloading...
   $ret = ftp_nb_continue ($my_connection);
}
if ($ret != FTP_FINISHED) {
   echo "There was an error downloading the file...";
   exit(1);
}

Exemplo 3. Resuming a download at position 100 to a new file with ftp_nb_get()

// Disable Autoseek
ftp_set_option ($my_connection, FTP_AUTOSEEK, FALSE);

// Initiate
$ret = ftp_nb_get ($my_connection, "newfile", "README", FTP_BINARY, 100);
while ($ret == FTP_MOREDATA) {

   ...
   
   // Continue downloading...
   $ret = ftp_nb_continue ($my_connection);
}

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 FTP_AUTOSEEK, the first 100 bytes of newfile will be '\0'.

See also ftp_nb_fget(), ftp_nb_continue(), ftp_get() and ftp_fget().

ftp_nb_put

(PHP 4 >= 4.3.0)

ftp_nb_put -- Stores a file on the FTP server (non-blocking)

Description

bool ftp_nb_put ( resource ftp_stream, string remote_file, string local_file, int mode [, int startpos])

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

Retorna TRUE em caso de sucesso ou FALSE em falhas.

Exemplo 1. ftp_nb_put() example

// Initiate the Upload
$ret = ftp_nb_put($my_connection, "test.remote", "test.local", FTP_BINARY);
while ($ret == FTP_MOREDATA) {
   
   // Do whatever you want
   echo ".";

   // Continue uploading...
   $ret = ftp_nb_continue ($my_connection);
}
if ($ret != FTP_FINISHED) {
   echo "There was an error uploading the file...";
   exit(1);
}

Exemplo 2. Resuming an upload with ftp_nb_put()

// Initiate
$ret = ftp_nb_put ($my_connection, "test.remote", "test.local", 
                      FTP_BINARY, ftp_size("test.remote"));
// OR: $ret = ftp_nb_put ($my_connection, "test.remote", "test.local", 
//                           FTP_BINARY, FTP_AUTORESUME);

while ($ret == FTP_MOREDATA) {
   
   // Do whatever you want
   echo ".";

   // Continue uploading...
   $ret = ftp_nb_continue ($my_connection);
}
if ($ret != FTP_FINISHED) {
   echo "There was an error uploading the file...";
   exit(1);
}

See also ftp_nb_fput(), ftp_nb_continue(), ftp_put() and ftp_fput().

ftp_nlist

(PHP 3>= 3.0.13, PHP 4 )

ftp_nlist -- Returns a list of files in the given directory

Description

array ftp_nlist ( resource ftp_stream, string directory)

Returns an array of filenames from the specified directory on success or FALSE on error.

ftp_pasv

(PHP 3>= 3.0.13, PHP 4 )

ftp_pasv -- Turns passive mode on or off

Description

bool ftp_pasv ( resource ftp_stream, bool pasv)

ftp_pasv() turns on passive mode if the pasv parameter is TRUE. It turns off passive mode if pasv is FALSE. In passive mode, data connections are initiated by the client, rather than by the server.

Retorna TRUE em caso de sucesso ou FALSE em falhas.

ftp_put

(PHP 3>= 3.0.13, PHP 4 )

ftp_put -- Uploads a file to the FTP server

Description

bool ftp_put ( resource ftp_stream, string remote_file, string local_file, int mode [, int startpos])

ftp_put() stores local_file on the FTP server, as remote_file. The transfer mode specified must be either FTP_ASCII or FTP_BINARY.

Nota: The startpos parameter was added in PHP 4.3.0.

Retorna TRUE em caso de sucesso ou FALSE em falhas.

Exemplo 1. ftp_put() example

$upload = ftp_put($conn_id, $destination_file, $source_file, FTP_ASCII);

ftp_pwd

(PHP 3>= 3.0.13, PHP 4 )

ftp_pwd -- Returns the current directory name

Description

string ftp_pwd ( resource ftp_stream)

Returns the current directory or FALSE on error.

ftp_quit

(PHP 3>= 3.0.13, PHP 4 )

ftp_quit -- Closes an FTP connection

Description

void ftp_quit ( resource ftp_stream)

ftp_quit() is an alias for ftp_close().

ftp_rawlist

(PHP 3>= 3.0.13, PHP 4 )

ftp_rawlist -- Returns a detailed list of files in the given directory

Description

array ftp_rawlist ( resource ftp_stream, string directory)

ftp_rawlist() executes the FTP LIST command, and returns the result as an array. Each array element corresponds to one line of text. The output is not parsed in any way. The system type identifier returned by ftp_systype() can be used to determine how the results should be interpreted.

ftp_rename

(PHP 3>= 3.0.13, PHP 4 )

ftp_rename -- Renames a file on the FTP server

Description

bool ftp_rename ( resource ftp_stream, string from, string to)

ftp_rename() renames the file or directory that is currently named from to the new name to, using the FTP stream ftp_stream.

Retorna TRUE em caso de sucesso ou FALSE em falhas.

ftp_rmdir

(PHP 3>= 3.0.13, PHP 4 )

ftp_rmdir -- Removes a directory

Description

bool ftp_rmdir ( resource ftp_stream, string directory)

Removes the specified directory.

Retorna TRUE em caso de sucesso ou FALSE em falhas.

ftp_set_option

(PHP 4 >= 4.2.0)

ftp_set_option -- Set miscellaneous runtime FTP options

Description

bool ftp_set_option ( resource ftp_stream, int option, mixed value)

Nota: This function is only available in CVS.

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 expected value for the given option.

This function controls various runtime options for the specified FTP stream. The value parameter depends on which option parameter is chosen to be altered. Currently, the following options are supported:

Tabela 1. Supported runtime FTP options

FTP_TIMEOUT_SEC Changes the timeout in seconds used for all network related functions. value must be an integer that is greater than 0. The default timeout is 90 seconds.
FTP_AUTOSEEK When enabled, GET or PUT requests with a resumepos or startpos parameter will first seek to the requested position within the file. This is enabled by default.

Exemplo 1. ftp_set_option() example

// Set the network timeout to 10 seconds
ftp_set_option($conn_id, FTP_TIMEOUT_SEC, 10);

ftp_site

(PHP 3>= 3.0.15, PHP 4 )

ftp_site -- Sends a SITE command to the server

Description

bool ftp_site ( resource ftp_stream, string cmd)

ftp_site() sends the command specified by cmd to the FTP server. SITE commands are not standardized, and vary from server to server. They are useful for handling such things as file permissions and group membership.

Retorna TRUE em caso de sucesso ou FALSE em falhas.

ftp_size

(PHP 3>= 3.0.13, PHP 4 )

ftp_size -- Returns the size of the given file

Description

int ftp_size ( resource ftp_stream, string remote_file)

ftp_size() returns the size of a file in bytes. If an error occurs, of if the file does not exist, -1 is returned. Not all servers support this feature.

Returns the file size on success, or -1 on error.

ftp_ssl_connect

(PHP 4 >= 4.3.0)

ftp_ssl_connect -- Opens an Secure SSL-FTP connection

Description

resource ftp_ssl_connect ( string host [, int port [, int timeout]])

Returns a SSL-FTP stream on success or FALSE on error.

ftp_ssl_connect() opens a SSL-FTP connection to the specified host. The port parameter specifies an alternate port to connect to. If it's omitted or set to zero then the default FTP port 21 will be used.

The timeout parameter specifies the timeout for all subsequent network operations. If omitted, the default value is 90 seconds. The timeout can be changed and queried at any time with ftp_set_option() and ftp_get_option().

Why this function may not exist: ftp_ssl_connect() is only available if OpenSSL support is enabled into your version of PHP. If it's undefined and you've compiled FTP support then this is why.

See also ftp_connect()

ftp_systype

(PHP 3>= 3.0.13, PHP 4 )

ftp_systype -- Returns the system type identifier of the remote FTP server

Description

string ftp_systype ( resource ftp_stream)

Returns the remote system type, or FALSE on error.

XXXIV. Function Handling functions

Introdução

These functions all handle various operations involved in working with functions.


Requisitos

Nenhuma biblioteca externa é necessária para compilar esta extensão.


Instalação

Não há nenhuma instalação nescessária para utilizar estas funções, elas fazem parte do núcleo do PHP.


Configuração durante execução

Esta extenção não define nenhum parâmetro de configuração no php.ini.


Constantes Predefinidas

Esta extensão não possui nenhuma constante.

Índice
call_user_func_array --  Call a user function given with an array of parameters
call_user_func --  Call a user function given by the first parameter
create_function -- Create an anonymous (lambda-style) function
func_get_arg -- Return an item from the argument list
func_get_args --  Returns an array comprising a function's argument list
func_num_args --  Returns the number of arguments passed to the function
function_exists --  Return TRUE if the given function has been defined
get_defined_functions --  Returns an array of all defined functions
register_shutdown_function --  Register a function for execution on shutdown
register_tick_function --  Register a function for execution on each tick
unregister_tick_function --  De-register a function for execution on each tick

call_user_func_array

(PHP 4 >= 4.0.4)

call_user_func_array --  Call a user function given with an array of parameters

Description

mixed call_user_func_array ( callback function [, array paramarr])

Call a user defined function given by function, with the parameters in paramarr. For example:

function debug($var, $val)
    echo "***DEBUGGING\nVARIABLE: $var\nVALUE:";
    if (is_array($val) || is_object($val) || is_resource($val))
        print_r($val);
    else
        echo "\n$val\n";
    echo "***\n";
}

$c = mysql_connect();
$host = $_SERVER["SERVER_NAME"];

call_user_func_array ('debug', array("host", $host));
call_user_func_array ('debug', array("c", $c));
call_user_func_array ('debug', array("_POST", $_POST));

See also: call_user_func(), call_user_method(), call_user_method_array().

call_user_func

(PHP 3>= 3.0.3, PHP 4 )

call_user_func --  Call a user function given by the first parameter

Description

mixed call_user_func ( callback function [, mixed parameter [, mixed ...]])

Call a user defined function given by the function parameter. Take the following:

function barber ($type) {
    print "You wanted a $type haircut, no problem";
}
call_user_func ('barber', "mushroom");
call_user_func ('barber', "shave");

Object methods may also be invoked statically using this function by passing array($objectname, $methodname) to the function parameter.

<?php
class myclass {
  function say_hello() {
    print "Hello!\n";
  }
}

$classname = "myclass";

call_user_func(array($classname,'say_hello'));
?>

See also: call_user_func_array(), call_user_method(), call_user_method_array().

create_function

(PHP 4 >= 4.0.1)

create_function -- Create an anonymous (lambda-style) function

Description

string create_function ( string args, string code)

Creates an anonymous function from the parameters passed, and returns a unique name for it. Usually the args will be passed as a single quote delimited string, and this is also recommended for the code. The reason for using single quoted strings, is to protect the variable names from parsing, otherwise, if you use double quotes there will be a need to escape the variable names, e.g. \$avar.

You can use this function, to (for example) create a function from information gathered at run time:

Exemplo 1. Creating an anonymous function with create_function()

$newfunc = create_function('$a,$b','return "ln($a) + ln($b) = ".log($a * $b);');
echo "New anonymous function: $newfunc\n";
echo $newfunc(2,M_E)."\n";
// outputs
// New anonymous function: lambda_1
// ln(2) + ln(2.718281828459) = 1.6931471805599
Or, perhaps to have general handler function that can apply a set of operations to a list of parameters:

Exemplo 2. Making a general processing function with create_function()

function process($var1, $var2, $farr) {
    for ($f=0; $f < count($farr); $f++)
    echo $farr[$f]($var1,$var2)."\n";
}

// create a bunch of math functions
$f1 = 'if ($a >=0) {return "b*a^2 = ".$b*sqrt($a);} else {return false;}';
$f2 = "return \"min(b^2+a, a^2,b) = \".min(\$a*\$a+\$b,\$b*\$b+\$a);";
$f3 = 'if ($a > 0 && $b != 0) {return "ln(a)/b = ".log($a)/$b; } else { return false; }';
$farr = array(
    create_function('$x,$y', 'return "some trig: ".(sin($x) + $x*cos($y));'),
    create_function('$x,$y', 'return "a hypotenuse: ".sqrt($x*$x + $y*$y);'),
    create_function('$a,$b', $f1),
    create_function('$a,$b', $f2),
    create_function('$a,$b', $f3)
    );

echo "\nUsing the first array of anonymous functions\n";
echo "parameters: 2.3445, M_PI\n";
process(2.3445, M_PI, $farr);

// now make a bunch of string processing functions
$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 first 3 chars)";'),
    create_function('$a,$b','; return "CRCs: ".crc32($a)." , ".crc32(b);'),
    create_function('$a,$b','; return "similar(a,b) = ".similar_text($a,$b,&$p)."($p%)";')
    );
echo "\nUsing the second array of anonymous functions\n";
process("Twas brilling and the slithy toves", "Twas the night", $garr);
and when you run the code above, the output will be:

Using the first array of anonymous functions
parameters: 2.3445, M_PI
some trig: -1.6291725057799
a hypotenuse: 3.9199852871011
b*a^2 = 4.8103313314525
min(b^2+a, a^2,b) = 8.6382729035898
ln(a/b) = 0.27122299212594

Using the second array of anonymous functions
** "Twas the night" and "Twas brilling and the slithy toves"
** Look the same to me! (looking at the first 3 chars)
CRCs: -725381282 , 1908338681
similar(a,b) = 11(45.833333333333%)

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

Exemplo 3. Using anonymous functions as callback functions

$av = array("the ","a ","that ","this ");
array_walk($av, create_function('&$v,$k','$v = $v."mango";'));
print_r($av);  // for PHP 3 use var_dump()
// outputs:
// Array
// (
//   [0] => the mango
//   [1] => a mango
//   [2] => that mango
//   [3] => this mango
// )

// an array of strings ordered from shorter to longer
$sv = array("small","larger","a big string","it is a string thing");
print_r($sv);
// outputs:
// Array
// (
//   [0] => small
//   [1] => larger
//   [2] => a big string
//   [3] => it is a string thing
// )

// sort it from longer to shorter
usort($sv, create_function('$a,$b','return strlen($b) - strlen($a);'));
print_r($sv);
// outputs:
// Array
// (
//   [0] => it is a string thing
//   [1] => a big string
//   [2] => larger
//   [3] => small
// )

func_get_arg

(PHP 4 )

func_get_arg -- Return an item from the argument list

Description

mixed func_get_arg ( int arg_num)

Returns the argument which is at the arg_num'th offset into a user-defined function's argument list. Function arguments are counted starting from zero. func_get_arg() will generate a warning if called from outside of a function definition.

If arg_num is greater than the number of arguments actually passed, a warning will be generated and func_get_arg() will return FALSE.

<?php
function foo() {
     $numargs = func_num_args();
     echo "Number of arguments: $numargs<br>\n";
     if ($numargs >= 2) {
     echo "Second argument is: " . func_get_arg (1) . "<br>\n";
     }
} 

foo (1, 2, 3);
?>

func_get_arg() may be used in conjunction with func_num_args() and func_get_args() to allow user-defined functions to accept variable-length argument lists.

Nota: This function was added in PHP 4.

func_get_args

(PHP 4 )

func_get_args --  Returns an array comprising a function's argument list

Description

array func_get_args ( void)

Returns an array in which each element is the corresponding member of the current user-defined function's argument list. func_get_args() will generate a warning if called from outside of a function definition.

<?php
function foo() {
    $numargs = func_num_args();
    echo "Number of arguments: $numargs<br>\n";
    if ($numargs >= 2) {
    echo "Second argument is: " . func_get_arg (1) . "<br>\n";
    }
    $arg_list = func_get_args();
    for ($i = 0; $i < $numargs; $i++) {
    echo "Argument $i is: " . $arg_list[$i] . "<br>\n";
    }
} 

foo (1, 2, 3);
?>

func_get_args() may be used in conjunction with func_num_args() and func_get_arg() to allow user-defined functions to accept variable-length argument lists.

Nota: This function was added in PHP 4.

func_num_args

(PHP 4 )

func_num_args --  Returns the number of arguments passed to the function

Description

int func_num_args ( void)

Returns the number of arguments passed into the current user-defined function. func_num_args() will generate a warning if called from outside of a user-defined function.

<?php
function foo() {
    $numargs = func_num_args();
    echo "Number of arguments: $numargs\n";
} 

foo (1, 2, 3);    // Prints 'Number of arguments: 3'
?>

func_num_args() may be used in conjunction with func_get_arg() and func_get_args() to allow user-defined functions to accept variable-length argument lists.

function_exists

(PHP 3>= 3.0.7, PHP 4 )

function_exists --  Return TRUE if the given function has been defined

Description

bool function_exists ( string function_name)

Checks the list of defined functions, both built-in (internal) and user-defined, for function_name. Retorna TRUE em caso de sucesso ou FALSE em falhas.

if (function_exists('imap_open')) {
    echo "IMAP functions are available.<br>\n";
} else {
    echo "IMAP functions are not available.<br>\n";
}

Note that a function name may exist even if the function itself is unusable due to configuration or compiling options (with the image functions being an example). Also note that function_exists() will return FALSE for constructs, such as include_once() and echo().

See also method_exists() and get_defined_functions().

get_defined_functions

(PHP 4 >= 4.0.4)

get_defined_functions --  Returns an array of all defined functions

Description

array get_defined_functions ( void)

This function returns an multidimensional array 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 using $arr["user"] (see example below).

function myrow($id, $data) {
    return "<tr><th>$id</th><td>$data</td></tr>\n";
}

$arr = get_defined_functions();

print_r($arr);

Will output something along the lines of:

Array
(
    [internal] => Array
        (
            [0] => zend_version
            [1] => func_num_args
            [2] => func_get_arg
            [3] => func_get_args
            [4] => strlen
            [5] => strcmp
            [6] => strncmp
            ...
            [750] => bcscale
            [751] => bccomp
        )

    [user] => Array
        (
            [0] => myrow
        )

)

See also get_defined_vars() and get_defined_constants().

register_shutdown_function

(PHP 3>= 3.0.4, PHP 4 )

register_shutdown_function --  Register a function for execution on shutdown

Description

int register_shutdown_function ( callback function)

Registers the function named by function to be executed when script processing is complete.

Multiple calls to register_shutdown_function() can be made, and each will be called in the same order as they were registered. If you call exit() within one registered shutdown function, processing will stop completely and no other registered shutdown functions will be called.

The registered shutdown functions are called after the request has been completed (including sending any output buffers), so it is not possible to send output to the browser using echo() or print(), or retrieve the contents of any output buffers using ob_get_contents().

register_tick_function

(PHP 4 >= 4.0.3)

register_tick_function --  Register a function for execution on each tick

Description

void register_tick_function ( callback function [, mixed arg])

Registers the function named by func to be executed when a tick is called.

unregister_tick_function

(PHP 4 >= 4.0.3)

unregister_tick_function --  De-register a function for execution on each tick

Description

void unregister_tick_function ( string function_name)

De-registers the function named by function_name so it is no longer executed when a tick is called.

XXXV. Gettext

Introdução

The gettext functions implement an NLS (Native Language Support) API which can be used to internationalize your PHP applications. Please see the gettext documentation for your system for a thorough explanation of these functions or view the docs at http://www.gnu.org/manual/gettext/index.html.


Requisitos

To use these functions you must download and install the GNU gettext package from http://www.gnu.org/software/gettext/gettext.html


Instalação

To include GNU gettext support in your PHP build you must add the option --with-gettext[=DIR] where DIR is the gettext install directory, defaults to /usr/local.

Note to Win32 Users: In order to enable this module on a Windows environment, you must copy gnu_gettext.dll from the DLL folder of the PHP/Win32 binary package to the SYSTEM32 folder of your windows machine. (Ex: C:\WINNT\SYSTEM32 or C:\WINDOWS\SYSTEM32). Starting with PHP 4.2.3 the name changed to libintl-1.dll


Configuração durante execução

Esta extenção não define nenhum parâmetro de configuração no php.ini.


Tipos Resource

Esta extensão não possui nenhum tipo resource.


Constantes Predefinidas

Esta extensão não possui nenhuma constante.

Índice
bind_textdomain_codeset --  Specify the character encoding in which the messages from the DOMAIN message catalog will be returned
bindtextdomain -- Sets the path for a domain
dcgettext -- Overrides the domain for a single lookup
dcngettext -- Plural version of dcgettext
dgettext -- Override the current domain
dngettext -- Plural version of dgettext
gettext -- Lookup a message in the current domain
ngettext -- Plural version of gettext
textdomain -- Sets the default domain

bind_textdomain_codeset

(PHP 4 >= 4.2.0)

bind_textdomain_codeset --  Specify the character encoding in which the messages from the DOMAIN message catalog will be returned

Description

string bind_textdomain_codeset ( string domain, string codeset)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

bindtextdomain

(PHP 3>= 3.0.7, PHP 4 )

bindtextdomain -- Sets the path for a domain

Description

string bindtextdomain ( string domain, string directory)

The bindtextdomain() function sets the path for a domain.

dcgettext

(PHP 3>= 3.0.7, PHP 4 )

dcgettext -- Overrides the domain for a single lookup

Description

string dcgettext ( string domain, string message, int category)

This function allows you to override the current domain for a single message lookup. It also allows you to specify a category.

dcngettext

(PHP 4 >= 4.2.0)

dcngettext -- Plural version of dcgettext

Description

string dcngettext ( string domain, string msgid1, string msgid2, int n, int category)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

dgettext

(PHP 3>= 3.0.7, PHP 4 )

dgettext -- Override the current domain

Description

string dgettext ( string domain, string message)

The dgettext() function allows you to override the current domain for a single message lookup.

dngettext

(PHP 4 >= 4.2.0)

dngettext -- Plural version of dgettext

Description

string dngettext ( string domain, string msgid1, string msgid2, int n)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

gettext

(PHP 3>= 3.0.7, PHP 4 )

gettext -- Lookup a message in the current domain

Description

string gettext ( string message)

This function returns a translated string if one is found in the translation table, or the submitted message if not found. You may use the underscore character '_' as an alias to this function.

Exemplo 1. gettext()-check

<?php
// Set language to German
setlocale(LC_ALL, 'de');

// Specify location of translation tables
bindtextdomain("myPHPApp", "./locale");

// Choose domain
textdomain("myPHPApp");

// Print a test message
print gettext("Welcome to My PHP Application");

// Or use the alias _() for gettext()
print _("Have a nice day");
?>

ngettext

(PHP 4 >= 4.2.0)

ngettext -- Plural version of gettext

Description

string ngettext ( string msgid1, string msgid2, int n)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

textdomain

(PHP 3>= 3.0.7, PHP 4 )

textdomain -- Sets the default domain

Description

string textdomain ( string text_domain)

This function sets the domain to search within when calls are made to gettext(), usually the named after an application. The previous default domain is returned. Call it with NULL as parameter to get the current setting without changing it.

XXXVI. GMP functions

Introdução

These functions allow you to work with arbitrary-length integers using the GNU MP library.

These functions have been added in PHP 4.0.4.

Nota: Most GMP functions accept GMP number arguments, defined as resource below. However, most of these functions will also accept numeric and string arguments, given that it is possible to convert the latter to a number. Also, if there is a faster function that can operate on integer arguments, it would be used instead of the slower function when the supplied arguments are integers. This is done transparently, so the bottom line is that you can use integers in every function that expects GMP number. See also the gmp_init() function.

Atenção

If you want to explicitly specify a large integer, specify it as a string. If you don't do that, PHP will interpret the integer-literal first, possibly resulting in loss of precision, even before GMP comes into play.

Nota: This extension is not available on Windows platforms.


Requisitos

You can download the GMP library from http://www.swox.com/gmp/. This site also has the GMP manual available.

You will need GMP version 2 or better to use these functions. Some functions may require more recent version of the GMP library.


Instalação

In order to have these functions available, you must compile PHP with GMP support by using the --with-gmp option.


Configuração durante execução

Esta extenção não define nenhum parâmetro de configuração no php.ini.


Tipos Resource

Esta extensão não possui nenhum tipo resource.


Constantes Predefinidas

As contantes abaixo são definidas por esta extensão e somente estarão disponíveis quando a extensão foi compilada com o PHP ou carregada dinamicamente durante a execução.

GMP_ROUND_ZERO (integer)

GMP_ROUND_PLUSINF (integer)

GMP_ROUND_MINUSINF (integer)


Exemplos

Exemplo 1. Factorial function using GMP

<?php
function fact ($x) {
    if ($x <= 1) 
        return 1;
    else
        return gmp_mul ($x, fact ($x-1));
}

print gmp_strval (fact (1000)) . "\n";
?>

This will calculate factorial of 1000 (pretty big number) very fast.


Veja Também

More mathmatical functions can be found in the sections BCMath Arbitrary Precision Mathematics Functions and Mathematical Functions.

Índice
gmp_abs -- Absolute value
gmp_add -- Add numbers
gmp_and -- Logical AND
gmp_clrbit -- Clear bit
gmp_cmp -- Compare numbers
gmp_com -- Calculates one's complement of a
gmp_div_q -- Divide numbers
gmp_div_qr -- Divide numbers and get quotient and remainder
gmp_div_r -- Remainder of the division of numbers
gmp_div -- Divide numbers
gmp_divexact -- Exact division of numbers
gmp_fact -- Factorial
gmp_gcd -- Calculate GCD
gmp_gcdext -- Calculate GCD and multipliers
gmp_hamdist -- Hamming distance
gmp_init -- Create GMP number
gmp_intval -- Convert GMP number to integer
gmp_invert -- Inverse by modulo
gmp_jacobi -- Jacobi symbol
gmp_legendre -- Legendre symbol
gmp_mod -- Modulo operation
gmp_mul -- Multiply numbers
gmp_neg -- Negate number
gmp_or -- Logical OR
gmp_perfect_square -- Perfect square check
gmp_popcount -- Population count
gmp_pow -- Raise number into power
gmp_powm -- Raise number into power with modulo
gmp_prob_prime -- Check if number is "probably prime"
gmp_random -- Random number
gmp_scan0 -- Scan for 0
gmp_scan1 -- Scan for 1
gmp_setbit -- Set bit
gmp_sign -- Sign of number
gmp_sqrt -- Square root
gmp_sqrtrm -- Square root with remainder
gmp_strval -- Convert GMP number to string
gmp_sub -- Subtract numbers
gmp_xor -- Logical XOR

gmp_abs

(PHP 4 >= 4.0.4)

gmp_abs -- Absolute value

Description

resource gmp_abs ( resource a)

Returns absolute value of a.

gmp_add

(PHP 4 >= 4.0.4)

gmp_add -- Add numbers

Description

resource gmp_add ( resource a, resource b)

Add two GMP numbers. The result will be a GMP number representing the sum of the arguments.

gmp_and

(PHP 4 >= 4.0.4)

gmp_and -- Logical AND

Description

resource gmp_and ( resource a, resource b)

Calculates logical AND of two GMP numbers.

gmp_clrbit

(PHP 4 >= 4.0.4)

gmp_clrbit -- Clear bit

Description

resource gmp_clrbit ( resource &a, int index)

Clears (sets to 0) bit index in a.

gmp_cmp

(PHP 4 >= 4.0.4)

gmp_cmp -- Compare numbers

Description

int gmp_cmp ( resource a, resource b)

Returns a positive value if a > b, zero if a = b and negative value if a < b.

gmp_com

(PHP 4 >= 4.0.4)

gmp_com -- Calculates one's complement of a

Description

resource gmp_com ( resource a)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

gmp_div_q

(PHP 4 >= 4.0.4)

gmp_div_q -- Divide numbers

Description

resource gmp_div_q ( resource a, resource b [, int round])

Divides a by b and returns the integer result. The result rounding is defined by the round, which can have the following values:

  • GMP_ROUND_ZERO: The result is truncated towards 0.

  • GMP_ROUND_PLUSINF: The result is rounded towards +infinity.

  • GMP_ROUND_MINUSINF: The result is rounded towards -infinity.

This function can also be called as gmp_div().

See also gmp_div_r(), gmp_div_qr()

gmp_div_qr

(PHP 4 >= 4.0.4)

gmp_div_qr -- Divide numbers and get quotient and remainder

Description

array gmp_div_qr ( resource n, resource d [, int round])

The function divides n by d and returns array, with the first element being [n/d] (the integer result of the division) and the second being (n - [n/d] * d) (the remainder of the division).

See the gmp_div_q() function for description of the round argument.

Exemplo 1. Division of GMP numbers

<?php
    $a = gmp_init ("0x41682179fbf5");
    $res = gmp_div_qr ($a, "0xDEFE75");
    printf("Result is: q - %s, r - %s", 
            gmp_strval ($res[0]), gmp_strval ($res[1]));
?>

See also gmp_div_q(), gmp_div_r().

gmp_div_r

(PHP 4 >= 4.0.4)

gmp_div_r -- Remainder of the division of numbers

Description

resource gmp_div_r ( resource n, resource d [, int round])

Calculates remainder of the integer division of n by d. The remainder has the sign of the n argument, if not zero.

See the gmp_div_q() function for description of the round argument.

See also gmp_div_q(), gmp_div_qr()

gmp_div

(PHP 4 >= 4.0.4)

gmp_div -- Divide numbers

Description

resource gmp_div ( resource a, resource b)

This function is an alias to gmp_div_q().

gmp_divexact

(PHP 4 >= 4.0.4)

gmp_divexact -- Exact division of numbers

Description

resource gmp_divexact ( resource n, resource d)

Divides n by d, using fast "exact division" algorithm. This function produces correct results only when it is known in advance that d divides n.

gmp_fact

(PHP 4 >= 4.0.4)

gmp_fact -- Factorial

Description

resource gmp_fact ( int a)

Calculates factorial (a!) of a.

gmp_gcd

(PHP 4 >= 4.0.4)

gmp_gcd -- Calculate GCD

Description

resource gmp_gcd ( resource a, resource b)

Calculate greatest common divisor of a and b. The result is always positive even if either of, or both, input operands are negative.

gmp_gcdext

(PHP 4 >= 4.0.4)

gmp_gcdext -- Calculate GCD and multipliers

Description

array gmp_gcdext ( resource a, resource b)

Calculates g, s, and t, such that a*s + b*t = g = gcd(a,b), where gcd is the greatest common divisor. Returns an array with respective elements g, s and t.

gmp_hamdist

(PHP 4 >= 4.0.4)

gmp_hamdist -- Hamming distance

Description

int gmp_hamdist ( resource a, resource b)

Returns the hamming distance between a and b. Both operands should be non-negative.

gmp_init

(PHP 4 >= 4.0.4)

gmp_init -- Create GMP number

Description

resource gmp_init ( mixed number)

Creates a GMP number from an integer or string. String representation can be decimal or hexadecimal. In the latter case, the string should start with 0x.

Exemplo 1. Creating GMP number

<?php
    $a = gmp_init (123456);
    $b = gmp_init ("0xFFFFDEBACDFEDF7200");
?>

Nota: It is not necessary to call this function if you want to use integer or string in place of GMP number in GMP functions, like gmp_add(). Function arguments are automatically converted to GMP numbers, if such conversion is possible and needed, using the same rules as gmp_init().

gmp_intval

(PHP 4 >= 4.0.4)

gmp_intval -- Convert GMP number to integer

Description

int gmp_intval ( resource gmpnumber)

This function allows to convert GMP number to integer.

Atenção

This function returns a useful result only if the number actually fits the PHP integer (i.e., signed long type). If you want just to print the GMP number, use gmp_strval().

gmp_invert

(PHP 4 >= 4.0.4)

gmp_invert -- Inverse by modulo

Description

resource gmp_invert ( resource a, resource b)

Computes the inverse of a modulo b. Returns FALSE if an inverse does not exist.

gmp_jacobi

(PHP 4 >= 4.0.4)

gmp_jacobi -- Jacobi symbol

Description

int gmp_jacobi ( resource a, resource p)

Computes Jacobi symbol of a and p. p should be odd and must be positive.

gmp_legendre

(PHP 4 >= 4.0.4)

gmp_legendre -- Legendre symbol

Description

int gmp_legendre ( resource a, resource p)

Compute the Legendre symbol of a and p. p should be odd and must be positive.

gmp_mod

(PHP 4 >= 4.0.4)

gmp_mod -- Modulo operation

Description

resource gmp_mod ( resource n, resource d)

Calculates n modulo d. The result is always non-negative, the sign of d is ignored.

gmp_mul

(PHP 4 >= 4.0.4)

gmp_mul -- Multiply numbers

Description

resource gmp_mul ( resource a, resource b)

Multiplies a by b and returns the result.

gmp_neg

(PHP 4 >= 4.0.4)

gmp_neg -- Negate number

Description

resource gmp_neg ( resource a)

Returns -a.

gmp_or

(PHP 4 >= 4.0.4)

gmp_or -- Logical OR

Description

resource gmp_or ( resource a, resource b)

Calculates logical inclusive OR of two GMP numbers.

gmp_perfect_square

(PHP 4 >= 4.0.4)

gmp_perfect_square -- Perfect square check

Description

bool gmp_perfect_square ( resource a)

Returns TRUE if a is a perfect square, FALSE otherwise.

See also: gmp_sqrt(), gmp_sqrtrm().

gmp_popcount

(PHP 4 >= 4.0.4)

gmp_popcount -- Population count

Description

int gmp_popcount ( resource a)

Return the population count of a.

gmp_pow

(PHP 4 >= 4.0.4)

gmp_pow -- Raise number into power

Description

resource gmp_pow ( resource base, int exp)

Raise base into power exp. The case of 0^0 yields 1. exp cannot be negative.

gmp_powm

(PHP 4 >= 4.0.4)

gmp_powm -- Raise number into power with modulo

Description

resource gmp_powm ( resource base, resource exp, resource mod)

Calculate (base raised into power exp) modulo mod. If exp is negative, result is undefined.

gmp_prob_prime

(PHP 4 >= 4.0.4)

gmp_prob_prime -- Check if number is "probably prime"

Description

int gmp_prob_prime ( resource a [, int reps])

If this function returns 0, a is definitely not prime. If it 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 probability for a non-prime to pass as a "probable" prime.

The function uses Miller-Rabin's probabilistic test.

gmp_random

(PHP 4 >= 4.0.4)

gmp_random -- Random number

Description

resource gmp_random ( int limiter)

Generate a random number. The number will be between limiter and zero in value. If limiter is negative, negative numbers are generated.

gmp_scan0

(PHP 4 >= 4.0.4)

gmp_scan0 -- Scan for 0

Description

int gmp_scan0 ( resource a, int start)

Scans a, starting with bit start, towards more significant bits, until the first clear bit is found. Returns the index of the found bit.

gmp_scan1

(PHP 4 >= 4.0.4)

gmp_scan1 -- Scan for 1

Description

int gmp_scan1 ( resource a, int start)

Scans a, starting with bit start, towards more significant bits, until the first set bit is found. Returns the index of the found bit.

gmp_setbit

(PHP 4 >= 4.0.4)

gmp_setbit -- Set bit

Description

resource gmp_setbit ( resource &a, int index [, bool set_clear])

Sets bit index in a. set_clear defines if the bit is set to 0 or 1. By default the bit is set to 1.

gmp_sign

(PHP 4 >= 4.0.4)

gmp_sign -- Sign of number

Description

int gmp_sign ( resource a)

Return sign of a - 1 if a is positive and -1 if it's negative.

gmp_sqrt

(PHP 4 >= 4.0.4)

gmp_sqrt -- Square root

Description

resource gmp_sqrt ( resource a)

Calculates square root of a.

gmp_sqrtrm

(no version information, might be only in CVS)

gmp_sqrtrm -- Square root with remainder

Description

array gmp_sqrtrm ( resource a)

Returns array where first element is the integer square root of a (see also gmp_sqrt()), and the second is the remainder (i.e., the difference between a and the first element squared).

gmp_strval

(PHP 4 >= 4.0.4)

gmp_strval -- Convert GMP number to string

Description

string gmp_strval ( resource gmpnumber [, int base])

Convert GMP number to string representation in base base. The default base is 10. Allowed values for the base are from 2 to 36.

Exemplo 1. Converting a GMP number to a string

<?php
    $a = gmp_init("0x41682179fbf5");
    printf ("Decimal: %s, 36-based: %s", gmp_strval($a), gmp_strval($a,36));
?>

gmp_sub

(PHP 4 >= 4.0.4)

gmp_sub -- Subtract numbers

Description

resource gmp_sub ( resource a, resource b)

Subtracts b from a and returns the result.

gmp_xor

(PHP 4 >= 4.0.4)

gmp_xor -- Logical XOR

Description

resource gmp_xor ( resource a, resource b)

Calculates logical exclusive OR (XOR) of two GMP numbers.

XXXVII. HTTP functions

Introdução

These functions let you manipulate the output sent back to the remote browser right down to the HTTP protocol level.


Requisitos

Nenhuma biblioteca externa é necessária para compilar esta extensão.


Instalação

Não há nenhuma instalação nescessária para utilizar estas funções, elas fazem parte do núcleo do PHP.


Configuração durante execução

Esta extenção não define nenhum parâmetro de configuração no php.ini.


Tipos Resource

Esta extensão não possui nenhum tipo resource.


Constantes Predefinidas

Esta extensão não possui nenhuma constante.

Índice
header -- Send a raw HTTP header
headers_sent -- Checks if or where headers have been sent
setcookie -- Send a cookie

header

(PHP 3, PHP 4 )

header -- Send a raw HTTP header

Description

int header ( string string [, bool replace [, int http_reponse_code]])

header() is used to send raw HTTP headers. See the HTTP/1.1 specification for more information on HTTP headers.

The optional replace parameter indicates whether the header should replace a previous similar header, or add a second header of the same type. By default it will replace, but if you pass in FALSE as the second argument you can force multiple headers of the same type. For example:

<?php
header('WWW-Authenticate: Negotiate');
header('WWW-Authenticate: NTLM', FALSE);
?>

The second optional http_response_code force the HTTP response code to the specified value. (This parameter is available in PHP 4.3.0 and higher.)

There are two special-case header calls. The first is a header that starts with the string "HTTP/" (case is not significant), which will be used to figure out the HTTP status code to send. For example, if you have configured Apache to use a PHP script to handle requests for missing files (using the ErrorDocument directive), you may want to make sure that your script generates the proper status code.

<?php
  header("HTTP/1.0 404 Not Found");
?>

Nota: The HTTP status header line will always be the first sent to the client, regardless of the actual header() call beeing the first or not. The status may be overridden by calling header() with a new status line at any time unless the HTTP headers have already been sent.

Nota: In PHP 3, this only works when PHP is compiled as an Apache module. You can achieve the same effect using the Status header.

<?php
header("Status: 404 Not Found");
?>

The second special case is the "Location:" header. Not only does it send this header back to the browser, but it also returns a REDIRECT (302) status code to the browser unless some 3xx status code has already been set.

<?php
header("Location: http://www.example.com/"); /* Redirect browser */
exit;                 /* Make sure that code below does 
                         not get executed when we redirect. */
?>

Nota: HTTP/1.1 requires an absolute URI as argument to Location: including the scheme, hostname and absolute path, but some clients accept relative URIs. You can usually use $_SERVER['HTTP_HOST'], $_SERVER['PHP_SELF'] and dirname() to make an absolute URI from a relative one yourself:

<?php
header("Location: http://".$_SERVER['HTTP_HOST']
                      .dirname($_SERVER['PHP_SELF'])
                      ."/".$relative_url);
?>

PHP scripts often generate dynamic content that must not be cached by the client browser or any proxy caches between the server and the client browser. Many proxies and clients can be forced to disable caching with

<?php
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");    // Date in the past
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); 
                                                     // always modified
header("Cache-Control: no-store, no-cache, must-revalidate");  // HTTP/1.1
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");                          // HTTP/1.0
?>

Nota: You may find that your pages aren't cached even if you don't output all of the headers above. There are a number of options that users may be able to set for their browser that change its default caching behavior. By sending the headers above, you should override any settings that may otherwise cause the output of your script to be cached.

Additionally, session_cache_limiter() and the session.cache_limiter configuration setting can be used to automatically generate the correct caching-related headers when sessions are being used.

Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include(), or require(), functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.

<html>
<?php
// This will give an error. Note the output
// above, which is before the header() call
header('Location: http://www.example.com/');
?>

Nota: In PHP 4, you can use output buffering to get around this problem, with the overhead of all of your output to the browser being buffered in the server until you send it. You can do this by calling ob_start() and ob_end_flush() in your script, or setting the output_buffering configuration directive on in your php.ini or server configuration files.

If you want the user to be prompted to save the data you are sending, such as a generated PDF file, you can use the Content-Disposition header to supply a recommended filename and force the browser to display the save dialog.

<?php
// We'll be outputting a PDF
header("Content-type: application/pdf");

// It will be called downloaded.pdf
header("Content-Disposition: attachment; filename=downloaded.pdf");

// The PDF source is in original.pdf
readfile('original.pdf');
?>

Nota: There is a bug in Microsoft Internet Explorer 4.01 that prevents this from working. There is no workaround. There is also a bug in Microsoft Internet Explorer 5.5 that interferes with this, which can be resolved by upgrading to Service Pack 2 or later.

Nota: If safe mode is enabled the uid of the script is added to the realm part of the WWW-Authenticate header if you set this header (used for HTTP Authentication).

See also headers_sent(), setcookie(), and the section on HTTP authentication.

headers_sent

(PHP 3>= 3.0.8, PHP 4 )

headers_sent -- Checks if or where headers have been sent

Description

bool headers_sent ( [string &file [, int &line]])

headers_sent() will return FALSE if no HTTP headers have already been sent or TRUE otherwise. If the optional file and line parameters are set, headers_sent() will put the php source file name and line number where output started in the file and line variables.

You can't add any more header lines using the header() function once the header block has already been sent. Using this function you can at least prevent getting HTTP header related error messages. Another option is to use Output Buffering.

New parameters: The optional file and line parameters where added in PHP 4.3.0.

Exemplo 1. Examples using headers_sent()

<?php

// If no headers are sent, send one
if (!headers_sent()) {
    header ('Location: http://www.example.com/');
    exit;
}
  
// An example using the optional file and line parameters, as of PHP 4.3.0
// Note that $filename and $linenum are passed in for later use.
// Do not assign them values beforehand.
if (!headers_sent($filename, $linenum)) {
    header ('Location: http://www.example.com/');
    exit;

// You would most likely trigger an error here.
} else {

    print "Headers already sent in $filename on line $linenum\n" .
          "Cannot redirect, for now please click this <a " .
          "href=\"http://www.example.com\">link</a> instead\n";
    exit;
}

?>

See also ob_start(), trigger_error(), and header() for a more detailed discussion of the matters involved.

setcookie

(PHP 3, PHP 4 )

setcookie -- Send a cookie

Description

bool setcookie ( string name [, string value [, int expire [, string path [, string domain [, int secure]]]]])

setcookie() defines a cookie to be sent along with the rest of the HTTP headers. Like other headers, cookies must be sent before any output from your script (this is a protocol restriction). This requires that you place calls to this function prior to any output, including <html> and <head> tags as well as any whitespace. If output exists prior to calling this function, setcookie() will fail and return FALSE. If setcookie() successfully runs, it will return TRUE. This does not indicate whether the user accepted the cookie.

All the arguments except the name argument are optional. If only the name argument is present, the cookie by that name will be deleted from the remote client. You may also replace an argument with an empty string ("") in order to skip that argument. Because the expire and secure arguments are integers, they cannot be skipped with an empty string, use a zero (0) instead. The following table explains each parameter of the setcookie() function, be sure to read the Netscape cookie specification for specifics.

Tabela 1. setcookie() parameters explained

Parameter Description Examples
name The name of the cookie. 'cookiename' is called as $_COOKIE['cookiename']
value The value of the cookie. This value is stored on the clients computer; do not store sensitive information. Assuming the name is 'cookiename', this value is retrieved through $_COOKIE['cookiename']
expire The time the cookie expires. This is a unix timestamp so is in number of seconds since the epoch. In otherwords, you'll most likely set this with the time() function plus the number of seconds before you want it to expire. Or you might use mktime(). time()+60*60*24*30 will set the cookie to expire in 30 days. If not set, the cookie will expire at the end of the session (when the browser closes).
path The path on the server in which the cookie will be available on. If set to '/', the cookie will be available within the entire domain. If set to '/foo/', the cookie will only be available within the /foo/ directory and all sub-directories such as /foo/bar/ of domain. The default value is the current directory that the cookie is being set in.
domain The domain that the cookie is available. To make the cookie available on all subdomains of example.com then you'd set it to '.example.com'. The . is not required but makes it compatible with more browsers. Setting it to www.example.com will make the cookie only available in the www subdomain. Refer to tail matching in the spec for details.
secure Indicates that the cookie should only be transmitted over a secure HTTPS connection. When set to 1, the cookie will only be set if a secure connection exists. The default is 0. 0 or 1

Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays. Note, autoglobals such as $_COOKIE became available in PHP 4.1.0. $HTTP_COOKIE_VARS has existed since PHP 3. Cookie values also exist in $_REQUEST.

Nota: If the PHP directive register_globals is set to on then cookie values will also be made into variables. In our examples below, $TextCookie will exist. It's recommended to use $_COOKIE.

Common Pitfalls:

  • Cookies will not become visible until the next loading of a page that the cookie should be visible for. To test if a cookie was successfully set, check for the cookie on a next loading page before the cookie expires. Expire time is set via the expire parameter. A nice way to debug the existence of cookies is by simply calling print_r($_COOKIE);.

  • Cookies must be deleted with the same parameters as they were set with.

  • Cookies names can be set as array names and will be available to your PHP scripts as arrays but seperate cookies are stored on the users system. Consider explode() or serialize() to set one cookie with multiple names and values.

In PHP 3, multiple calls to setcookie() in the same script will be performed in reverse order. If you are trying to delete one cookie before inserting another you should put the insert before the delete. In PHP 4, multiple calls to setcookie() are performed in the order called.

Some examples follow how to send cookies:

Exemplo 1. setcookie() send examples

<?php
$value = 'something from somewhere';

setcookie ("TestCookie", $value);
setcookie ("TestCookie", $value,time()+3600);  /* expire in 1 hour */
setcookie ("TestCookie", $value,time()+3600, "/~rasmus/", ".example.com", 1);
?>

Note that the value portion of the cookie will automatically be urlencoded when you send the cookie, and when it is received, it is automatically decoded and assigned to a variable by the same name as the cookie name. To see the contents of our test cookie in a script, simply use one of the following examples:

<?php
// Print an individual cookie
echo $_COOKIE["TestCookie"];
echo $HTTP_COOKIE_VARS["TestCookie"];

// Another way to debug/test is to view all cookies
print_r($_COOKIE);
?>

When deleting a cookie you should assure that the expiration date is in the past, to trigger the removal mechanism in your browser. Examples follow how to delete cookies sent in previous example:

Exemplo 2. setcookie() delete examples

<?php
// set the expiration date to one hour ago
setcookie ("TestCookie", "", time() - 3600);
setcookie ("TestCookie", "", time() - 3600, "/~rasmus/", ".example.com", 1);
?>

You may also set array cookies by using array notation in the cookie name. This has the effect of setting as many cookies as you have array elements, but when the cookie is received by your script, the values are all placed in an array with the cookie's name:

<?php
// set the cookies
setcookie ("cookie[three]", "cookiethree");
setcookie ("cookie[two]", "cookietwo");
setcookie ("cookie[one]", "cookieone");

// after the page reloads, print them out
if (isset($_COOKIE['cookie'])) {
    foreach ($_COOKIE['cookie'] as $name => $value) {
        echo "$name : $value <br />\n";
    }
}

/* which prints

three : cookiethree
two : cookietwo
one : cookieone

*/
?>

For more information on cookies, see Netscape's cookie specification at http://www.netscape.com/newsref/std/cookie_spec.html.

Microsoft Internet Explorer 4 with Service Pack 1 applied does not correctly deal with cookies that have their path parameter set.

Netscape Communicator 4.05 and Microsoft Internet Explorer 3.x appear to handle cookies incorrectly when the path and time are not set.

XXXVIII. Hyperwave functions

Introdução

Hyperwave has been developed at IICM in Graz. It started with the name Hyper-G and changed to Hyperwave when it was commercialised (in 1996).

Hyperwave is not free software. The current version, 5.5 is available at http://www.hyperwave.com/. A time limited version can be ordered for free (30 days).

See also the Hyperwave API module.

Hyperwave is an information system similar to a database (HIS, Hyperwave Information Server). Its focus 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 its object record. The object record contains meta data for the document. The meta data is a list of attributes which can be extended by the user. Certain attributes are always set by the Hyperwave server, other may be modified by the user. An attribute is a name/value pair of the form name=value. The complete object record contains as many of those pairs as the user likes. The name of an attribute does not have to be unique, e.g. a title may appear several times within an object record. This makes sense if you want to specify a title in several languages. In such a case there is a convention, that each title value is preceded by the two letter language abbreviation followed by a colon, e.g. 'en:Title in English' or 'ge:Titel in deutsch'. Other attributes like a description or keywords are potential candidates. You may also replace the language abbreviation by any other string as long as it separated by colon from the rest of the attribute value.

Each object record has native a string representation with each name/value pair separated by a newline. The Hyperwave extension also knows a second representation which is an associated array with the attribute name being the key. Multilingual attribute values itself form another associated array with the key being the language abbreviation. Actually any multiple attribute forms an associated array with the string left to the colon in the attribute value being the key. (This is not fully implemented. Only the attributes Title, Description and Keyword are treated properly yet.)

Besides the documents, all hyper links contained in a document are stored as object records as well. Hyper links which are in a document will be removed from it and stored as individual objects, when the document is inserted into the database. The object record of the link contains information about where it starts and where it ends. In order to gain the original document you will have to retrieve the plain document without the links and the list of links and reinsert them. The functions hw_pipedocument() and hw_gettext() do this for you. The advantage of separating links from the document is obvious. Once a document to which a link is pointing to changes its name, the link can easily be modified accordingly. The document containing the link is not affected at all. You may even add a link to a document without modifying the document itself.

Saying that hw_pipedocument() and hw_gettext() do the link insertion automatically is not as simple as it sounds. Inserting links implies a certain hierarchy of the documents. On a web server this is given by the file system, but Hyperwave has its own hierarchy and names do not reflect the position of an object in that hierarchy. Therefore creation of links first of all requires a mapping from the Hyperwave hierarchy and namespace into a web hierarchy respective web namespace. The fundamental difference between Hyperwave and the web is the clear distinction between names and hierarchy in Hyperwave. The name does not contain any information about the objects position in the hierarchy. In the web the name also contains the information on where the object is located in the hierarchy. This leads to two possibles ways of mapping. Either the Hyperwave hierarchy and name of the Hyperwave object is reflected in the URL or the name only. To make things simple the second approach is used. Hyperwave object with name my_object is mapped to http://host/my_object disregarding where it resides in the Hyperwave hierarchy. An object with name parent/my_object could be the child of my_object in the Hyperwave hierarchy, though in a web namespace it appears to be just the opposite and the user might get confused. This can only be prevented by selecting reasonable object names.

Having made this decision a second problem arises. How do you involve PHP? The URL http://host/my_object will not call any PHP script unless you tell your web server to rewrite it to e.g. http://host/php_script/my_object and the script php_script evaluates the $PATH_INFO variable and retrieves the object with name my_object from the Hyperwave server. Their is just one little drawback which can be fixed easily. Rewriting any URL would not allow any access to other document on the web server. A PHP script for searching in the Hyperwave server would be impossible. Therefore you will need at least a second rewriting rule to exclude certain URLs like all e.g. starting with http://host/Hyperwave This is basically sharing of a namespace by the web and Hyperwave server.

Based on the above mechanism links are insert into documents.

It gets more complicated if PHP is not run as a server module or CGI script but as a standalone application e.g. to dump the content of the Hyperwave server on a CD-ROM. In such a case it makes sense to retain the Hyperwave hierarchy and map in onto the file system. This conflicts with the object names if they reflect its own hierarchy (e.g. by choosing names including '/'). Therefore '/' has to be replaced by another character, e.g. '_'.

The network protocol to communicate with the Hyperwave server is called HG-CSP (Hyper-G Client/Server Protocol). It is based on messages to initiate certain actions, e.g. get object record. In early versions of the Hyperwave Server two native clients (Harmony, Amadeus) were provided for communication with the server. Those two disappeared when Hyperwave was commercialised. As a replacement a so called wavemaster was provided. The wavemaster is like a protocol converter from HTTP to HG-CSP. The idea is to do all the administration of the database and visualisation of documents by a web interface. The wavemaster implements a set of placeholders for certain actions to customise the interface. This set of placeholders is called the PLACE Language. PLACE lacks a lot of features of a real programming language and any extension to it only enlarges the list of placeholders. This has led to the use of JavaScript which IMO does not make life easier.

Adding Hyperwave support to PHP should fill in the gap of a missing programming language for interface customisation. It implements all the messages as defined by the HG-CSP but also provides more powerful commands to e.g. retrieve complete documents.

Hyperwave has its own terminology to name certain pieces of information. This has widely been taken over and extended. Almost all functions operate on one of the following data types.

  • object ID: An unique integer value for each object in the Hyperwave server. It is also one of the attributes of the object record (ObjectID). Object ids are often used as an input parameter to specify an object.

  • object record: A string with attribute-value pairs of the form attribute=value. The pairs are separated by a carriage return from each other. An object record can easily be converted into an object array with hw_object2array(). Several functions return object records. The names of those functions end with obj.

  • object array: An associative array with all attributes of an object. The keys are the attribute names. If an attribute occurs more than once in an object record it will result in another indexed or associative array. Attributes which are language depended (like the title, keyword, description) will form an associative array with the keys set to the language abbreviations. All other multiple attributes will form an indexed array. PHP functions never return object arrays.

  • hw_document: This is a complete new data type which holds the actual document, e.g. HTML, PDF etc. It is somewhat optimized for HTML documents but may be used for any format.

Several functions which return an array of object records do also return an associative array with statistical information about them. The array is the last element of the object record array. The statistical array contains the following entries:

Hidden

Number of object records with attribute PresentationHints set to Hidden.

CollectionHead

Number of object records with attribute PresentationHints set to CollectionHead.

FullCollectionHead

Number of object records with attribute PresentationHints set to FullCollectionHead.

CollectionHeadNr

Index in array of object records with attribute PresentationHints set to CollectionHead.

FullCollectionHeadNr

Index in array of object records with attribute PresentationHints set to FullCollectionHead.

Total

Total: Number of object records.


Requisitos

This extension needs a Hyperwave server downloadable from http://www.hyperwave.com/.


Instalação

To enable Hyperwave support compile PHP --with-hyperwave.


Integration with Apache

The Hyperwave extension is best used when PHP is compiled as an Apache module. In such a case the underlying Hyperwave server can be hidden from users almost completely if Apache uses its rewriting engine. The following instructions will explain this.

Since PHP with Hyperwave support built into Apache is intended to replace the native Hyperwave solution based on Wavemaster, we will assume that the Apache server will only serve as a Hyperwave web interface for these examples. This is not necessary but it simplifies the configuration. The concept is quite simple. First of all you need a PHP script which evaluates the $_ENV['PATH_INFO'] variable and treats its value as the name of a Hyperwave object. Let's call this script 'Hyperwave'. The URL http://your.hostname/Hyperwave/name_of_object would than return the Hyperwave object with the name 'name_of_object'. Depending on the type of the object the script has to react accordingly. If it is a collection, it will probably return a list of children. If it is a document it will return the mime type and the content. A slight improvement can be achieved if the Apache rewriting engine is used. From the users point of view it would be more straight forward if the URL http://your.hostname/name_of_object would return the object. The rewriting rule is quite easy:

RewriteRule ^/(.*) /usr/local/apache/htdocs/HyperWave/$1 [L]

Now every URL relates to an object in the Hyperwave server. This causes a simple to solve problem. There is no way to execute a different script, e.g. for searching, than the 'Hyperwave' script. This can be fixed with another rewriting rule like the following:

RewriteRule ^/hw/(.*) /usr/local/apache/htdocs/hw/$1 [L]

This will reserve the directory /usr/local/apache/htdocs/hw for additional scripts and other files. Just make sure this rule is evaluated before the one above. There is just a little drawback: all Hyperwave objects whose name starts with 'hw/' will be shadowed. So, make sure you don't use such names. If you need more directories, e.g. for images just add more rules or place them all in one directory. Before you put those instructions, don't forget to turn on the rewriting engine with

RewriteEngine on

You will need scripts:

  • to return the object itself

  • to allow searching

  • to identify yourself

  • to set your profile

  • one for each additional function like to show the object attributes, to show information about users, to show the status of the server, etc.

As an alternative to the Rewrite Engine, you can also consider using the Apache ErrorDocument directive, but be aware, that ErrorDocument redirected pages cannot receive POST data.


Configuração durante execução

O comportamento dessas funções podem ser modificado pelas configurações do php.ini.

Tabela 1. Hyperwave configuration options

Name Default Changeable
hyerwave.allow_persistent "0" PHP_INI_SYSTEM
hyperwave.default_port "418" PHP_INI_ALL
For further details and definition of the PHP_INI_* constants see ini_set().


Tipos Resource

Esta extensão não possui nenhum tipo resource.


Constantes Predefinidas

As contantes abaixo são definidas por esta extensão e somente estarão disponíveis quando a extensão foi compilada com o PHP ou carregada dinamicamente durante a execução.

HW_ATTR_LANG (integer)

HW_ATTR_NR (integer)

HW_ATTR_NONE (integer)


Todo

There are still some things to do:

  • The hw_InsertDocument has to be split into hw_insertobject() and hw_putdocument().

  • The names of several functions are not fixed, yet.

  • Most functions require the current connection as its first parameter. This leads to a lot of typing, which is quite often not necessary if there is just one open connection. A default connection will improve this.

  • Conversion form object record into object array needs to handle any multiple attribute.

Índice
hw_Array2Objrec -- convert attributes from object array to object record
hw_changeobject --  Changes attributes of an object (obsolete)
hw_Children -- object ids of children
hw_ChildrenObj -- object records of children
hw_Close -- closes the Hyperwave connection
hw_Connect -- opens a connection
hw_connection_info --  Prints information about the connection to Hyperwave server
hw_Cp -- copies objects
hw_Deleteobject -- deletes object
hw_DocByAnchor -- object id object belonging to anchor
hw_DocByAnchorObj -- object record object belonging to anchor
hw_Document_Attributes -- object record of hw_document
hw_Document_BodyTag -- body tag of hw_document
hw_Document_Content -- returns content of hw_document
hw_Document_SetContent -- sets/replaces content of hw_document
hw_Document_Size -- size of hw_document
hw_dummy --  Hyperwave dummy function
hw_EditText -- retrieve text document
hw_Error -- error number
hw_ErrorMsg -- returns error message
hw_Free_Document -- frees hw_document
hw_GetAnchors -- object ids of anchors of document
hw_GetAnchorsObj -- object records of anchors of document
hw_GetAndLock -- return bject record and lock object
hw_GetChildColl -- object ids of child collections
hw_GetChildCollObj -- object records of child collections
hw_GetChildDocColl -- object ids of child documents of collection
hw_GetChildDocCollObj -- object records of child documents of collection
hw_GetObject -- object record
hw_GetObjectByQuery -- search object
hw_GetObjectByQueryColl -- search object in collection
hw_GetObjectByQueryCollObj -- search object in collection
hw_GetObjectByQueryObj -- search object
hw_GetParents -- object ids of parents
hw_GetParentsObj -- object records of parents
hw_getrellink --  Get link from source to dest relative to rootid
hw_GetRemote -- Gets a remote document
hw_GetRemoteChildren -- Gets children of remote document
hw_GetSrcByDestObj -- Returns anchors pointing at object
hw_GetText -- retrieve text document
hw_getusername -- name of currently logged in user
hw_Identify -- identifies as user
hw_InCollections -- check if object ids in collections
hw_Info -- info about connection
hw_InsColl -- insert collection
hw_InsDoc -- insert document
hw_insertanchors --  Inserts only anchors into text
hw_InsertDocument -- upload any document
hw_InsertObject -- inserts an object record
hw_mapid -- Maps global id on virtual local id
hw_Modifyobject -- modifies object record
hw_Mv -- moves objects
hw_New_Document -- create new document
hw_Objrec2Array -- convert attributes from object record to object array
hw_Output_Document -- prints hw_document
hw_pConnect -- make a persistent database connection
hw_PipeDocument -- retrieve any document
hw_Root -- root object id
hw_setlinkroot --  Set the id to which links are calculated
hw_stat --  Returns status string
hw_Unlock -- unlock object
hw_Who -- List of currently logged in users

hw_Array2Objrec

(PHP 3>= 3.0.4, PHP 4 )

hw_Array2Objrec -- convert attributes from object array to object record

Description

strin hw_array2objrec ( array object_array)

Converts an object_array into an object record. Multiple attributes like 'Title' in different languages are treated properly.

See also hw_objrec2array().

hw_changeobject

(PHP 3>= 3.0.3, PHP 4 )

hw_changeobject --  Changes attributes of an object (obsolete)

Description

void hw_changeobject ( int link, int objid, array attributes)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

hw_Children

(PHP 3>= 3.0.3, PHP 4 )

hw_Children -- object ids of children

Description

array hw_children ( int connection, int objectID)

Returns an array of object ids. Each id belongs to a child of the collection with ID objectID. The array contains all children both documents and collections.

hw_ChildrenObj

(PHP 3>= 3.0.3, PHP 4 )

hw_ChildrenObj -- object records of children

Description

array hw_childrenobj ( int connection, int objectID)

Returns an array of object records. Each object record belongs to a child of the collection with ID objectID. The array contains all children both documents and collections.

hw_Close

(PHP 3>= 3.0.3, PHP 4 )

hw_Close -- closes the Hyperwave connection

Description

int hw_close ( int connection)

Returns FALSE if connection is not a valid connection index, otherwise TRUE. Closes down the connection to a Hyperwave server with the given connection index.

hw_Connect

(PHP 3>= 3.0.3, PHP 4 )

hw_Connect -- opens a connection

Description

int hw_connect ( string host, int port, string username, string password)

Opens a connection to a Hyperwave server and returns a connection index on success, or FALSE if the connection could not be made. Each of the arguments should be a quoted string, except for the port number. The username and password arguments are optional and can be left out. In such a case no identification with the server will be done. It is similar to identify as user anonymous. This function returns a connection index that is needed by other Hyperwave functions. You can have multiple connections open at once. Keep in mind, that the password is not encrypted.

See also hw_pconnect().

hw_connection_info

(PHP 3>= 3.0.3, PHP 4 )

hw_connection_info --  Prints information about the connection to Hyperwave server

Description

void hw_connection_info ( int link)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

hw_Cp

(PHP 3>= 3.0.3, PHP 4 )

hw_Cp -- copies objects

Description

int hw_cp ( int connection, array object_id_array, int destination id)

Copies the objects with object ids as specified in the second parameter to the collection with the id destination id.

The value return is the number of copied objects.

See also hw_mv().

hw_Deleteobject

(PHP 3>= 3.0.3, PHP 4 )

hw_Deleteobject -- deletes object

Description

int hw_deleteobject ( int connection, int object_to_delete)

Deletes the object with the given object id in the second parameter. It will delete all instances of the object.

Returns TRUE if no error occurs otherwise FALSE.

See also hw_mv().

hw_DocByAnchor

(PHP 3>= 3.0.3, PHP 4 )

hw_DocByAnchor -- object id object belonging to anchor

Description

int hw_docbyanchor ( int connection, int anchorID)

Returns an th object id of the document to which anchorID belongs.

hw_DocByAnchorObj

(PHP 3>= 3.0.3, PHP 4 )

hw_DocByAnchorObj -- object record object belonging to anchor

Description

string hw_docbyanchorobj ( int connection, int anchorID)

Returns an th object record of the document to which anchorID belongs.

hw_Document_Attributes

(PHP 3>= 3.0.3, PHP 4 )

hw_Document_Attributes -- object record of hw_document

Description

string hw_document_attributes ( int hw_document)

Returns the object record of the document.

For backward compatibility, hw_documentattributes() is also accepted. This is deprecated, however.

See also hw_document_bodytag(), and hw_document_size().

hw_Document_BodyTag

(PHP 3>= 3.0.3, PHP 4 )

hw_Document_BodyTag -- body tag of hw_document

Description

string hw_document_bodytag ( int hw_document)

Returns the BODY tag of the document. If the document is an HTML document the BODY tag should be printed before the document.

See also hw_document_attributes(), and hw_document_size().

For backward compatibility, hw_documentbodytag() is also accepted. This is deprecated, however.

hw_Document_Content

(PHP 3>= 3.0.3, PHP 4 )

hw_Document_Content -- returns content of hw_document

Description

string hw_document_content ( int hw_document)

Returns the content of the document. If the document is an HTML document the content is everything after the BODY tag. Information from the HEAD and BODY tag is in the stored in the object record.

See also hw_document_attributes(), hw_document_size(), and hw_document_setcontent().

hw_Document_SetContent

(PHP 4 )

hw_Document_SetContent -- sets/replaces content of hw_document

Description

string hw_document_setcontent ( int hw_document, string content)

Sets or replaces the content of the document. If the document is an HTML document the content is everything after the BODY tag. Information from the HEAD and BODY tag is in the stored in the object record. If you provide this information in the content of the document too, the Hyperwave server will change the 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.

See also hw_document_attributes(), hw_document_size(), and hw_document_content().

hw_Document_Size

(PHP 3>= 3.0.3, PHP 4 )

hw_Document_Size -- size of hw_document

Description

int hw_document_size ( int hw_document)

Returns the size in bytes of the document.

See also hw_document_bodytag(), and hw_document_attributes().

For backward compatibility, hw_documentsize() is also accepted. This is deprecated, however.

hw_dummy

(PHP 3>= 3.0.3, PHP 4 )

hw_dummy --  Hyperwave dummy function

Description

string hw_dummy ( int link, int id, int msgid)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

hw_EditText

(PHP 3>= 3.0.3, PHP 4 )

hw_EditText -- retrieve text document

Description

int hw_edittext ( int connection, int hw_document)

Uploads the text document to the server. The object record of the document may not be modified while the document is edited. This function will only works for pure text documents. It will not open a special data connection and therefore blocks the control connection during the transfer.

See also hw_pipedocument(), hw_free_document(), hw_document_bodytag(), hw_document_size(), hw_output_document(), hw_gettext().

hw_Error

(PHP 3>= 3.0.3, PHP 4 )

hw_Error -- error number

Description

int hw_error ( int connection)

Returns the last error number. If the return value is 0 no error has occurred. The error relates to the last command.

hw_ErrorMsg

(PHP 3>= 3.0.3, PHP 4 )

hw_ErrorMsg -- returns error message

Description

string hw_errormsg ( int connection)

Returns a string containing the last error message or 'No Error'. If FALSE is returned, this function failed. The message relates to the last command.

hw_Free_Document

(PHP 3>= 3.0.3, PHP 4 )

hw_Free_Document -- frees hw_document

Description

int hw_free_document ( int hw_document)

Frees the memory occupied by the Hyperwave document.

hw_GetAnchors

(PHP 3>= 3.0.3, PHP 4 )

hw_GetAnchors -- object ids of anchors of document

Description

array hw_getanchors ( int connection, int objectID)

Returns an array of object ids with anchors of the document with object ID objectID.

hw_GetAnchorsObj

(PHP 3>= 3.0.3, PHP 4 )

hw_GetAnchorsObj -- object records of anchors of document

Description

array hw_getanchorsobj ( int connection, int objectID)

Returns an array of object records with anchors of the document with object ID objectID.

hw_GetAndLock

(PHP 3>= 3.0.3, PHP 4 )

hw_GetAndLock -- return bject record and lock object

Description

string hw_getandlock ( int connection, int objectID)

Returns the object record for the object with ID objectID. It will also lock the object, so other users cannot access it until it is unlocked.

See also hw_unlock(), and hw_getobject().

hw_GetChildColl

(PHP 3>= 3.0.3, PHP 4 )

hw_GetChildColl -- object ids of child collections

Description

array hw_getchildcoll ( int connection, int objectID)

Returns an array of object ids. Each object ID belongs to a child collection of the collection with ID objectID. The function will not return child documents.

See also hw_children(), and hw_getchilddoccoll().

hw_GetChildCollObj

(PHP 3>= 3.0.3, PHP 4 )

hw_GetChildCollObj -- object records of child collections

Description

array hw_getchildcollobj ( int connection, int objectID)

Returns an array of object records. Each object records belongs to a child collection of the collection with ID objectID. The function will not return child documents.

See also hw_childrenobj(), and hw_getchilddoccollobj().

hw_GetChildDocColl

(PHP 3>= 3.0.3, PHP 4 )

hw_GetChildDocColl -- object ids of child documents of collection

Description

array hw_getchilddoccoll ( int connection, int objectID)

Returns array of object ids for child documents of a collection.

See also hw_children(), and hw_getchildcoll().

hw_GetChildDocCollObj

(PHP 3>= 3.0.3, PHP 4 )

hw_GetChildDocCollObj -- object records of child documents of collection

Description

array hw_getchilddoccollobj ( int connection, int objectID)

Returns an array of object records for child documents of a collection.

See also hw_childrenobj(), and hw_getchildcollobj().

hw_GetObject

(PHP 3>= 3.0.3, PHP 4 )

hw_GetObject -- object record

Description

array hw_getobject ( int connection, [int|array] objectID, string query)

Returns the object record for the object with ID objectID if the second parameter is an integer. If the second parameter is an array of integer the function will return an array of object records. In such a case the last parameter is also evaluated which is a query string.

The query string has the following syntax:

<expr> ::= "(" <expr> ")" |

"!" <expr> | /* NOT */

<expr> "||" <expr> | /* OR */

<expr> "&&" <expr> | /* AND */

<attribute> <operator> <value>

<attribute> ::= /* any attribute name (Title, Author, DocumentType ...) */

<operator> ::= "=" | /* equal */

"<" | /* less than (string compare) */

">" | /* greater than (string compare) */

"~" /* regular expression matching */

The query allows to further select certain objects from the list of given objects. Unlike the other query functions, this query may use not indexed attributes. How many object records are returned depends on the query and if access to the object is allowed.

See also hw_getandlock(), and hw_getobjectbyquery().

hw_GetObjectByQuery

(PHP 3>= 3.0.3, PHP 4 )

hw_GetObjectByQuery -- search object

Description

array hw_getobjectbyquery ( int connection, string query, int max_hits)

Searches for objects on the whole server and returns an array of object ids. The maximum number of matches is limited to max_hits. If max_hits is set to -1 the maximum number of matches is unlimited.

The query will only work with indexed attributes.

See also hw_getobjectbyqueryobj().

hw_GetObjectByQueryColl

(PHP 3>= 3.0.3, PHP 4 )

hw_GetObjectByQueryColl -- search object in collection

Description

array hw_getobjectbyquerycoll ( int connection, int objectID, string query, int max_hits)

Searches for objects in collection with ID objectID and returns an array of object ids. The maximum number of matches is limited to max_hits. If max_hits is set to -1 the maximum number of matches is unlimited.

The query will only work with indexed attributes.

See also hw_getobjectbyquerycollobj().

hw_GetObjectByQueryCollObj

(PHP 3>= 3.0.3, PHP 4 )

hw_GetObjectByQueryCollObj -- search object in collection

Description

array hw_getobjectbyquerycollobj ( int connection, int objectID, string query, int max_hits)

Searches for objects in collection with ID objectID and returns an array of object records. The maximum number of matches is limited to max_hits. If max_hits is set to -1 the maximum number of matches is unlimited.

The query will only work with indexed attributes.

See also hw_getobjectbyquerycoll().

hw_GetObjectByQueryObj

(PHP 3>= 3.0.3, PHP 4 )

hw_GetObjectByQueryObj -- search object

Description

array hw_getobjectbyqueryobj ( int connection, string query, int max_hits)

Searches for objects on the whole server and returns an array of object records. The maximum number of matches is limited to max_hits. If max_hits is set to -1 the maximum number of matches is unlimited.

The query will only work with indexed attributes.

See also hw_getobjectbyquery().

hw_GetParents

(PHP 3>= 3.0.3, PHP 4 )

hw_GetParents -- object ids of parents

Description

array hw_getparents ( int connection, int objectID)

Returns an indexed array of object ids. Each object id belongs to a parent of the object with ID objectID.

hw_GetParentsObj

(PHP 3>= 3.0.3, PHP 4 )

hw_GetParentsObj -- object records of parents

Description

array hw_getparentsobj ( int connection, int objectID)

Returns an indexed array of object records plus an associated array with statistical information about the object records. The associated array is the last entry of the returned array. Each object record belongs to a parent of the object with ID objectID.

hw_getrellink

(PHP 3>= 3.0.3, PHP 4 )

hw_getrellink --  Get link from source to dest relative to rootid

Description

string hw_getrellink ( int link, int rootid, int sourceid, int destid)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

hw_GetRemote

(PHP 3>= 3.0.3, PHP 4 )

hw_GetRemote -- Gets a remote document

Description

int hw_getremote ( int connection, int objectID)

Returns a remote document. Remote documents in Hyperwave notation are documents retrieved from an external source. Common remote documents are for example external web pages or queries in a database. In order to be able to access external sources throught remote documents Hyperwave introduces the HGI (Hyperwave Gateway Interface) which is similar to the CGI. Currently, only ftp, http-servers and some databases can be accessed by the HGI. Calling hw_getremote() returns the document from the external source. If you want to use this function you should be very familiar with HGIs. You should also consider to use PHP instead of Hyperwave to access external sources. Adding database support by a Hyperwave gateway should be more difficult than doing it in PHP.

See also hw_getremotechildren().

hw_GetRemoteChildren

(PHP 3>= 3.0.3, PHP 4 )

hw_GetRemoteChildren -- Gets children of remote document

Description

int hw_getremotechildren ( int connection, string object record)

Returns the children of a remote document. Children of a remote document are remote documents itself. This makes sense if a database query has to be narrowed and is explained in Hyperwave Programmers' Guide. If the number of children is 1 the function will return the document itself formated by the Hyperwave Gateway Interface (HGI). If the number of children is greater than 1 it will return an array of object record with each maybe the input value for another call to hw_getremotechildren(). Those object records are virtual and do not exist in the Hyperwave server, therefore they do not have a valid object ID. How exactely such an object record looks like is up to the HGI. If you want to use this function you should be very familiar with HGIs. You should also consider to use PHP instead of Hyperwave to access external sources. Adding database support by a Hyperwave gateway should be more difficult than doing it in PHP.

See also hw_getremote().

hw_GetSrcByDestObj

(PHP 3>= 3.0.3, PHP 4 )

hw_GetSrcByDestObj -- Returns anchors pointing at object

Description

array hw_getsrcbydestobj ( int connection, int objectID)

Returns the object records of all anchors pointing to the object with ID objectID. The object can either be a document or an anchor of type destination.

See also hw_getanchors().

hw_GetText

(PHP 3>= 3.0.3, PHP 4 )

hw_GetText -- retrieve text document

Description

int hw_gettext ( int connection, int objectID [, mixed rootID/prefix])

Returns the document with object ID objectID. If the document has anchors which can be inserted, they will be inserted already. The optional parameter rootID/prefix can be a string or an integer. If it is an integer it determines how links are inserted into the document. The default is 0 and will result in links that are constructed from the name of the link's destination object. This is useful for web applications. If a link points to an object with name 'internet_movie' the HTML link will be <A HREF="/internet_movie">. The actual location of the source and destination object in the document hierachy is disregarded. You will have to set up your web browser, to rewrite that URL to for example '/my_script.php3/internet_movie'. 'my_script.php3' will have to evaluate $PATH_INFO and retrieve the document. All links will have the prefix '/my_script.php3/'. If you do not want this you can set the optional parameter rootID/prefix to any prefix which is used instead. Is this case it has to be a string.

If rootID/prefix is an integer and unequal to 0 the link is constructed from all the names starting at the object with the id rootID/prefix separated by a slash relative to the current object. If for example the above document 'internet_movie' is located at 'a-b-c-internet_movie' with '-' being the seperator between hierachy levels on the Hyperwave server and the source document is located at 'a-b-d-source' the resulting HTML link would be: <A HREF="../c/internet_movie">. This is useful if you want to download the whole server content onto disk and map the document hierachy onto the file system.

This function will only work for pure text documents. It will not open a special data connection and therefore blocks the control connection during the transfer.

See also hw_pipedocument(), hw_free_document(), hw_document_bodytag(), hw_document_size(), and hw_output_document().

hw_getusername

(PHP 3>= 3.0.3, PHP 4 )

hw_getusername -- name of currently logged in user

Description

string hw_getusername ( int connection)

Returns the username of the connection.

hw_Identify

(PHP 3>= 3.0.3, PHP 4 )

hw_Identify -- identifies as user

Description

int hw_identify ( string username, string password)

Identifies as user with username and password. Identification is only valid for the current session. I do not thing this function will be needed very often. In most cases it will be easier to identify with the opening of the connection.

See also hw_connect().

hw_InCollections

(PHP 3>= 3.0.3, PHP 4 )

hw_InCollections -- check if object ids in collections

Description

array hw_incollections ( int connection, array object_id_array, array collection_id_array, int return_collections)

Checks whether a set of objects (documents or collections) specified by the object_id_array is part of the collections listed in collection_id_array. When the fourth parameter return_collections is 0, the subset of object ids that is part of the collections (i.e., the documents or collections that are children of one or more collections of collection ids or their subcollections, recursively) is returned as an array. When the fourth parameter is 1, however, the set of collections that have one or more objects of this subset as children are returned as an array. This option allows a client to, e.g., highlight the part of the collection hierarchy that contains the matches of a previous query, in a graphical overview.

hw_Info

(PHP 3>= 3.0.3, PHP 4 )

hw_Info -- info about connection

Description

string hw_info ( int connection)

Returns information about the current connection. The returned string has the following format: <Serverstring>, <Host>, <Port>, <Username>, <Port of Client>, <Byte swapping>

hw_InsColl

(PHP 3>= 3.0.3, PHP 4 )

hw_InsColl -- insert collection

Description

int hw_inscoll ( int connection, int objectID, array object_array)

Inserts a new collection with attributes as in object_array into collection with object ID objectID.

hw_InsDoc

(PHP 3>= 3.0.3, PHP 4 )

hw_InsDoc -- insert document

Description

int hw_insdoc ( int connection, int parentID, string object_record, string text)

Inserts a new document with attributes as in object_record into collection with object ID parentID. This function inserts either an object record only or an object record and a pure ascii text in text if text is given. If you want to insert a general document of any kind use hw_insertdocument() instead.

See also hw_insertdocument(), and hw_inscoll().

hw_insertanchors

(PHP 4 >= 4.0.4)

hw_insertanchors --  Inserts only anchors into text

Description

string hw_insertanchors ( int hwdoc, array anchorecs, array dest [, array urlprefixes])

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

hw_InsertDocument

(PHP 3>= 3.0.3, PHP 4 )

hw_InsertDocument -- upload any document

Description

int hw_insertdocument ( int connection, int parent_id, int hw_document)

Uploads a document into the collection with parent_id. The document has to be created before with hw_new_document(). Make sure that the object record of the new document contains at least the attributes: Type, DocumentType, Title and Name. Possibly you also want to set the MimeType. The functions returns the object id of the new document or FALSE.

See also hw_pipedocument().

hw_InsertObject

(PHP 3>= 3.0.3, PHP 4 )

hw_InsertObject -- inserts an object record

Description

int hw_insertobject ( int connection, string object rec, string parameter)

Inserts an object into the server. The object can be any valid hyperwave object. See the HG-CSP documentation for a detailed information on how the parameters have to be.

Note: If you want to insert an Anchor, the attribute Position has always been set either to a start/end value or to 'invisible'. Invisible positions are needed if the annotation has no correspondig link in the annotation text.

See also hw_pipedocument(), hw_insertdocument(), hw_insdoc(), and hw_inscoll().

hw_mapid

(PHP 3>= 3.0.13, PHP 4 )

hw_mapid -- Maps global id on virtual local id

Description

int hw_mapid ( int connection, int server id, int object id)

Maps a global object id on any hyperwave server, even those you did not connect to with hw_connect(), onto a virtual object id. This virtual object id can then be used as any other object id, e.g. to obtain the object record with hw_getobject(). The server id is the first part of the global object id (GOid) of the object which is actually the IP number as an integer.

Note: In order to use this function you will have to set the F_DISTRIBUTED flag, which can currently only be set at compile time in hg_comm.c. It is not set by default. Read the comment at the beginning of hg_comm.c

hw_Modifyobject

(PHP 3>= 3.0.7, PHP 4 )

hw_Modifyobject -- modifies object record

Description

int hw_modifyobject ( int connection, int object_to_change, array remove, array add, int mode)

This command allows to remove, add, or modify individual attributes of an object record. The object is specified by the Object ID object_to_change. The first array remove is a list of attributes to remove. The second array add is a list of attributes to add. In order to modify an attribute one will have to remove the old one and add a new one. hw_modifyobject() will always remove the attributes before it adds attributes unless the value of the attribute to remove is not a string or array.

The last parameter determines if the modification is performed recursively. 1 means recurive modification. If some of the objects cannot be modified they will be skiped without notice. hw_error() may not indicate an error though some of the objects could not be modified.

The keys of both arrays are the attributes name. The value of each array element can either be an array, a string or anything else. If it is an array each attribute value is constructed by the key of each element plus a colon and the value of each element. If it is a string it is taken as the attribute value. An empty string will result in a complete removal of that attribute. If the value is neither a string nor an array but something else, e.g. an integer, no operation at all will be performed on the attribute. This is neccessary if you want to to add a completely new attribute not just a new value for an existing attribute. If the remove array contained an empty string for that attribute, the attribute would be tried to be removed which would fail since it doesn't exist. The following addition of a new value for that attribute would also fail. Setting the value for that attribute to e.g. 0 would not even try to remove it and the addition will work.

If you would like to change the attribute 'Name' with the current value 'books' into 'articles' you will have to create two arrays and call hw_modifyobject().

Exemplo 1. modifying an attribute

// $connect is an existing connection to the Hyperwave server
       // $objid is the ID of the object to modify
       $remarr = array("Name" => "books");
       $addarr = array("Name" => "articles");
       $hw_modifyobject($connect, $objid, $remarr, $addarr);
In order to delete/add a name=value pair from/to the object record just pass the remove/add array and set the last/third parameter to an empty array. If the attribute is the first one with that name to add, set attribute value in the remove array to an integer.

Exemplo 2. adding a completely new attribute

// $connect is an existing connection to the Hyperwave server
       // $objid is the ID of the object to modify
       $remarr = array("Name" => 0);
       $addarr = array("Name" => "articles");
       $hw_modifyobject($connect, $objid, $remarr, $addarr);

Nota: Multilingual attributes, e.g. 'Title', can be modified in two ways. Either by providing the attributes value in its native form 'language':'title' or by providing an array with elements for each language as described above. The above example would than be:

Exemplo 3. modifying Title attribute

$remarr = array("Title" => "en:Books");
       $addarr = array("Title" => "en:Articles");
       $hw_modifyobject($connect, $objid, $remarr, $addarr);
or

Exemplo 4. modifying Title attribute

$remarr = array("Title" => array("en" => "Books"));
       $addarr = array("Title" => array("en" => "Articles", "ge"=>"Artikel"));
       $hw_modifyobject($connect, $objid, $remarr, $addarr);
This removes the english title 'Books' and adds the english title 'Articles' and the german title 'Artikel'.

Exemplo 5. removing attribute

$remarr = array("Title" => "");
       $addarr = array("Title" => "en:Articles");
       $hw_modifyobject($connect, $objid, $remarr, $addarr);

Nota: This will remove all attributes with the name 'Title' and adds a new 'Title' attribute. This comes in handy if you want to remove attributes recursively.

Nota: If you need to delete all attributes with a certain name you will have to pass an empty string as the attribute value.

Nota: Only the attributes 'Title', 'Description' and 'Keyword' will properly handle the language prefix. If those attributes don't carry a language prefix, the prefix 'xx' will be assigned.

Nota: The 'Name' attribute is somewhat special. In some cases it cannot be complete removed. You will get an error message 'Change of base attribute' (not clear when this happens). Therefore you will always have to add a new Name first and than remove the old one.

Nota: You may not suround this function by calls to hw_getandlock() and hw_unlock(). hw_modifyobject() does this internally.

Returns TRUE if no error occurs otherwise FALSE.

hw_Mv

(PHP 3>= 3.0.3, PHP 4 )

hw_Mv -- moves objects

Description

int hw_mv ( int connection, array object id array, int source id, int destination id)

Moves the objects with object ids as specified in the second parameter from the collection with id source id to the collection with the id destination id. If the destination id is 0 the objects will be unlinked from the source collection. If this is the last instance of that object it will be deleted. If you want to delete all instances at once, use hw_deleteobject().

The value return is the number of moved objects.

See also hw_cp(), and hw_deleteobject().

hw_New_Document

(PHP 3>= 3.0.3, PHP 4 )

hw_New_Document -- create new document

Description

int hw_new_document ( string object_record, string document_data, int document_size)

Returns a new Hyperwave document with document data set to document_data and object record set to object_record. The length of the document_data has to passed in document_sizeThis function does not insert the document into the Hyperwave server.

See also hw_free_document(), hw_document_size(), hw_document_bodytag(), hw_output_document(), and hw_insertdocument().

hw_Objrec2Array

(PHP 3>= 3.0.3, PHP 4 )

hw_Objrec2Array -- convert attributes from object record to object array

Description

array hw_objrec2array ( string object_record [, array format])

Converts an object_record into an object array. The keys of the resulting array are the attributes names. Multi-value attributes like 'Title' in different languages form its own array. The keys of this array are the left part to the colon of the attribute value. This left part must be two characters long. Other multi-value attributes without a prefix form an indexed array. If the optional parameter is missing the attributes 'Title', 'Description' and 'Keyword' are treated as language attributes and the attributes 'Group', 'Parent' and 'HtmlAttr' as non-prefixed multi-value attributes. By passing an array holding the type for each attribute you can alter this behaviour. The array is an associated array with the attribute name as its key and the value being one of HW_ATTR_LANG or HW_ATTR_NONE

See also hw_array2objrec().

hw_Output_Document

(PHP 3>= 3.0.3, PHP 4 )

hw_Output_Document -- prints hw_document

Description

int hw_output_document ( int hw_document)

Prints the document without the BODY tag.

For backward compatibility, hw_outputdocument() is also accepted. This is deprecated, however.

hw_pConnect

(PHP 3>= 3.0.3, PHP 4 )

hw_pConnect -- make a persistent database connection

Description

int hw_pconnect ( string host, int port, string username, string password)

Returns a connection index on success, or FALSE if the connection could not be made. Opens a persistent connection to a Hyperwave server. Each of the arguments should be a quoted string, except for the port number. The username and password arguments are optional and can be left out. In such a case no identification with the server will be done. It is similar to identify as user anonymous. This function returns a connection index that is needed by other Hyperwave functions. You can have multiple persistent connections open at once.

See also hw_connect().

hw_PipeDocument

(PHP 3>= 3.0.3, PHP 4 )

hw_PipeDocument -- retrieve any document

Description

int hw_pipedocument ( int connection, int objectID)

Returns the Hyperwave document with object ID objectID. If the document has anchors which can be inserted, they will have been inserted already. The document will be transfered via a special data connection which does not block the control connection.

See also hw_gettext() for more on link insertion, hw_free_document(), hw_document_size(), hw_document_bodytag(), and hw_output_document().

hw_Root

(PHP 3>= 3.0.3, PHP 4 )

hw_Root -- root object id

Description

int hw_root ( )

Returns the object ID of the hyperroot collection. Currently this is always 0. The child collection of the hyperroot is the root collection of the connected server.

hw_setlinkroot

(PHP 3>= 3.0.3, PHP 4 )

hw_setlinkroot --  Set the id to which links are calculated

Description

void hw_setlinkroot ( int link, int rootid)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

hw_stat

(PHP 3>= 3.0.3, PHP 4 )

hw_stat --  Returns status string

Description

string hw_stat ( int link)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

hw_Unlock

(PHP 3>= 3.0.3, PHP 4 )

hw_Unlock -- unlock object

Description

int hw_unlock ( int connection, int objectID)

Unlocks a document, so other users regain access.

See also hw_getandlock().

hw_Who

(PHP 3>= 3.0.3, PHP 4 )

hw_Who -- List of currently logged in users

Description

int hw_who ( int connection)

Returns an array of users currently logged into the Hyperwave server. Each entry in this array is an array itself containing the elements id, name, system, onSinceDate, onSinceTime, TotalTime and self. 'self' is 1 if this entry belongs to the user who initianted the request.

XXXIX. Hyperwave API functions

Introdução

Hyperwave has been developed at IICM in Graz. It started with the name Hyper-G and changed to Hyperwave when it was commercialised (in 1996).

Hyperwave is not free software. The current version, 5.5, is available at http://www.hyperwave.com/. A time limited version can be ordered for free (30 days).

See also the Hyperwave module.

Hyperwave is an information system similar to a database (HIS, Hyperwave Information Server). Its focus 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 its object record. The object record contains meta data for the document. The meta data is a list of attributes which can be extended by the user. Certain attributes are always set by the Hyperwave server, other may be modified by the user.


Requisitos

Since 2001 there is a Hyperwave SDK available. It supports Java, JavaScript and C++. This PHP Extension is based on the C++ interface. In order to activate the hwapi support in PHP you will have to install the Hyperwave SDK first.


Instalação

After installing the Hyperwave SDK, configure PHP with --with-hwapi[=DIR].


Integration with Apache

The integration with Apache and possible other servers is already described in the Hyperwave module which has been the first extension to connect a Hyperwave Server.


Configuração durante execução

O comportamento dessas funções podem ser modificado pelas configurações do php.ini.

Tabela 1. Hyperwave API configuration options

Name Default Changeable
hwapi.allow_persistent "0" PHP_INI_SYSTEM
For further details and definition of the PHP_INI_* constants see ini_set().


Tipos Resource

Esta extensão não possui nenhum tipo resource.


Constantes Predefinidas

Esta extensão não possui nenhuma constante.


Classes

The API provided by the HW_API extension is fully object oriented. It is very similar to the C++ interface of the Hyperwave SDK. It consist of the following classes.

  • HW_API

  • HW_API_Object

  • HW_API_Attribute

  • HW_API_Error

  • HW_API_Content

  • HW_API_Reason

Some basic classes like HW_API_String, HW_API_String_Array, etc., which exist in the Hyperwave SDK have not been implemented since PHP has powerful replacements for them.

Each class has certain method, whose names are identical to its counterparts in the Hyperwave SDK. Passing arguments to this function differs from all the other PHP extensions but is close to the C++ API of the HW SDK. Instead of passing serval parameters they are all put into an associated array and passed as one paramter. The names of the keys are identical to those documented in the HW SDK. The common parameters are listed below. If other parameters are required they will be documented if needed.

  • objectIdentifier The name or id of an object, e.g. "rootcollection", "0x873A8768 0x00000002".

  • parentIdentifier The name or id of an object which is considered to be a parent.

  • object An instance of class HW_API_Object.

  • parameters An instance of class HW_API_Object.

  • version The version of an object.

  • mode An integer value determine the way an operation is executed.

  • attributeSelector Any array of strings, each containing a name of an attribute. This is used if you retrieve the object record and want to include certain attributes.

  • 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 a function like hw_api->children() or hw_api->find().

Índice
hw_api_attribute->key -- Returns key of the attribute
hw_api_attribute->langdepvalue -- Returns value for a given language
hw_api_attribute->value -- Returns value of the attribute
hw_api_attribute->values -- Returns all values of the attribute
hw_api_attribute -- Creates instance of class hw_api_attribute
hw_api->checkin -- Checks in an object
hw_api->checkout -- Checks out an object
hw_api->children -- Returns children of an object
hw_api_content->mimetype -- Returns mimetype
hw_api_content->read -- Read content
hw_api->content -- Returns content of an object
hw_api->copy -- Copies physically
hw_api->dbstat -- Returns statistics about database server
hw_api->dcstat -- Returns statistics about document cache server
hw_api->dstanchors -- Returns a list of all destination anchors
hw_api->dstofsrcanchors -- Returns destination of a source anchor
hw_api_error->count -- Returns number of reasons
hw_api_error->reason -- Returns reason of error
hw_api->find -- Search for objects
hw_api->ftstat -- Returns statistics about fulltext server
hwapi_hgcsp -- Returns object of class hw_api
hw_api->hwstat -- Returns statistics about Hyperwave server
hw_api->identify -- Log into Hyperwave Server
hw_api->info -- Returns information about server configuration
hw_api->insert -- Inserts a new object
hw_api->insertanchor -- Inserts a new object of type anchor
hw_api->insertcollection -- Inserts a new object of type collection
hw_api->insertdocument -- Inserts a new object of type document
hw_api->link -- Creates a link to an object
hw_api->lock -- Locks an object
hw_api->move -- Moves object between collections
hw_api_content -- Create new instance of class hw_api_content
hw_api_object->assign -- Clones object
hw_api_object->attreditable -- Checks whether an attribute is editable
hw_api_object->count -- Returns number of attributes
hw_api_object->insert -- Inserts new attribute
hw_api_object -- Creates a new instance of class hw_api_object
hw_api_object->remove -- Removes attribute
hw_api_object->title -- Returns the title attribute
hw_api_object->value -- Returns value of attribute
hw_api->object -- Retrieve attribute information
hw_api->objectbyanchor -- Returns the object an anchor belongs to
hw_api->parents -- Returns parents of an object
hw_api_reason->description -- Returns description of reason
hw_api_reason->type -- Returns type of reason
hw_api->remove -- Delete an object
hw_api->replace -- Replaces an object
hw_api->setcommitedversion -- Commits version other than last version
hw_api->srcanchors -- Returns a list of all source anchors
hw_api->srcsofdst -- Returns source of a destination object
hw_api->unlock -- Unlocks a locked object
hw_api->user -- Returns the own user object
hw_api->userlist -- Returns a list of all logged in users

hw_api_attribute->key

(no version information, might be only in CVS)

hw_api_attribute->key -- Returns key of the attribute

Description

string key ( void )

Returns the name of the attribute.

See also hwapi_attribute_value().

hw_api_attribute->langdepvalue

(no version information, might be only in CVS)

hw_api_attribute->langdepvalue -- Returns value for a given language

Description

string langdepvalue ( string language)

Returns the value in the given language of the attribute.

See also hwapi_attribute_value().

hw_api_attribute->value

(no version information, might be only in CVS)

hw_api_attribute->value -- Returns value of the attribute

Description

string value ( void )

Returns the value of the attribute.

See also hwapi_attribute_key(), hwapi_attribute_values().

hw_api_attribute->values

(no version information, might be only in CVS)

hw_api_attribute->values -- Returns all values of the attribute

Description

array values ( void )

Returns all values of the attribute as an array of strings.

See also hwapi_attribute_value().

hw_api_attribute

(no version information, might be only in CVS)

hw_api_attribute -- Creates instance of class hw_api_attribute

Description

object attribute ( [string name [, string value]])

Creates a new instance of hw_api_attribute with the given name and value.

hw_api->checkin

(no version information, might be only in CVS)

hw_api->checkin -- Checks in an object

Description

object checkin ( array parameter)

This function checks in an object or a whole hiearchie of objects. The parameters array contains the required element 'objectIdentifier' and the optional element 'version', 'comment', 'mode' and 'objectQuery'. 'version' 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 of the following values:

HW_API_CHECKIN_NORMAL

Checks in and commits the object. The object must be a document.

HW_API_CHECKIN_RECURSIVE

If the object to check in is a collection, all children will be checked in recursively if they are documents. Trying to check in a collection would result in an error.

HW_API_CHECKIN_FORCE_VERSION_CONTROL

Checks in an object even if it is not under version control.

HW_API_CHECKIN_REVERT_IF_NOT_CHANGED

Check if the new version is different from the last version. Unless this is the case the object will be checked in.

HW_API_CHECKIN_KEEP_TIME_MODIFIED

Keeps the time modified from the most recent object.

HW_API_CHECKIN_NO_AUTO_COMMIT

The object is not automatically commited on checkin.

See also hwapi_checkout().

hw_api->checkout

(no version information, might be only in CVS)

hw_api->checkout -- Checks out an object

Description

object checkout ( array parameter)

This function checks out an object or a whole hiearchie of objects. The parameters array contains the required element 'objectIdentifier' and the optional element 'version', 'mode' and 'objectQuery'. 'mode' can be one of the following values:

HW_API_CHECKIN_NORMAL

Checks out an object. The object must be a document.

HW_API_CHECKIN_RECURSIVE

If the object to check out is a collection, all children will be checked out recursively if they are documents. Trying to check out a collection would result in an error.

See also hwapi_checkin().

hw_api->children

(no version information, might be only in CVS)

hw_api->children -- Returns children of an object

Description

array children ( array parameter)

Retrieves the children of a collection or the attributes of a document. The children can be further filtered by specifying an object query. The parameter array contains the required elements 'objectIdentifier' and the optional elements 'attributeSelector' and 'objectQuery'.

The return value is an array of objects of type HW_API_Object or HW_API_Error.

See also hwapi_parents().

hw_api_content->mimetype

(no version information, might be only in CVS)

hw_api_content->mimetype -- Returns mimetype

Description

string mimetype ( void )

Returns the mimetype of the content.

hw_api_content->read

(no version information, might be only in CVS)

hw_api_content->read -- Read content

Description

string read ( string buffer, integer len)

Reads len bytes from the content into the given buffer.

hw_api->content

(no version information, might be only in CVS)

hw_api->content -- Returns content of an object

Description

object content ( array parameter)

This function returns the content of a document as an object of type hw_api_content. The parameter array contains the required elements 'objectidentifier' and the optional element 'mode'. The mode can be one of the constants HW_API_CONTENT_ALLLINKS, HW_API_CONTENT_REACHABLELINKS or HW_API_CONTENT_PLAIN. HW_API_CONTENT_ALLLINKS means to insert all anchors even if the destination is not reachable. HW_API_CONTENT_REACHABLELINKS tells hw_api_content() to insert only reachable links and HW_API_CONTENT_PLAIN will lead to document without any links.

hw_api->copy

(no version information, might be only in CVS)

hw_api->copy -- Copies physically

Description

object copy ( array parameter)

This function will make a physical copy including the content if it exists and returns the new object or an error object. The parameter array contains the required elements 'objectIdentifier' and 'destinationParentIdentifier'. The optional parameter is 'attributeSelector'`

See also hwapi_move(), hwapi_link().

hw_api->dbstat

(no version information, might be only in CVS)

hw_api->dbstat -- Returns statistics about database server

Description

object dbstat ( array parameter)

See also hwapi_dcstat(), hwapi_hwstat(), hwapi_ftstat().

hw_api->dcstat

(no version information, might be only in CVS)

hw_api->dcstat -- Returns statistics about document cache server

Description

object dcstat ( array parameter)

See also hwapi_hwstat(), hwapi_dbstat(), hwapi_ftstat().

hw_api->dstanchors

(no version information, might be only in CVS)

hw_api->dstanchors -- Returns a list of all destination anchors

Description

object dstanchors ( array parameter)

Retrieves all destination anchors of an object. The parameter array contains the required element 'objectIdentifier' and the optional elements 'attributeSelector' and 'objectQuery'.

See also hwapi_srcanchors().

hw_api->dstofsrcanchors

(no version information, might be only in CVS)

hw_api->dstofsrcanchors -- Returns destination of a source anchor

Description

object dstofsrcanchors ( array parameter)

Retrieves the destination object pointed by the specified source anchors. The destination object can either be a destination anchor or a whole document. The parameters array contains the required element 'objectIdentifier' and the optional element 'attributeSelector'.

See also hwapi_srcanchors(), hwapi_dstanchors(), hwapi_objectbyanchor().

hw_api_error->count

(no version information, might be only in CVS)

hw_api_error->count -- Returns number of reasons

Description

int count ( void )

Returns the number of error reasons.

See also hwapi_error_reason().

hw_api_error->reason

(no version information, might be only in CVS)

hw_api_error->reason -- Returns reason of error

Description

object reason ( void )

Returns the first error reason.

See also hwapi_error_count().

hw_api->find

(no version information, might be only in CVS)

hw_api->find -- Search for objects

Description

array find ( array parameter)

This functions searches for objects either by executing a key or/and full text query. The found objects can further 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 number of hits. This allows to perform an incremental search, each returning just a subset of all found documents, starting at a given index. The parameter array contains the 'keyquery' or/and 'fulltextquery' depending on who you would like to search. Optional parameters are 'objectquery', 'scope', 'lanugages' and 'attributeselector'. In case of an incremental search the optional parameters 'startIndex', numberOfObjectsToGet' and 'exactMatchUnit' can be passed.

hw_api->ftstat

(no version information, might be only in CVS)

hw_api->ftstat -- Returns statistics about fulltext server

Description

object ftstat ( array parameter)

See also hwapi_dcstat(), hwapi_dbstat(), hwapi_hwstat().

hwapi_hgcsp

(no version information, might be only in CVS)

hwapi_hgcsp -- Returns object of class hw_api

Description

object hwapi_hgcsp ( string hostname [, int port])

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.

See also hwapi_hwtp().

hw_api->hwstat

(no version information, might be only in CVS)

hw_api->hwstat -- Returns statistics about Hyperwave server

Description

object hwstat ( array parameter)

See also hwapi_dcstat(), hwapi_dbstat(), hwapi_ftstat().

hw_api->identify

(no version information, might be only in CVS)

hw_api->identify -- Log into Hyperwave Server

Description

object identify ( array parameter)

Logs into the Hyperwave Server. The parameter array must contain the elements 'username' und 'password'.

The return value will be an object of type HW_API_Error if identification failed or TRUE if it was successful.

hw_api->info

(no version information, might be only in CVS)

hw_api->info -- Returns information about server configuration

Description

object info ( array parameter)

See also hwapi_dcstat(), hwapi_dbstat(), hwapi_ftstat(), hwapi_hwstat().

hw_api->insert

(no version information, might be only in CVS)

hw_api->insert -- Inserts a new object

Description

object insert ( array parameter)

Insert a new object. The object type can be user, group, document or anchor. Depending on the type other object 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 'parameters', 'mode' and 'attributeSelector'. The 'object' must contain all attributes of the object. 'parameters' is an object as well holding futher attributes like the destination (attribute key is 'Parent'). 'content' is the content of the document. 'mode' can be a combination of the following flags:

HW_API_INSERT_NORMAL

The object in inserted into the server.

HW_API_INSERT_FORCE-VERSION-CONTROL

HW_API_INSERT_AUTOMATIC-CHECKOUT

HW_API_INSERT_PLAIN

HW_API_INSERT_KEEP_TIME_MODIFIED

HW_API_INSERT_DELAY_INDEXING

See also hwapi_replace().

hw_api->insertanchor

(no version information, might be only in CVS)

hw_api->insertanchor -- Inserts a new object of type anchor

Description

object insertanchor ( array parameter)

This function is a shortcut for hwapi_insert(). It inserts an object of type anchor and sets some of the attributes required for an anchor. The parameter array contains the required elements 'object' and 'documentIdentifier' and the optional elements 'destinationIdentifier', 'parameter', 'hint' and 'attributeSelector'. The 'documentIdentifier' specifies the document where the anchor shall be inserted. The target of the anchor is set in 'destinationIdentifier' if it already exists. If the target 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 automatically.

See also hwapi_insertdocument(), hwapi_insertcollection(), hwapi_insert().

hw_api->insertcollection

(no version information, might be only in CVS)

hw_api->insertcollection -- Inserts a new object of type collection

Description

object insertcollection ( array parameter)

This function is a shortcut for hwapi_insert(). It inserts an object of type collection and sets some of the attributes required for a collection. The parameter array contains the required elements 'object' and 'parentIdentifier' and the optional elements 'parameter' and 'attributeSelector'. See hwapi_insert() for the meaning of each element.

See also hwapi_insertdocument(), hwapi_insertanchor(), hwapi_insert().

hw_api->insertdocument

(no version information, might be only in CVS)

hw_api->insertdocument -- Inserts a new object of type document

Description

object insertdocument ( array parameter)

This function is a shortcut for hwapi_insert(). It inserts an object with content and sets some of the attributes required for a document. The parameter array contains the required elements 'object', 'parentIdentifier' and 'content' and the optional elements 'mode', 'parameter' and 'attributeSelector'. See hwapi_insert() for the meaning of each element.

See also hwapi_insert() hwapi_insertanchor(), hwapi_insertcollection().

hw_api->link

(no version information, might be only in CVS)

hw_api->link -- Creates a link to an object

Description

object link ( array parameter)

Creates a link to an object. Accessing this link is like accessing the object to links points to. The parameter array contains the required elements 'objectIdentifier' and 'destinationParentIdentifier'. 'destinationParentIdentifier' is the target collection.

The function returns TRUE on success or an error object.

See also hwapi_copy().

hw_api->lock

(no version information, might be only in CVS)

hw_api->lock -- Locks an object

Description

object lock ( array parameter)

Locks an object for exclusive editing by the user calling 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 parameters 'mode' and 'objectquery'. 'mode' determines how an object is locked. HW_API_LOCK_NORMAL means, an object is locked until it is unlocked. HW_API_LOCK_RECURSIVE is only valid for collection and 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.

See also hwapi_unlock().

hw_api->move

(no version information, might be only in CVS)

hw_api->move -- Moves object between collections

Description

object move ( array parameter)

See also hw_objrec2array().

hw_api_content

(no version information, might be only in CVS)

hw_api_content -- Create new instance of class hw_api_content

Description

string content ( string content, string mimetype)

Creates a new content object from the string content. The mimetype is set to mimetype.

hw_api_object->assign

(no version information, might be only in CVS)

hw_api_object->assign -- Clones object

Description

object assign ( array parameter)

Clones the attributes of an object.

hw_api_object->attreditable

(no version information, might be only in CVS)

hw_api_object->attreditable -- Checks whether an attribute is editable

Description

bool attreditable ( array parameter)

hw_api_object->count

(no version information, might be only in CVS)

hw_api_object->count -- Returns number of attributes

Description

int count ( array parameter)

hw_api_object->insert

(no version information, might be only in CVS)

hw_api_object->insert -- Inserts new attribute

Description

bool insert ( object attribute)

Adds an attribute to the object. Returns TRUE on success and otherwise FALSE.

See also hwapi_object_remove().

hw_api_object

(no version information, might be only in CVS)

hw_api_object -- Creates a new instance of class hw_api_object

Description

object hw_api_object ( array parameter)

See also hwapi_lock().

hw_api_object->remove

(no version information, might be only in CVS)

hw_api_object->remove -- Removes attribute

Description

bool remove ( string name)

Removes the attribute with the given name. Returns TRUE on success and otherwise FALSE.

See also hwapi_object_insert().

hw_api_object->title

(no version information, might be only in CVS)

hw_api_object->title -- Returns the title attribute

Description

string title ( array parameter)

hw_api_object->value

(no version information, might be only in CVS)

hw_api_object->value -- Returns value of attribute

Description

string value ( string name)

Returns the value of the attribute with the given name or FALSE if an error occured.

hw_api->object

(no version information, might be only in CVS)

hw_api->object -- Retrieve attribute information

Description

object hw_api->object ( array parameter)

This function retrieves the attribute information of an object of any version. It will not return the document content. The parameter array contains the required elements 'objectIdentifier' and the optional elements 'attributeSelector' and 'version'.

The returned object is an instance of class HW_API_Object on success or HW_API_Error if an error occured.

This simple example retrieves an object and checks for errors.

Exemplo 1. Retrieve an object

<?php
function handle_error($error) {
  $reason = $error->reason(0);
  echo "Type: <B>";
  switch($reason->type()) {
    case 0:
      echo "Error";
      break;
    case 1:
      echo "Warning";
      break;
    case 2:
      echo "Message";
      break;
  }
  echo "</B><BR>\n";
  echo "Description: ".$reason->description("en")."<BR>\n";
}

function list_attr($obj) {
  echo "<TABLE>\n";
  $count = $obj->count();
  for($i=0; $i<$count; $i++) {
    $attr = $obj->attribute($i);
    printf("  <TR><TD ALIGN=right bgcolor=#c0c0c0><B>%s</B></TD><TD bgcolor=#F0F0F0>%s</TD>\n",
             $attr->key(), $attr->value());
  }
  echo "</TABLE>\n";
}

$hwapi = hwapi_hgcsp($g_config[HOSTNAME]);
$parms = array("objectIdentifier"=>"rootcollection, "attributeSelector"=>array("Title", "Name", "DocumentType"));
$root = $hwapi->object($parms);
if(get_class($root) == "HW_API_Error") {
  handle_error($root);
  exit;
}
list_attr($root);
?>

See also hwapi_content().

hw_api->objectbyanchor

(no version information, might be only in CVS)

hw_api->objectbyanchor -- Returns the object an anchor belongs to

Description

object objectbyanchor ( array parameter)

This function retrieves an object the specified anchor belongs to. The parameter array contains the required element 'objectIdentifier' and the optional element 'attributeSelector'.

See also hwapi_dstofsrcanchor(), hwapi_srcanchors(), hwapi_dstanchors().

hw_api->parents

(no version information, might be only in CVS)

hw_api->parents -- Returns parents of an object

Description

array parents ( 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 'objectidentifier' and the optional elements 'attributeselector' and 'objectquery'.

The return value is an array of objects of type HW_API_Object or HW_API_Error.

See also hwapi_children().

hw_api_reason->description

(no version information, might be only in CVS)

hw_api_reason->description -- Returns description of reason

Description

string description ( void )

Returns the description of a reason

hw_api_reason->type

(no version information, might be only in CVS)

hw_api_reason->type -- Returns type of reason

Description

object type ( void )

Returns the type of a reason.

hw_api->remove

(no version information, might be only in CVS)

hw_api->remove -- Delete an object

Description

object remove ( array parameter)

This function removes an object from the specified 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 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 'parentidentifier' can be skiped. The optional parameter 'mode' determines how the deletion is performed. In normal mode the object will not be removed physically until all instances are removed. In physical mode all instances of the object will be deleted imediately. In removelinks mode all references to and from the objects will be deleted as well. In nonrecursive the deletion is not performed recursive. Removing a collection which is not empty will cause an error.

See also hwapi_move().

hw_api->replace

(no version information, might be only in CVS)

hw_api->replace -- Replaces an object

Description

object replace ( array parameter)

Replaces the attributes and the content of an object The parameter array contains the required elements 'objectIdentifier' and 'object' and the optional parameters 'content', 'parameters', 'mode' and 'attributeSelector'. 'objectIdentifier' contains the object to be replaced. 'object' contains the new object. 'content' contains the new content. 'parameters' contain extra information for HTML documents. HTML_Language is the letter abbreviation of the language of the title. HTML_Base sets the base attribute of the HTML document. 'mode' can be a combination of the following flags:

HW_API_REPLACE_NORMAL

The object on the server is replace with the object passed.

HW_API_REPLACE_FORCE_VERSION_CONTROL

HW_API_REPLACE_AUTOMATIC_CHECKOUT

HW_API_REPLACE_AUTOMATIC_CHECKIN

HW_API_REPLACE_PLAIN

HW_API_REPLACE_REVERT_IF_NOT_CHANGED

HW_API_REPLACE_KEEP_TIME_MODIFIED

See also hwapi_insert().

hw_api->setcommitedversion

(no version information, might be only in CVS)

hw_api->setcommitedversion -- Commits version other than last version

Description

object setcommitedversion ( array parameter)

Commits a version of a docuemnt. The commited version is the one which is visible to users with read access. By default the last version is the commited version.

See also hwapi_checkin(), hwapi_checkout(), hwapi_revert().

hw_api->srcanchors

(no version information, might be only in CVS)

hw_api->srcanchors -- Returns a list of all source anchors

Description

object srcanchors ( array parameter)

Retrieves all source anchors of an object. The parameter array contains the required element 'objectIdentifier' and the optional elements 'attributeSelector' and 'objectQuery'.

See also hwapi_dstanchors().

hw_api->srcsofdst

(no version information, might be only in CVS)

hw_api->srcsofdst -- Returns source of a destination object

Description

object srcsofdst ( array parameter)

Retrieves all the source anchors pointing to the specified destination. The destination object can either be a destination anchor or a whole document. The parameters array contains the required element 'objectIdentifier' and the optional element 'attributeSelector' and 'objectQuery'. The function returns an array of objects or an error.

See also hwapi_dstofsrcanchor().

hw_api->unlock

(no version information, might be only in CVS)

hw_api->unlock -- Unlocks a locked object

Description

object unlock ( array parameter)

Unlocks a locked object. Only the user who has locked the object and the system user may unlock an object. The parameter array contains the required element 'objectIdentifier' and the optional parameters 'mode' and 'objectquery'. The meaning of 'mode' is the same as in function hwapi_lock().

Returns TRUE on success or an object of class HW_API_Error.

See also hwapi_lock().

hw_api->user

(no version information, might be only in CVS)

hw_api->user -- Returns the own user object

Description

object user ( array parameter)

See also hwapi_userlist().

hw_api->userlist

(no version information, might be only in CVS)

hw_api->userlist -- Returns a list of all logged in users

Description

object userlist ( array parameter)

See also hwapi_user().

XL. iconv functions

Introdução

This module contains an interface to the iconv library functions. The iconv library functions convert strings between various character sets encodings. The supported character sets depend on the iconv() 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 library.


Requisitos

Your systems standard C library must provide the iconv() function or you must have libiconv installed on your system. The libiconv library is available from http://www.gnu.org/software/libiconv/.


Instalação

To be able to use the functions defined in this module you must compile your PHP interpreter using the configure line --with-iconv[=DIR].

Note to Win32 Users: In order to enable this module on a Windows environment, you must copy iconv-1.3.dll from the DLL folder of the PHP/Win32 binary package to the SYSTEM32 folder of your windows machine. (Ex: C:\WINNT\SYSTEM32 or C:\WINDOWS\SYSTEM32). Starting with PHP 4.2.1 the name changed to iconv.dll


Configuração durante execução

O comportamento dessas funções podem ser modificado pelas configurações do php.ini.

Tabela 1. Iconv configuration options

Name Default Changeable
iconv.input_encoding ICONV_INPUT_ENCODING PHP_INI_ALL
iconv.output_encoding ICONV_OUTPUT_ENCODING PHP_INI_ALL
iconv.internal_encoding ICONV_INTERNAL_ENCODING PHP_INI_ALL
For further details and definition of the PHP_INI_* constants see ini_set().


Tipos Resource

Esta extensão não possui nenhum tipo resource.


Constantes Predefinidas

Since PHP 4.3.0 it is possible to identify at runtime which iconv implementation is adopted by this extension.

Tabela 2. iconv constants

constant type description
ICONV_IMPL string The implementation name
ICONV_VERSION string The implementation version

Nota: Writing implementation-dependent scripts with these constants should be discouraged.


Veja Também

See also the GNU Recode functions.

Índice
iconv_get_encoding -- Get current setting for character encoding conversion
iconv_set_encoding -- Set current setting for character encoding conversion
iconv -- Convert string to requested character encoding
ob_iconv_handler -- Convert character encoding as output buffer handler

iconv_get_encoding

(PHP 4 >= 4.0.5)

iconv_get_encoding -- Get current setting for character encoding conversion

Description

array iconv_get_encoding ( [string type])

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_encoding
output_encoding
internal_encoding

If type is omitted or not 'all' iconv_get_encoding() returns the current settings of ob_iconv_handler() as string.

Exemplo 1. iconv_get_encoding() example:

<pre>
<?php
iconv_set_encoding("internal_encoding", "UTF-8");
iconv_set_encoding("output_encoding", "ISO-8859-1");
var_dump(iconv_get_encoding('all'));
?>
</pre>

The printout of the above program will be:
Array

(

    [input_encoding] => ISO-8859-1

    [output_encoding] => ISO-8859-1

    [internal_encoding] => UTF-8

)

See also: iconv_set_encoding() and ob_iconv_handler().

iconv_set_encoding

(PHP 4 >= 4.0.5)

iconv_set_encoding -- Set current setting for character encoding conversion

Description

bool iconv_set_encoding ( string type, string charset)

It changes the value of type to charset. Retorna TRUE em caso de sucesso ou FALSE em falhas.

The value of type can be:

input_encoding
output_encoding
internal_encoding

Exemplo 1. iconv_set_encoding() example:

iconv_set_encoding("internal_encoding", "UTF-8");
iconv_set_encoding("output_encoding", "ISO-8859-1");

See also: iconv_get_encoding() and ob_iconv_handler().

iconv

(PHP 4 >= 4.0.5)

iconv -- Convert string to requested character encoding

Description

string iconv ( string in_charset, string out_charset, string str)

It converts the string str encoded in in_charset to the string encoded in out_charset. It returns the converted string or FALSE, if it fails.

Exemplo 1. iconv() example:

echo iconv("ISO-8859-1","UTF-8","This is a test.");

ob_iconv_handler

(PHP 4 >= 4.0.5)

ob_iconv_handler -- Convert character encoding as output buffer handler

Description

array ob_iconv_handler ( string contents, int status)

It converts the string encoded in internal_encoding to output_encoding.

internal_encoding and output_encoding should be defined by iconv_set_encoding() or in the configuration file php.ini.

Exemplo 1. ob_iconv_handler() example:

ob_start("ob_iconv_handler"); // start output buffering

See also: iconv_get_encoding(), iconv_set_encoding(), and output-control functions.

XLI. Image functions

Introdução

PHP is not limited to creating just HTML output. It can also be used to create and manipulate image files in a variety of different image formats, including gif, png, jpg, wbmp, and xpm. Even more convenient, PHP can output image streams directly to a browser. You will need to compile PHP with the GD library of image functions for this to work. GD and PHP may also require other libraries, depending on which image formats you want to work with.

You can use the image functions in PHP to get the size of JPEG, GIF, PNG, SWF, TIFF and JPEG2000 images.

Nota: Read requirements section about how to expand image capabilities to read, write and modify images and to read meta data of pictures taken by digital cameras.


Requisitos

If you have the GD library (available at http://www.boutell.com/gd/) you will also be able to create and manipulate images.

The format of images you are able to manipulate depend on the version of GD you install, and any other libraries GD might need to access those image formats. Versions of GD older than gd-1.6 support GIF format images, and do not support PNG, where versions greater than gd-1.6 support PNG, not GIF.

Nota: Since PHP 4.3 there is a bundled version of the GD lib. This bundled version has some additional features like alpha blending, and should be used in preference to the external library since it's codebase is better maintained and more stable.

You may wish to enhance GD to handle more image formats.

Tabela 1. Supported image formats

Image format Library to download Notes
gif   Only supported in GD versions older than gd-1.6. Read-only GIF support is available with PHP 4.3.0 and the bundled GD-library.
jpeg-6b ftp://ftp.uu.net/graphics/jpeg/  
png http://www.libpng.org/pub/png/libpng.html Only supported in GD versions greater than gd-1.6.
xpm ftp://metalab.unc.edu/pub/Linux/libs/X/!INDEX.html It's likely you have this library already available, if your system has an installed X-Environment.

You may wish to enhance GD to deal with different fonts. The following font libraries are supported:

Tabela 2. Supported font libraries

Font library Download Notes
FreeType 1.x http://www.freetype.org/  
FreeType 2 http://www.freetype.org/  
T1lib ftp://sunsite.unc.edu/pub/Linux/libs/graphics/) Support for Type 1 fonts.

If you have PHP compiled with --enable-exif you are able to work with information stored in headers of JPEG and TIFF images. This way you can read meta data generated by digital cameras as mentioned above. These functions does not require the GD library.

Nota: PHP does not require any additional library for exif the module.


Instalação

To enable GD-support configure PHP --with-gd[=DIR], where DIR is the GD base install directory. To use the recommended bundled version of the GD library configure --with-gd. In Windows you'll include php_gd2.dll as an extension in php.ini. There is also php_gd.dll for GD1 but it's not preferred.

Enhance the capabilities of GD to handle more image formats by specifying the --with-XXXX configure switch to your PHP configure line.

Tabela 3. Supported image formats

Image Format Configure Switch
jpeg-6b To enable support for jpeg-6b add --with-jpeg-dir=DIR.
png To enable support for png add --with-png-dir=DIR. Note, libpng requires the zlib library, therefore add --with-zlib-dir[=DIR] to your configure line.
xpm To enable support for xpm add --with-xpm-dir=DIR. If configure is not able to find the required libraries, you may add the path to your X11 libraries.

Enhance the capabilities of GD to deal with different fonts by specifying the --with-XXXX configure switch to your PHP configure line.

Tabela 4. Supported font libraries

Font library Configure Switch
FreeType 1.x To enable support for FreeType 1.x add --with-ttf[=DIR].
FreeType 2 To enable support for FreeType 2 add --with-freetype-dir=DIR.
T1lib To enable support for T1lib (Type 1 fonts) add --with-t1lib[=DIR].
Native TrueType string function To enable support for native TrueType string function add --enable-gd-native-ttf.


Configuração durante execução

O comportamento dessas funções podem ser modificado pelas configurações do php.ini.

Exif supports automatically conversion for Unicode and JIS character encodings of user comments when module mbstring is available. This is done by first decoding the comment using the specified characterset. The result is then encoded with another characterset which should match your HTTP output.

Tabela 5. Exif configuration options

Name Default Changeable
exif.encode_unicode "ISO-8859-15" PHP_INI_ALL
exif.decode_unicode_motorola "UCS-2BE" PHP_INI_ALL
exif.decode_unicode_intel "UCS-2LE" PHP_INI_ALL
exif.encode_jis "" PHP_INI_ALL
exif.decode_jis_motorola "JIS" PHP_INI_ALL
exif.decode_jis_intel "JIS" PHP_INI_ALL
For further details and definition of the PHP_INI_* constants see ini_set().

Here is a short explanation of the configuration directives.

exif.encode_unicode string

exif.encode_unicode defines the characterset UNICODE user comments are handled. This defaults to ISO-8859-15 which should work for most non asian countries. The setting can be empty or must be an encoding supported by mbstring. If it is empty the current internal encoding of mbstring is used.

exif.decode_unicode_motorola string

exif.decode_unicode_motorola defines the image internal characterset for Unicode encoded user comments if image is in motorola byte order (big-endian). This setting cannot be empty but you can specify a list of encodings supported by mbstring. The default is UCS-2BE.

exif.decode_unicode_intel string

exif.decode_unicode_intel defines the image internal characterset for Unicode encoded user comments if image is in intel byte order (little-endian). This setting cannot be empty but you can specify a list of encodings supported by mbstring. The default is UCS-2LE.

exif.encode_jis string

exif.encode_jis defines the characterset JIS user comments are handled. This defaults to an empty value which forces the functions to use the current internal encoding of mbstring.

exif.decode_jis_motorola string

exif.decode_jis_motorola defines the image internal characterset for JIS encoded user comments if image is in motorola byte order (big-endian). This setting cannot be empty but you can specify a list of encodings supported by mbstring. The default is JIS.

exif.decode_jis_intel string

exif.decode_jis_intel defines the image internal characterset for JIS encoded user comments if image is in intel byte order (little-endian). This setting cannot be empty but you can specify a list of encodings supported by mbstring. The default is JIS.


Tipos Resource

Esta extensão não possui nenhum tipo resource.


Constantes Predefinidas

As contantes abaixo são definidas por esta extensão e somente estarão disponíveis quando a extensão foi compilada com o PHP ou carregada dinamicamente durante a execução.

IMG_GIF (integer)

IMG_JPG (integer)

IMG_JPEG (integer)

IMG_PNG (integer)

IMG_WBMP (integer)

IMG_XPM (integer)

IMG_COLOR_TILED (integer)

IMG_COLOR_STYLED (integer)

IMG_COLOR_BRUSHED (integer)

IMG_COLOR_STYLEDBRUSHED (integer)

IMG_COLOR_TRANSPARENT (integer)

IMG_ARC_ROUNDED (integer)

IMG_ARC_PIE (integer)

IMG_ARC_CHORD (integer)

IMG_ARC_NOFILL (integer)

IMG_ARC_EDGED (integer)

IMAGETYPE_GIF (integer)

IMAGETYPE_JPEG (integer)

IMAGETYPE_PNG (integer)

IMAGETYPE_SWF (integer)

IMAGETYPE_PSD (integer)

IMAGETYPE_BMP (integer)

IMAGETYPE_TIFF_II (integer)

IMAGETYPE_TIFF_MM (integer)

IMAGETYPE_JPC (integer)

IMAGETYPE_JP2 (integer)

IMAGETYPE_JPX (integer)

IMAGETYPE_SWC (integer)


Exemplos

Exemplo 1. PNG creation with PHP

<?php
    header("Content-type: image/png");
    $string = $_GET['text'];
    $im     = imagecreatefrompng("images/button1.png");
    $orange = imagecolorallocate($im, 220, 210, 60);
    $px     = (imagesx($im) - 7.5 * strlen($string)) / 2;
    imagestring($im, 3, $px, 9, $string, $orange);
    imagepng($im);
    imagedestroy($im);
?>
This example would be called from a page with a tag like: <img src="button.php?text">. The above button.php script then takes this "text" string and overlays it on top of a base image which in this case is "images/button1.png" and outputs the resulting image. This is a very convenient way to avoid having to draw new button images every time you want to change the text of a button. With this method they are dynamically generated.

Índice
exif_imagetype -- Determine the type of an image
exif_read_data -- Read the EXIF headers from JPEG or TIFF. This way you can read meta data generated by digital cameras.
exif_thumbnail -- Retrieve the embedded thumbnail of a TIFF or JPEG image
gd_info -- Retrieve information about the currently installed GD library
getimagesize -- Get the size of an image
image_type_to_mime_type -- Get Mime-Type for image-type returned by getimagesize, exif_read_data, exif_thumbnail, exif_imagetype
image2wbmp -- Output image to browser or file
imagealphablending -- Set the blending mode for an image
imagearc -- Draw a partial ellipse
imagechar -- Draw a character horizontally
imagecharup -- Draw a character vertically
imagecolorallocate -- Allocate a color for an image
imagecolorallocatealpha -- Allocate a color for an image
imagecolorat -- Get the index of the color of a pixel
imagecolorclosest -- Get the index of the closest color to the specified color
imagecolorclosestalpha -- Get the index of the closest color to the specified color + alpha
imagecolorclosesthwb --  Get the index of the color which has the hue, white and blackness nearest to the given color
imagecolordeallocate -- De-allocate a color for an image
imagecolorexact -- Get the index of the specified color
imagecolorexactalpha -- Get the index of the specified color + alpha
imagecolorresolve --  Get the index of the specified color or its closest possible alternative
imagecolorresolvealpha --  Get the index of the specified color + alpha or its closest possible alternative
imagecolorset -- Set the color for the specified palette index
imagecolorsforindex -- Get the colors for an index
imagecolorstotal -- Find out the number of colors in an image's palette
imagecolortransparent -- Define a color as transparent
imagecopy -- Copy part of an image
imagecopymerge -- Copy and merge part of an image
imagecopymergegray -- Copy and merge part of an image with gray scale
imagecopyresampled -- Copy and resize part of an image with resampling
imagecopyresized -- Copy and resize part of an image
imagecreate -- Create a new palette based image
imagecreatefromgd2 -- Create a new image from GD2 file or URL
imagecreatefromgd2part -- Create a new image from a given part of GD2 file or URL
imagecreatefromgd -- Create a new image from GD file or URL
imagecreatefromgif -- Create a new image from file or URL
imagecreatefromjpeg -- Create a new image from file or URL
imagecreatefrompng -- Create a new image from file or URL
imagecreatefromstring -- Create a new image from the image stream in the string
imagecreatefromwbmp -- Create a new image from file or URL
imagecreatefromxbm -- Create a new image from file or URL
imagecreatefromxpm -- Create a new image from file or URL
imagecreatetruecolor -- Create a new true color image
imagedashedline -- Draw a dashed line
imagedestroy -- Destroy an image
imageellipse -- Draw an ellipse
imagefill -- Flood fill
imagefilledarc -- Draw a partial ellipse and fill it
imagefilledellipse -- Draw a filled ellipse
imagefilledpolygon -- Draw a filled polygon
imagefilledrectangle -- Draw a filled rectangle
imagefilltoborder -- Flood fill to specific color
imagefontheight -- Get font height
imagefontwidth -- Get font width
imageftbbox -- Give the bounding box of a text using fonts via freetype2
imagefttext -- Write text to the image using fonts using FreeType 2
imagegammacorrect -- Apply a gamma correction to a GD image
imagegd2 -- Output GD2 image to browser or file
imagegd -- Output GD image to browser or file
imagegif -- Output image to browser or file
imageinterlace -- Enable or disable interlace
imagejpeg -- Output image to browser or file
imageline -- Draw a line
imageloadfont -- Load a new font
imagepalettecopy -- Copy the palette from one image to another
imagepng -- Output a PNG image to either the browser or a file
imagepolygon -- Draw a polygon
imagepsbbox --  Give the bounding box of a text rectangle using PostScript Type1 fonts
imagepscopyfont --  Make a copy of an already loaded font for further modification
imagepsencodefont -- Change the character encoding vector of a font
imagepsextendfont -- Extend or condense a font
imagepsfreefont -- Free memory used by a PostScript Type 1 font
imagepsloadfont -- Load a PostScript Type 1 font from file
imagepsslantfont -- Slant a font
imagepstext -- To draw a text string over an image using PostScript Type1 fonts
imagerectangle -- Draw a rectangle
imagerotate -- Rotate an image with a given angle
imagesetbrush -- Set the brush image for line drawing
imagesetpixel -- Set a single pixel
imagesetstyle -- Set the style for line drawing
imagesetthickness -- Set the thickness for line drawing
imagesettile -- Set the tile image for filling
imagestring -- Draw a string horizontally
imagestringup -- Draw a string vertically
imagesx -- Get image width
imagesy -- Get image height
imagetruecolortopalette -- Convert a true color image to a palette image
imagettfbbox -- Give the bounding box of a text using TrueType fonts
imagettftext -- Write text to the image using TrueType fonts
imagetypes -- Return the image types supported by this PHP build
imagewbmp -- Output image to browser or file
iptcembed -- Embed binary IPTC data into a JPEG image
iptcparse --  Parse a binary IPTC http://www.iptc.org/ block into single tags.
jpeg2wbmp -- Convert JPEG image file to WBMP image file
png2wbmp -- Convert PNG image file to WBMP image file
read_exif_data -- Reads header information stored in TIFF and JPEG images

exif_imagetype

(PHP 4 >= 4.3.0)

exif_imagetype -- Determine the type of an image

Description

int|false exif_imagetype ( string filename)

exif_imagetype() reads the first bytes of an image and checks its signature. When a correct signature is found a constant will be returned otherwise the return value is FALSE. The return value is the same value that getimagesize() returns in index 2 but this function is much faster.

The following constants are defined: 1 = IMAGETYPE_GIF, 2 = IMAGETYPE_JPEG, 3 = IMAGETYPE_PNG, 4 = IMAGETYPE_SWF, 5 = IMAGETYPE_PSD, 6 = IMAGETYPE_BMP, 7 = IMAGETYPE_TIFF_II (intel byte order), 8 = IMAGETYPE_TIFF_MM (motorola byte order), 9 = IMAGETYPE_JPC, 10 = IMAGETYPE_JP2, 11 = IMAGETYPE_JPX, 12 = IMAGETYPE_SWC.

This function can be used to avoid calls to other exif functions with unsupported file types or in conjunction with $_SERVER['HTTP_ACCEPT'] to check whether or not the viewer is able to see a specific image in his browser.

Nota: This function is only available in PHP 4 compiled using --enable-exif.

This function does not require the GD image library.

See also getimagesize().

exif_read_data

(PHP 4 >= 4.2.0)

exif_read_data -- Read the EXIF headers from JPEG or TIFF. This way you can read meta data generated by digital cameras.

Description

array exif_read_data ( string filename [, string sections [, bool arrays [, bool thumbnail]]])

The exif_read_data() function reads the EXIF headers from a JPEG or TIFF image file. It returns an associative array where the indexes are the header names and the values are the values associated with those headers. If no data can be returned the result is FALSE.

filename is the name of the file to read. This cannot be a url.

sections a comma separated list of sections that need to be present in file to produce a result array.

FILE FileName, FileSize, FileDateTime, SectionsFound
COMPUTED html, Width, Height, IsColor and some more if available.
ANY_TAG Any information that has a Tag e.g. IFD0, EXIF, ...
IFD0 All tagged data of IFD0. In normal imagefiles this contains image size and so forth.
THUMBNAIL A file is supposed to contain a thumbnail if it has a second IFD. All tagged information about the embedded thumbnail is stored in this section.
COMMENT Comment headers of JPEG images.
EXIF The EXIF section is a sub section of IFD0. It contains more detailed information about an image. Most of these entries are digital camera related.

arrays specifies whether or not each section becomes an array. The sections FILE, COMPUTED and THUMBNAIL allways become arrays as they may contain values whose names are conflict with other sections.

thumbnail whether or not to read the thumbnail itself and not only its tagged data.

Nota: Exif headers tend to be present in JPEG/TIFF images generated by digital cameras, but unfortunately each digital camera maker has a different idea of how to actually tag their images, so you can't always rely on a specific Exif header being present.

Exemplo 1. exif_read_data() example

<?php
echo "test1.jpg:<br />\n";
$exif = exif_read_data ('tests/test1.jpg','IFD0');
echo $exif===false ? "No header data found.<br />\n" : "Image contains headers<br />";
$exif = exif_read_data ('tests/test2.jpg',0,true);
echo "test2.jpg:<br />\n";
foreach($exif as $key=>$section) {
    foreach($section as $name=>$val) {
        echo "$key.$name: $val<br />\n";
    }
}?>

The first call fails because the image has no header information.
test1.jpg:
No header data found.
test2.jpg:
FILE.FileName: test2.jpg
FILE.FileDateTime: 1017666176
FILE.FileSize: 1240
FILE.FileType: 2
FILE.SectionsFound: ANY_TAG, IFD0, THUMBNAIL, COMMENT
COMPUTED.html: width="1" height="1"
COMPUTED.Height: 1
COMPUTED.Width: 1
COMPUTED.IsColor: 1
COMPUTED.ByteOrderMotorola: 1
COMPUTED.UserComment: Exif test image.
COMPUTED.UserCommentEncoding: ASCII
COMPUTED.Copyright: Photo (c) M.Boerger, Edited by M.Boerger.
COMPUTED.Copyright.Photographer: Photo (c) M.Boerger
COMPUTED.Copyright.Editor: Edited by M.Boerger.
IFD0.Copyright: Photo (c) M.Boerger
IFD0.UserComment: ASCII
THUMBNAIL.JPEGInterchangeFormat: 134
THUMBNAIL.JPEGInterchangeFormatLength: 523
COMMENT.0: Comment #1.
COMMENT.1: Comment #2.
COMMENT.2: Comment #3end

THUMBNAIL.JPEGInterchangeFormat: 134
THUMBNAIL.Thumbnail.Height: 1
THUMBNAIL.Thumbnail.Height: 1

Nota: If the image contains any IFD0 data then COMPUTED contains the entry ByteOrderMotorola which is 0 for little-endian (intel) and 1 for big-endian (motorola) byte order. This was added in PHP 4.3.

When an Exif header contains a Copyright note this itself can contain two values. As the solution is inconsitent in the Exif 2.10 standard the COMPUTED section will return both entries Copyright.Photographer and Copyright.Editor while the IFD0 sections contains the byte array with the NULL character that splits both entries. Or just the first entry if the datatype was wrong (normal behaviour of Exif). The COMPUTED will contain also an entry Copyright Which is either the original copyright string or it is a comma separated list of photo and editor copyright.

Nota: The tag UserComment has the same problem as the Copyright tag. It can store two values first the encoding used and second the value itself. If so the IFD section only contains the encoding or a byte array. The COMPUTED section will store both in the entries UserCommentEncoding and UserComment. The entry UserComment is available in both cases so it should be used in preference to the value in IFD0 section.

If the user comment uses Unicode or JIS encoding and the module mbstring is available this encoding will automatically changed according to the exif ini settings. This was added in PHP 4.3.

Nota: Height and Width are computed the same way getimagesize() does so their values must not be part of any header returned. Also html is a height/width text string to be used inside normal HTML.

Nota: Starting from PHP 4.3 the function can read all embedded IFD data including arrays (returned as such). Also the size of an embedded thumbnail is returned in THUMBNAIL subarray and the function exif_read_data() can return thumbnails in TIFF format. Last but not least there is no longer a maximum legth for returned values (not until memory limit is reached).

Nota: This function is only available in PHP 4 compiled using --enable-exif. Its functionality and behaviour has changed in PHP 4.2. Earlier versions are very unstable.

Since PHP 4.3 user comment can automatically change encoding if PHP 4 was compiled using --enable-mbstring.

This function does not require the GD image library.

See also exif_thumbnail() and getimagesize().

exif_thumbnail

(PHP 4 >= 4.2.0)

exif_thumbnail -- Retrieve the embedded thumbnail of a TIFF or JPEG image

Description

string exif_thumbnail ( string filename [, int &width [, int &height [, int &imagetype]]])

exif_thumbnail() reads the embedded thumbnail of a TIFF or JPEG image. If the image contains no thumbnail FALSE will be returned.

The parameters width, height and imagetype are available since PHP 4.3 and return the size of the thumbnail as well as its type. It is possible that exif_thumbnail() cannot create an image but determine its size. In this case the return value is FALSE but width and height are set.

If you want to deliver thumbnails through this function you should send the mimetype information using header() function. The following example demonstrates this:

Exemplo 1. exif_thumbnail() example

<?php
if (array_key_exists('file',$_REQUEST)) {
	$image = exif_thumbnail($_REQUEST['file'], $width, $height, $type);
} else {
    $image = false;
}
if ($image!==false) {
    header("Content-type: ".image_type_to_mime_type($type));
    echo $image;
    exit;
} else {
    // no thumbnail available, handle the error here
    echo "No thumbnail available";
}
?>

Starting from version PHP 4.3 the function exif_thumbnail() can return thumbnails in TIFF format.

Nota: This function is only available in PHP 4 compiled using --enable-exif. Its functionality and behaviour has changed in PHP 4.2

This function does not require the GD image library.

See also exif_read_data() and image_type_to_mime_type().

gd_info

(PHP 4 >= 4.3.0)

gd_info -- Retrieve information about the currently installed GD library

Description

array gd_info ( void)

Returns an associative array describing the version and capabilities of the installed GD library.

Tabela 1. Elements of array returned by gd_info()

Attribute Meaning
GD Version string value describing the installed libgd version.
Freetype Support boolean value. TRUE if Freetype Support is installed.
Freetype Linkage string value describing the way in which Freetype was linked. Expected values are: 'with freetype', 'with TTF library', and 'with unknown library'. This element will only be defined if Freetype Support evaluated to TRUE.
T1Lib Support boolean value. TRUE if T1Lib support is included.
GIF Read Support boolean value. TRUE if support for reading GIF images is included.
GIF Create Support boolean value. TRUE if support for creating GIF images is included.
JPG Support boolean value. TRUE if JPG support is included.
PNG Support boolean value. TRUE if PNG support is included.
WBMP Support boolean value. TRUE if WBMP support is included.
XBM Support boolean value. TRUE if XBM support is included.

Exemplo 1. Using gd_info()

<?php
var_dump(gd_info());

/* Typical Output
   ==============

array(9) {
  ["GD Version"]=>
  string(24) "bundled (2.0 compatible)"
  ["FreeType Support"]=>
  bool(false)
  ["T1Lib Support"]=>
  bool(false)
  ["GIF Read Support"]=>
  bool(true)
  ["GIF Create Support"]=>
  bool(false)
  ["JPG Support"]=>
  bool(false)
  ["PNG Support"]=>
  bool(true)
  ["WBMP Support"]=>
  bool(true)
  ["XBM Support"]=>
  bool(false)
}

*/
?>

See also: imagepng(), imagejpeg(), imagegif(), imagewbmp(), and imagetypes().

getimagesize

(PHP 3, PHP 4 )

getimagesize -- Get the size of an image

Description

array getimagesize ( string filename [, array imageinfo])

The getimagesize() function will determine the size of any GIF, JPG, PNG, SWF, SWC, PSD, TIFF, BMP or IFF image file and return the dimensions along with the file type and a height/width text string to be used inside a normal HTML IMG tag.

Returns an array with 4 elements. Index 0 contains the width of the image in pixels. Index 1 contains the height. Index 2 is a flag indicating the type of the image: 1 = GIF, 2 = JPG, 3 = PNG, 4 = SWF, 5 = PSD, 6 = BMP, 7 = TIFF(intel byte order), 8 = TIFF(motorola byte order), 9 = JPC, 10 = JP2, 11 = JPX, 12 = JB2, 13 = SWC, 14 = IFF. These values correspond to the IMAGETYPE constants that were added in PHP 4.3. Index 3 is a text string with the correct height="yyy" width="xxx" string that can be used directly in an IMG tag.

Exemplo 1. getimagesize (file)

<?php
$size = getimagesize ("img/flag.jpg");
echo "<img src=\"img/flag.jpg\" {$size[3]}>";
?>

Exemplo 2. getimagesize (URL)

<?php $size = getimagesize ("http://www.example.com/gifs/logo.gif"); ?>

With JPG images, two extra indexes are returned: channels and bits. channels will be 3 for RGB pictures and 4 for CMYK pictures. bits is the number of bits for each color.

Beginning with PHP 4.3, bits and channels are present for other image types, too. However, the presence of these values can be a bit confusing. As an example, GIF always uses 3 channels per pixel, but the number of bits per pixel cannot be calculated for an animated GIF with a global color table.

Some formats may contain no image or may contain multiple images. In these cases, getimagesize() might not be able to properly determine the image size. getimagesize() will return zero for width and height in these cases.

Beginning with PHP 4.3, getimagesize() also returns an additional parameter, mime, that corresponds with the MIME type of the image. This information can be used to deliver images with correct HTTP Content-type headers:

Exemplo 3. getimagesize() and MIME types

<?php
$size = getimagesize ($filename);
$fp=fopen($filename, "rb");
if ($size && $fp) {
  header("Content-type: {$size['mime']}");
  fpassthru($fp);
  exit;
} else {
  // error
}
?>

If accessing the filename image is impossible, or if it isn't a valid picture, getimagesize() will return FALSE and generate a warning.

The optional imageinfo parameter allows you to extract some extended information from the image file. Currently, this will return the different JPG APP markers as an associative array. Some programs use these APP markers to embed text information in images. A very common one is to embed IPTC http://www.iptc.org/ information in the APP13 marker. You can use the iptcparse() function to parse the binary APP13 marker into something readable.

Exemplo 4. getimagesize() returning IPTC

<?php
$size = getimagesize ("testimg.jpg",&$info);
if (isset ($info["APP13"])) {
    $iptc = iptcparse ($info["APP13"]);
    var_dump ($iptc);
}
?>

Nota: TIFF support was added in PHP 4.2.

This function does not require the GD image library.

See also image_type_to_mime_type(), exif_imagetype(), exif_read_data() and exif_thumbnail().

URL support was added in PHP 4.0.5.

image_type_to_mime_type

(PHP 4 >= 4.3.0)

image_type_to_mime_type -- Get Mime-Type for image-type returned by getimagesize, exif_read_data, exif_thumbnail, exif_imagetype

Description

string image_type_to_mime_type ( int imagetype)

The image_type_to_mime_type() function will determine the Mime-Type for an IMAGETYPE constant.

Exemplo 1. image_type_to_mime_type (file)

<?php
header ("Content-type: ".image_type_to_mime_type (IMAGETYPE_PNG));
?>

Nota: This function does not require the GD image library.

See also getimagesize(), exif_imagetype(), exif_read_data() and exif_thumbnail().

image2wbmp

(PHP 4 >= 4.0.5)

image2wbmp -- Output image to browser or file

Description

int image2wbmp ( resource image [, string filename [, int threshold]])

image2wbmp() creates the WBMP file in filename from the image image. The image argument is the return from imagecreate().

The filename argument is optional, and if left off, the raw image stream will be output directly. By sending an image/vnd.wap.wbmp content-type using header(), you can create a PHP script that outputs WBMP images directly.

Nota: WBMP support is only available if PHP was compiled against GD-1.8 or later.

See also imagewbmp().

imagealphablending

(PHP 4 >= 4.0.6)

imagealphablending -- Set the blending mode for an image

Description

int imagealphablending ( resource image, bool blendmode)

imagealphablending() allows for two different modes of drawing on truecolor images. In blending mode, the alpha channel component of the color supplied to all drawing function, such as imagesetpixel() determines 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 stores the result in the image. The resulting pixel is opaque. In non-blending mode, the drawing color is copied literally with its alpha channel information, replacing the destination pixel. Blending mode is not available when drawing on palette images. If blendmode is TRUE, then blending mode is enabled, otherwise disabled.

Nota: This function was added in PHP 4.0.6 and requires GD 2.0.1

imagearc

(PHP 3, PHP 4 )

imagearc -- Draw a partial ellipse

Description

int imagearc ( resource image, int cx, int cy, int w, int h, int s, int e, int col)

imagearc() 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 while the start and end points are specified in degrees indicated by the s and e arguments. 0° is located at the three-o'clock position, and the arc is drawn counter-clockwise.

See also imageellipse(), imagefilledellipse(), and imagefilledarc().

imagechar

(PHP 3, PHP 4 )

imagechar -- Draw a character horizontally

Description

int imagechar ( resource image, int font, int x, int y, string c, int col)

imagechar() draws the first character of c in the image identified by id with its upper-left at x,y (top left is 0, 0) with the color col. If font is 1, 2, 3, 4 or 5, a built-in font is used (with higher numbers corresponding to larger fonts).

See also imageloadfont().

imagecharup

(PHP 3, PHP 4 )

imagecharup -- Draw a character vertically

Description

int imagecharup ( resource image, int font, int x, int y, string c, int col)

imagecharup() draws the character c vertically in the image identified by image at coordinates x, y (top left is 0, 0) with the color col. If font is 1, 2, 3, 4 or 5, a built-in font is used.

See also imageloadfont().

imagecolorallocate

(PHP 3, PHP 4 )

imagecolorallocate -- Allocate a color for an image

Description

int imagecolorallocate ( resource image, int red, int green, int blue)

imagecolorallocate() returns a color identifier representing the color composed of the given RGB components. The im argument is the return from the imagecreate() function. red, green and blue are the values of the red, green and blue component of the requested color respectively. These parameters are integers between 0 and 255. imagecolorallocate() must be called to create each color that is to be used in the image represented by image.

$white = imagecolorallocate ($im, 255, 255, 255);
$black = imagecolorallocate ($im, 0, 0, 0);

Returns -1 if the allocation failed.

imagecolorallocatealpha

(no version information, might be only in CVS)

imagecolorallocatealpha -- Allocate a color for an image

Description

int imagecolorallocatealpha ( resource image, int red, int green, int blue, int alpha)

imagecolorallocatealpha() behaves identically to imagecolorallocate() with the addition of the transparency parameter alpha which may have a value between 0 and 127. 0 indicates completely opaque while 127 indicates completely transparent.

Returns FALSE if the allocation failed.

imagecolorat

(PHP 3, PHP 4 )

imagecolorat -- Get the index of the color of a pixel

Description

int imagecolorat ( resource image, int x, int y)

Returns the index of the color of the pixel at the specified location in the image specified by image.

If PHP is compiled against GD library 2.0 or higher and the image is a truecolor image, this function returns the RGB value of that pixel as integer. Use bitshifting and masking to access the distinct red, green and blue component values:

Exemplo 1. Access distinct RGB values

<?php
$im = ImageCreateFromPng("rockym.png");
$rgb = ImageColorAt($im, 100, 100);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
?>

See also imagecolorset() and imagecolorsforindex().

imagecolorclosest

(PHP 3, PHP 4 )

imagecolorclosest -- Get the index of the closest color to the specified color

Description

int imagecolorclosest ( resource image, int red, int green, int blue)

Returns the index of the color in the palette of the image which is "closest" to the specified RGB value.

The "distance" between the desired color and each color in the palette is calculated as if the RGB values represented points in three-dimensional space.

See also imagecolorexact().

imagecolorclosestalpha

(PHP 4 >= 4.0.6)

imagecolorclosestalpha -- Get the index of the closest color to the specified color + alpha

Description

int imagecolorclosestalpha ( resource image, int red, int green, int blue, int alpha)

Returns the index of the color in the palette of the image which is "closest" to the specified RGB value and alpha level.

See also imagecolorexactalpha().

Nota: This function was added in PHP 4.0.6 and requires GD 2.0.1

imagecolorclosesthwb

(PHP 4 >= 4.0.1)

imagecolorclosesthwb --  Get the index of the color which has the hue, white and blackness nearest to the given color

Description

int imagecolorclosesthwb ( resource image, int red, int green, int blue)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

imagecolordeallocate

(PHP 3>= 3.0.6, PHP 4 )

imagecolordeallocate -- De-allocate a color for an image

Description

int imagecolordeallocate ( resource image, int color)

The imagecolordeallocate() function de-allocates a color previously allocated with the imagecolorallocate() function.

$white = imagecolorallocate ($im, 255, 255, 255);
imagecolordeallocate ($im, $white);

imagecolorexact

(PHP 3, PHP 4 )

imagecolorexact -- Get the index of the specified color

Description

int imagecolorexact ( resource image, int red, int green, int blue)

Returns the index of the specified color in the palette of the image.

If the color does not exist in the image's palette, -1 is returned.

See also imagecolorclosest().

imagecolorexactalpha

(PHP 4 >= 4.0.6)

imagecolorexactalpha -- Get the index of the specified color + alpha

Description

int imagecolorexactalpha ( resource image, int red, int green, int blue, int alpha)

Returns the index of the specified color+alpha in the palette of the image.

If the color does not exist in the image's palette, -1 is returned.

See also imagecolorclosestalpha().

Nota: This function was added in PHP 4.0.6 and requires GD 2.0.1 or later

imagecolorresolve

(PHP 3>= 3.0.2, PHP 4 )

imagecolorresolve --  Get the index of the specified color or its closest possible alternative

Description

int imagecolorresolve ( resource image, int red, int green, int blue)

This function is guaranteed to return a color index for a requested color, either the exact color or the closest possible alternative.

See also imagecolorclosest().

imagecolorresolvealpha

(PHP 4 >= 4.0.6)

imagecolorresolvealpha --  Get the index of the specified color + alpha or its closest possible alternative

Description

int imagecolorresolvealpha ( resource image, int red, int green, int blue, int alpha)

This function is guaranteed to return a color index for a requested color, either the exact color or the closest possible alternative.

See also imagecolorclosestalpha().

Nota: This function was added in PHP 4.0.6 and requires GD 2.0.1

imagecolorset

(PHP 3, PHP 4 )

imagecolorset -- Set the color for the specified palette index

Description

bool imagecolorset ( resource image, int index, int red, int green, int blue)

This sets the specified index in the palette to the specified color. This is useful for creating flood-fill-like effects in paletted images without the overhead of performing the actual flood-fill.

See also imagecolorat().

imagecolorsforindex

(PHP 3, PHP 4 )

imagecolorsforindex -- Get the colors for an index

Description

array imagecolorsforindex ( resource image, int index)

This returns an associative array with red, green, and blue keys that contain the appropriate values for the specified color index.

See also imagecolorat() and imagecolorexact().

imagecolorstotal

(PHP 3, PHP 4 )

imagecolorstotal -- Find out the number of colors in an image's palette

Description

int imagecolorstotal ( resource image)

This returns the number of colors in the specified image's palette.

See also imagecolorat() and imagecolorsforindex().

imagecolortransparent

(PHP 3, PHP 4 )

imagecolortransparent -- Define a color as transparent

Description

int imagecolortransparent ( resource image [, int color])

imagecolortransparent() sets the transparent color in the image image to color. image is the image identifier returned by imagecreate() and color is a color identifier returned by imagecolorallocate().

Nota: The transparent color is a property of the image, transparency is not a property of the color. Once you have a set a color to be the transparent color, any regions of the image in that color that were drawn previously will be transparent.

The identifier of the new (or current, if none is specified) transparent color is returned.

imagecopy

(PHP 3>= 3.0.6, PHP 4 )

imagecopy -- Copy part of an image

Description

int imagecopy ( resource dst_im, resource src_im, int dst_x, int dst_y, int src_x, int src_y, int src_w, int src_h)

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 the x,y coordinates, dst_x and dst_y.

imagecopymerge

(PHP 4 >= 4.0.1)

imagecopymerge -- Copy and merge part of an image

Description

int imagecopymerge ( resource dst_im, resource src_im, int dst_x, int dst_y, int src_x, int src_y, int src_w, int src_h, int pct)

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 the x,y coordinates, dst_x and dst_y. The two images will be merged according to pct which can range from 0 to 100. When pct = 0, no action is taken, when 100 this function behaves identically to imagecopy().

Nota: This function was added in PHP 4.0.6

imagecopymergegray

(PHP 4 >= 4.0.6)

imagecopymergegray -- Copy and merge part of an image with gray scale

Description

int imagecopymergegray ( resource dst_im, resource src_im, int dst_x, int dst_y, int src_x, int src_y, int src_w, int src_h, int pct)

imagecopymergegray() 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 the x,y coordinates, dst_x and dst_y. The two images will be merged according to pct which can range from 0 to 100. When pct = 0, no action is taken, when 100 this function behaves identically to imagecopy().

This function is identical to imagecopymerge() except that when merging it preservese the hue of the source by converting the destination pixels to gray scale before the copy operation.

Nota: This function was added in PHP 4.0.6

imagecopyresampled

(PHP 4 >= 4.0.6)

imagecopyresampled -- Copy and resize part of an image with resampling

Description

int imagecopyresampled ( resource dst_im, resource src_im, int dstX, int dstY, int srcX, int srcY, int dstW, int dstH, int srcW, int srcH)

imagecopyresampled() copies a rectangular portion of one image to another image, smoothly interpolating pixel values so that, in particular, reducing the size of an image still retains a great deal of clarity. Dst_im is the destination image, src_im is the source image identifier. If the source and destination coordinates and width and heights differ, appropriate stretching or shrinking of the image fragment will be performed. The coordinates refer to the upper left corner. This function can be used to copy regions within the same image (if dst_im is the same as src_im) but if the regions overlap the results will be unpredictable.

Nota: There is a problem due to palette image limitations (255+1 colors). Resampling or filtering an image commonly needs more colors than 255, a kind of approximation is used to calculate the new resampled pixel and its color. With a palette image we try to allocate a new color, if that failed, we choose the closest (in theory) computed color. This is not always the closest visual color. That may produce a weird result, like blank (or visually blank) images. To skip this problem, please use a truecolor image as a destination image, such as one created by imagecreatetruecolor().

Nota: imagecopyresampled() requires GD 2.0.l or greater.

See also imagecopyresized().

imagecopyresized

(PHP 3, PHP 4 )

imagecopyresized -- Copy and resize part of an image

Description

int imagecopyresized ( resource dst_im, resource src_im, int dstX, int dstY, int srcX, int srcY, int dstW, int dstH, int srcW, int srcH)

imagecopyresized() copies a rectangular portion of one image to another image. Dst_im is the destination image, src_im is the source image identifier. If the source and destination coordinates and width and heights differ, appropriate stretching or shrinking of the image fragment will be performed. The coordinates refer to the upper left corner. This function can be used to copy regions within the same image (if dst_im is the same as src_im) but if the regions overlap the results will be unpredictable.

Nota: There is a problem due to palette image limitations (255+1 colors). Resampling or filtering an image commonly needs more colors than 255, a kind of approximation is used to calculate the new resampled pixel and its color. With a palette image we try to allocate a new color, if that failed, we choose the closest (in theory) computed color. This is not always the closest visual color. That may produce a weird result, like blank (or visually blank) images. To skip this problem, please use a truecolor image as a destination image, such as one created by imagecreatetruecolor().

See also imagecopyresampled().

imagecreate

(PHP 3, PHP 4 )

imagecreate -- Create a new palette based image

Description

resource imagecreate ( int x_size, int y_size)

imagecreate() returns an image identifier representing a blank image of size x_size by y_size.

We recommend the use of imagecreatetruecolor().

Exemplo 1. Creating a new GD image stream and outputting an image.

<?php
header ("Content-type: image/png");
$im = @imagecreate (50, 100)
    or die ("Cannot Initialize new GD image stream");
$background_color = imagecolorallocate ($im, 255, 255, 255);
$text_color = imagecolorallocate ($im, 233, 14, 91);
imagestring ($im, 1, 5, 5,  "A Simple Text String", $text_color);
imagepng ($im);
?>

See also imagecreatetruecolor().

imagecreatefromgd2

(PHP 4 >= 4.1.0)

imagecreatefromgd2 -- Create a new image from GD2 file or URL

Description

resource imagecreatefromgd2 ( string filename)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

Dica: Você pode usar uma URL com esta função se fopen wrappers estiver habilitado. Veja fopen() para mais detalhes em como especificar o nome do arquivo e Apêndice I para uma lista de protololos URL suportados.

Atenção

A versões Windows do PHP anteriores ao PHP 4.3 não suportam acesso a arquivos remotos através desta função, mesmo se allow_url_fopen estiver ativado.

imagecreatefromgd2part

(PHP 4 >= 4.1.0)

imagecreatefromgd2part -- Create a new image from a given part of GD2 file or URL

Description

resource imagecreatefromgd2part ( string filename, int srcX, int srcY, int width, int height)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

Dica: Você pode usar uma URL com esta função se fopen wrappers estiver habilitado. Veja fopen() para mais detalhes em como especificar o nome do arquivo e Apêndice I para uma lista de protololos URL suportados.

Atenção

A versões Windows do PHP anteriores ao PHP 4.3 não suportam acesso a arquivos remotos através desta função, mesmo se allow_url_fopen estiver ativado.

imagecreatefromgd

(PHP 4 >= 4.1.0)

imagecreatefromgd -- Create a new image from GD file or URL

Description

resource imagecreatefromgd ( string filename)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

Dica: Você pode usar uma URL com esta função se fopen wrappers estiver habilitado. Veja fopen() para mais detalhes em como especificar o nome do arquivo e Apêndice I para uma lista de protololos URL suportados.

Atenção

A versões Windows do PHP anteriores ao PHP 4.3 não suportam acesso a arquivos remotos através desta função, mesmo se allow_url_fopen estiver ativado.

imagecreatefromgif

(PHP 3, PHP 4 )

imagecreatefromgif -- Create a new image from file or URL

Description

resource imagecreatefromgif ( string filename)

imagecreatefromgif() returns an image identifier representing the image obtained from the given filename.

imagecreatefromgif() returns an empty string on failure. It also outputs an error message, which unfortunately displays as a broken link in a browser. To ease debugging the following example will produce an error GIF:

Exemplo 1. Example to handle an error during creation (courtesy vic@zymsys.com)

function LoadGif ($imgname) {
    $im = @imagecreatefromgif ($imgname); /* Attempt to open */
    if (!$im) { /* See if it failed */
        $im = imagecreate (150, 30); /* Create a blank image */
        $bgc = imagecolorallocate ($im, 255, 255, 255);
        $tc = imagecolorallocate ($im, 0, 0, 0);
        imagefilledrectangle ($im, 0, 0, 150, 30, $bgc);
        /* Output an errmsg */
        imagestring ($im, 1, 5, 5, "Error loading $imgname", $tc);
    }
    return $im;
}

Nota: Since all GIF support was removed from the GD library in version 1.6, this function is not available if you are using that version of the GD library.

Dica: Você pode usar uma URL com esta função se fopen wrappers estiver habilitado. Veja fopen() para mais detalhes em como especificar o nome do arquivo e Apêndice I para uma lista de protololos URL suportados.

Atenção

A versões Windows do PHP anteriores ao PHP 4.3 não suportam acesso a arquivos remotos através desta função, mesmo se allow_url_fopen estiver ativado.

imagecreatefromjpeg

(PHP 3>= 3.0.16, PHP 4 )

imagecreatefromjpeg -- Create a new image from file or URL

Description

resource imagecreatefromjpeg ( string filename)

imagecreatefromjpeg() returns an image identifier representing the image obtained from the given filename.

imagecreatefromjpeg() returns an empty string on failure. It also outputs an error message, which unfortunately displays as a broken link in a browser. To ease debugging the following example will produce an error JPEG:

Exemplo 1. Example to handle an error during creation (courtesy vic@zymsys.com )

function LoadJpeg ($imgname) {
    $im = @imagecreatefromjpeg ($imgname); /* Attempt to open */
    if (!$im) { /* See if it failed */
        $im  = imagecreate (150, 30); /* Create a blank image */
        $bgc = imagecolorallocate ($im, 255, 255, 255);
        $tc  = imagecolorallocate ($im, 0, 0, 0);
        imagefilledrectangle ($im, 0, 0, 150, 30, $bgc);
        /* Output an errmsg */
        imagestring ($im, 1, 5, 5, "Error loading $imgname", $tc);
    }
    return $im;
}

Dica: Você pode usar uma URL com esta função se fopen wrappers estiver habilitado. Veja fopen() para mais detalhes em como especificar o nome do arquivo e Apêndice I para uma lista de protololos URL suportados.

Atenção

A versões Windows do PHP anteriores ao PHP 4.3 não suportam acesso a arquivos remotos através desta função, mesmo se allow_url_fopen estiver ativado.

imagecreatefrompng

(PHP 3>= 3.0.13, PHP 4 )

imagecreatefrompng -- Create a new image from file or URL

Description

resource imagecreatefrompng ( string filename)

imagecreatefrompng() returns an image identifier representing the image obtained from the given filename.

imagecreatefrompng() returns an empty string on failure. It also outputs an error message, which unfortunately displays as a broken link in a browser. To ease debugging the following example will produce an error PNG:

Exemplo 1. Example to handle an error during creation (courtesy vic@zymsys.com)

function LoadPNG ($imgname) {
    $im = @imagecreatefrompng ($imgname); /* Attempt to open */
    if (!$im) { /* See if it failed */
        $im  = imagecreate (150, 30); /* Create a blank image */
        $bgc = imagecolorallocate ($im, 255, 255, 255);
        $tc  = imagecolorallocate ($im, 0, 0, 0);
        imagefilledrectangle ($im, 0, 0, 150, 30, $bgc);
        /* Output an errmsg */
        imagestring ($im, 1, 5, 5, "Error loading $imgname", $tc);
    }
    return $im;
}

Dica: Você pode usar uma URL com esta função se fopen wrappers estiver habilitado. Veja fopen() para mais detalhes em como especificar o nome do arquivo e Apêndice I para uma lista de protololos URL suportados.

Atenção

A versões Windows do PHP anteriores ao PHP 4.3 não suportam acesso a arquivos remotos através desta função, mesmo se allow_url_fopen estiver ativado.

imagecreatefromstring

(PHP 4 >= 4.0.4)

imagecreatefromstring -- Create a new image from the image stream in the string

Description

resource imagecreatefromstring ( string image)

imagecreatefromstring() returns an image identifier representing the image obtained from the given string.

imagecreatefromwbmp

(PHP 4 >= 4.0.1)

imagecreatefromwbmp -- Create a new image from file or URL

Description

resource imagecreatefromwbmp ( string filename)

imagecreatefromwbmp() returns an image identifier representing the image obtained from the given filename.

imagecreatefromwbmp() returns an empty string on failure. It also outputs an error message, which unfortunately displays as a broken link in a browser. To ease debugging the following example will produce an error WBMP:

Exemplo 1. Example to handle an error during creation (courtesy vic@zymsys.com)

function LoadWBMP ($imgname) {
    $im = @imagecreatefromwbmp ($imgname); /* Attempt to open */
    if (!$im) { /* See if it failed */
        $im  = imagecreate (20, 20); /* Create a blank image */
        $bgc = imagecolorallocate ($im, 255, 255, 255);
        $tc  = imagecolorallocate ($im, 0, 0, 0);
        imagefilledrectangle ($im, 0, 0, 10, 10, $bgc);
        /* Output an errmsg */
        imagestring ($im, 1, 5, 5, "Error loading $imgname", $tc);
    }
    return $im;
}

Nota: WBMP support is only available if PHP was compiled against GD-1.8 or later.

Dica: Você pode usar uma URL com esta função se fopen wrappers estiver habilitado. Veja fopen() para mais detalhes em como especificar o nome do arquivo e Apêndice I para uma lista de protololos URL suportados.

Atenção

A versões Windows do PHP anteriores ao PHP 4.3 não suportam acesso a arquivos remotos através desta função, mesmo se allow_url_fopen estiver ativado.

imagecreatefromxbm

(PHP 4 >= 4.0.1)

imagecreatefromxbm -- Create a new image from file or URL

Description

resource imagecreatefromxbm ( string filename)

imagecreatefromxbm() returns an image identifier representing the image obtained from the given filename.

Dica: Você pode usar uma URL com esta função se fopen wrappers estiver habilitado. Veja fopen() para mais detalhes em como especificar o nome do arquivo e Apêndice I para uma lista de protololos URL suportados.

Atenção

A versões Windows do PHP anteriores ao PHP 4.3 não suportam acesso a arquivos remotos através desta função, mesmo se allow_url_fopen estiver ativado.

imagecreatefromxpm

(PHP 4 >= 4.0.1)

imagecreatefromxpm -- Create a new image from file or URL

Description

resource imagecreatefromxpm ( string filename)

imagecreatefromxpm() returns an image identifier representing the image obtained from the given filename.

Dica: Você pode usar uma URL com esta função se fopen wrappers estiver habilitado. Veja fopen() para mais detalhes em como especificar o nome do arquivo e Apêndice I para uma lista de protololos URL suportados.

Atenção

A versões Windows do PHP anteriores ao PHP 4.3 não suportam acesso a arquivos remotos através desta função, mesmo se allow_url_fopen estiver ativado.

imagecreatetruecolor

(PHP 4 >= 4.0.6)

imagecreatetruecolor -- Create a new true color image

Description

resource imagecreatetruecolor ( int x_size, int y_size)

imagecreatetruecolor() returns an image identifier representing a black image of size x_size by y_size.

Nota: This function was added in PHP 4.0.6 and requires GD 2.0.1 or later

Nota: This function will not work with GIF file formats.

imagedashedline

(PHP 3, PHP 4 )

imagedashedline -- Draw a dashed line

Description

int imagedashedline ( resource image, int x1, int y1, int x2, int y2, int col)

This function is deprecated. Use combination of imagesetstyle() and imageline() instead.

imagedestroy

(PHP 3, PHP 4 )

imagedestroy -- Destroy an image

Description

int imagedestroy ( resource image)

imagedestroy() frees any memory associated with image image. image is the image identifier returned by the imagecreate() function.

imageellipse

(PHP 4 >= 4.0.6)

imageellipse -- Draw an ellipse

Description

int imageellipse ( resource image, int cx, int cy, int w, int h, int col)

imageellipse() draws an 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. The color of the ellipse is specified by color.

Nota: This function was added in PHP 4.0.6 and requires GD 2.0.2 or later which can be obtained at http://www.boutell.com/gd/

See also imagearc().

imagefill

(PHP 3, PHP 4 )

imagefill -- Flood fill

Description

int imagefill ( resource image, int x, int y, int col)

imagefill() performs a flood fill starting at coordinate x, y (top left is 0, 0) with color col in the image image.

imagefilledarc

(PHP 4 >= 4.0.6)

imagefilledarc -- Draw a partial ellipse and fill it

Description

int imagefilledarc ( resource image, int cx, int cy, int w, int h, int s, int e, int col, int style)

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 while the start and end points are specified in degrees indicated by the s and e arguments. style is a bitwise OR of the following possibilities:

  1. IMG_ARC_PIE

  2. IMG_ARC_CHORD

  3. IMG_ARC_NOFILL

  4. IMG_ARC_EDGED

IMG_ARC_PIE and IMG_ARC_CHORD are mutually 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 indicates that the arc or chord should be outlined, not filled. IMG_ARC_EDGED, used together with 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'.

Nota: This function was added in PHP 4.0.6 and requires GD 2.0.1

imagefilledellipse

(PHP 4 >= 4.0.6)

imagefilledellipse -- Draw a filled ellipse

Description

int imagefilledellipse ( resource image, int cx, int cy, int w, int h, int col)

imagefilledellipse() draws an 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. The ellipse is filled using color

Nota: This function was added in PHP 4.0.6 and requires GD 2.0.1 or later

See also imagefilledarc().

imagefilledpolygon

(PHP 3, PHP 4 )

imagefilledpolygon -- Draw a filled polygon

Description

int imagefilledpolygon ( resource image, array points, int num_points, int col)

imagefilledpolygon() creates a filled polygon in image image. points is a PHP array containing the polygon's vertices, ie. points[0] = x0, points[1] = y0, points[2] = x1, points[3] = y1, etc. num_points is the total number of vertices.

imagefilledrectangle

(PHP 3, PHP 4 )

imagefilledrectangle -- Draw a filled rectangle

Description

int imagefilledrectangle ( resource image, int x1, int y1, int x2, int y2, int col)

imagefilledrectangle() creates a filled rectangle of color col in image image starting at upper left coordinates x1, y1 and ending at bottom right coordinates x2, y2. 0, 0 is the top left corner of the image.

imagefilltoborder

(PHP 3, PHP 4 )

imagefilltoborder -- Flood fill to specific color

Description

int imagefilltoborder ( resource image, int x, int y, int border, int col)

imagefilltoborder() performs a flood fill whose border color is defined by border. The starting point for the fill is x, y (top left is 0, 0) and the region is filled with color col.

imagefontheight

(PHP 3, PHP 4 )

imagefontheight -- Get font height

Description

int imagefontheight ( int font)

Returns the pixel height of a character in the specified font.

See also imagefontwidth() and imageloadfont().

imagefontwidth

(PHP 3, PHP 4 )

imagefontwidth -- Get font width

Description

int imagefontwidth ( int font)

Returns the pixel width of a character in font.

See also imagefontheight() and imageloadfont().

imageftbbox

(PHP 4 >= 4.1.0)

imageftbbox -- Give the bounding box of a text using fonts via freetype2

Description

array imageftbbox ( int size, int angle, string font_file, string text [, array extrainfo])

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

imagefttext

(PHP 4 >= 4.1.0)

imagefttext -- Write text to the image using fonts using FreeType 2

Description

array imagefttext ( resource image, int size, int angle, int x, int y, int col, string font_file, string text [, array extrainfo])

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

imagegammacorrect

(PHP 3>= 3.0.13, PHP 4 )

imagegammacorrect -- Apply a gamma correction to a GD image

Description

int imagegammacorrect ( resource image, float inputgamma, float outputgamma)

The imagegammacorrect() function applies gamma correction to a gd image stream (image) given an input gamma, the parameter inputgamma and an output gamma, the parameter outputgamma.

imagegd2

(PHP 4 >= 4.1.0)

imagegd2 -- Output GD2 image to browser or file

Description

int imagegd2 ( resource image [, string filename [, int chunk_size [, string type]]])

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

The optional type parameter is either raw or compressed.

Nota: The optional chunk_size and type parameters became available in PHP 4.3.1.

imagegd

(PHP 4 >= 4.1.0)

imagegd -- Output GD image to browser or file

Description

int imagegd ( resource image [, string filename])

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

imagegif

(PHP 3, PHP 4 )

imagegif -- Output image to browser or file

Description

int imagegif ( resource image [, string filename])

imagegif() creates the GIF file in filename from the image image. The image argument is the return from the imagecreate() function.

The image format will be GIF87a unless the image has been made transparent with imagecolortransparent(), in which case the image format will be GIF89a.

The filename argument is optional, and if left off, the raw image stream will be output directly. By sending an image/gif content-type using header(), you can create a PHP script that outputs GIF images directly.

Nota: Since all GIF support was removed from the GD library in version 1.6, this function is not available if you are using that version of the GD library.

The following code snippet allows you to write more portable PHP applications by auto-detecting the type of GD support which is available. Replace the sequence header ("Content-type: image/gif"); imagegif ($im); by the more flexible sequence:

<?php
if (function_exists("imagegif")) {
    header ("Content-type: image/gif");
    imagegif ($im);
}
elseif (function_exists("imagejpeg")) {
    header ("Content-type: image/jpeg");
    imagejpeg ($im, "", 0.5);
}
elseif (function_exists("imagepng")) {
    header ("Content-type: image/png");
    imagepng ($im);
}
elseif (function_exists("imagewbmp")) {
    header ("Content-type: image/vnd.wap.wbmp");
    imagewbmp ($im);
}
else
    die("No image support in this PHP server");
?>

Nota: As of version 3.0.18 and 4.0.2 you can use the function imagetypes() in place of function_exists() for checking the presence of the various supported image formats:

if (imagetypes() & IMG_GIF) {
    header ("Content-type: image/gif");
    imagegif ($im);
}
elseif (imagetypes() & IMG_JPG) {
        ... etc.

See also imagepng(), imagewbmp(), imagejpeg(), imagetypes().

imageinterlace

(PHP 3, PHP 4 )

imageinterlace -- Enable or disable interlace

Description

int imageinterlace ( resource image [, int interlace])

imageinterlace() turns the interlace bit on or off. If interlace is 1 the image will be interlaced, and if interlace is 0 the interlace bit is turned off.

If the interlace bit is set and the image is used as a JPEG image, the image is created as a progressive JPEG.

This function returns whether the interlace bit is set for the image.

imagejpeg

(PHP 3>= 3.0.16, PHP 4 )

imagejpeg -- Output image to browser or file

Description

int imagejpeg ( resource image [, string filename [, int quality]])

imagejpeg() creates the JPEG file in filename from the image image. The image argument is the return from the imagecreate() function.

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 an empty string (''). By sending an image/jpeg content-type using header(), you can create a PHP script that outputs JPEG images directly.

Nota: JPEG support is only available if PHP was compiled against GD-1.8 or later.

quality is optional, and ranges from 0 (worst quality, smaller file) to 100 (best quality, biggest file). The default is the default IJG quality value (about 75).

If you want to output Progressive JPEGs, you need to set interlacing on with imageinterlace().

See also imagepng(), imagegif(), imagewbmp(), imageinterlace() and imagetypes().

imageline

(PHP 3, PHP 4 )

imageline -- Draw a line

Description

int imageline ( resource image, int x1, int y1, int x2, int y2, int col)

imageline() draws a line from x1, y1 to x2, y2 (top left is 0, 0) in image im of color col.

See also imagecreate() and imagecolorallocate().

imageloadfont

(PHP 3, PHP 4 )

imageloadfont -- Load a new font

Description

int imageloadfont ( string file)

imageloadfont() loads a user-defined bitmap font and returns an identifier for the font (that is always greater than 5, so it will not conflict with the built-in fonts).

The font file format is currently binary and architecture dependent. This means you should generate the font files on the same type of CPU as the machine you are running PHP on.

Tabela 1. Font file format

byte position C data type description
byte 0-3 int number of characters in the font
byte 4-7 int value of first character in the font (often 32 for space)
byte 8-11 int pixel width of each character
byte 12-15 int pixel height of each character
byte 16- char array with character data, one byte per pixel in each character, for a total of (nchars*width*height) bytes.

See also imagefontwidth() and imagefontheight().

imagepalettecopy

(PHP 4 >= 4.0.1)

imagepalettecopy -- Copy the palette from one image to another

Description

int imagepalettecopy ( resource destination, resource source)

imagepalettecopy() copies the palette from the source image to the destination image.

imagepng

(PHP 3>= 3.0.13, PHP 4 )

imagepng -- Output a PNG image to either the browser or a file

Description

int imagepng ( resource image [, string filename])

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 image to the file.

<?php
$im = imagecreatefrompng ("test.png");
imagepng ($im);
?>

See also imagegif(), imagewbmp(), imagejpeg(), imagetypes().

imagepolygon

(PHP 3, PHP 4 )

imagepolygon -- Draw a polygon

Description

int imagepolygon ( resource image, array points, int num_points, int col)

imagepolygon() creates a polygon in image id. points is a PHP array containing the polygon's vertices, ie. points[0] = x0, points[1] = y0, points[2] = x1, points[3] = y1, etc. num_points is the total number of points (vertices).

See also imagecreate() and imagecreatetruecolor().

imagepsbbox

(PHP 3>= 3.0.9, PHP 4 )

imagepsbbox --  Give the bounding box of a text rectangle using PostScript Type1 fonts

Description

array imagepsbbox ( string text, int font, int size [, int space [, int tightness [, float angle]]])

Size is expressed in pixels.

Space allows you to change the default value of a space in a font. This amount is added to the normal value and can also be negative.

Tightness allows you to control the amount of white space between characters. This amount is added to the normal character width and can also be negative.

Angle is in degrees.

Parameters space and tightness are expressed in character space units, where 1 unit is 1/1000th of an em-square.

Parameters space, tightness, and angle are optional.

The bounding box is calculated using information available from character metrics, and unfortunately tends to differ slightly from the results achieved by actually rasterizing the text. If the angle is 0 degrees, you can expect the text to need 1 pixel more to every direction.

This function returns an array containing the following elements:

0 lower left x-coordinate
1 lower left y-coordinate
2 upper right x-coordinate
3 upper right y-coordinate

See also imagepstext().

imagepscopyfont

(PHP 3>= 3.0.9, PHP 4 )

imagepscopyfont --  Make a copy of an already loaded font for further modification

Description

int imagepscopyfont ( int fontindex)

Use this function if you need make further modifications to the font, for example extending/condensing, slanting it or changing it's character encoding vector, but need to keep the original along as well. Note that the font you want to copy must be one obtained using imagepsloadfont(), not a font that is itself a copied one. You can although make modifications to it before copying.

If you use this function, you must free the fonts obtained this way yourself and in reverse order. Otherwise your script will hang.

In the case everything went right, a valid font index will be returned and can be used for further purposes. Otherwise the function returns FALSE and prints a message describing what went wrong.

See also imagepsloadfont().

imagepsencodefont

(PHP 3>= 3.0.9, PHP 4 )

imagepsencodefont -- Change the character encoding vector of a font

Description

int imagepsencodefont ( int font_index, string encodingfile)

Loads a character encoding vector from from a file and changes the fonts encoding vector to it. As a PostScript fonts default vector lacks most of the character positions above 127, you'll definitely want to change this if you use an other language than english. The exact format of this file is described in T1libs documentation. T1lib comes with two ready-to-use files, IsoLatin1.enc and IsoLatin2.enc.

If you find yourself using this function all the time, a much better way to define the encoding is to set ps.default_encoding in the configuration file to point to the right encoding file and all fonts you load will automatically have the right encoding.

imagepsextendfont

(PHP 3>= 3.0.9, PHP 4 )

imagepsextendfont -- Extend or condense a font

Description

bool imagepsextendfont ( int font_index, float extend)

Extend or condense a font (font_index), if the value of the extend parameter is less than one you will be condensing the font.

imagepsfreefont

(PHP 3>= 3.0.9, PHP 4 )

imagepsfreefont -- Free memory used by a PostScript Type 1 font

Description

void imagepsfreefont ( int fontindex)

See also imagepsloadfont().

imagepsloadfont

(PHP 3>= 3.0.9, PHP 4 )

imagepsloadfont -- Load a PostScript Type 1 font from file

Description

int imagepsloadfont ( string filename)

In the case everything went right, a valid font index will be returned and can be used for further purposes. Otherwise the function returns FALSE and prints a message describing what went wrong, which you cannot read directly, while the output type is image.

<?php
header ("Content-type: image/jpeg");
$im = imagecreate (350, 45);
$black = imagecolorallocate ($im, 0, 0, 0);
$white = imagecolorallocate ($im, 255, 255, 255);
$font = imagepsloadfont ("bchbi.pfb"); // or locate your .pfb files on your machine
imagepstext ($im, "Testing... It worked!", $font, 32, $white, $black, 32, 32);
imagepsfreefont ($font);
imagejpeg ($im, "", 100); //for best quality...your mileage may vary
imagedestroy ($im);
?>

See also imagepsfreefont().

imagepsslantfont

(PHP 3>= 3.0.9, PHP 4 )

imagepsslantfont -- Slant a font

Description

bool imagepsslantfont ( int font_index, float slant)

Slant a font given by the font_index parameter with a slant of the value of the slant parameter.

imagepstext

(PHP 3>= 3.0.9, PHP 4 )

imagepstext -- To draw a text string over an image using PostScript Type1 fonts

Description

array imagepstext ( resource image, string text, int font, int size, int foreground, int background, int x, int y [, int space [, int tightness [, float angle [, int antialias_steps]]]])

Size is expressed in pixels.

Foreground is the color in which the text will be painted. Background is the color to which the text will try to fade in with antialiasing. No pixels with the color background are actually painted, so the background image does not need to be of solid color.

The coordinates given by x, y will define the origin (or reference point) of the first character (roughly the lower-left corner of the character). This is different from the imagestring(), where x, y define the upper-right corner of the first character. Refer to PostScipt documentation about fonts and their measuring system if you have trouble understanding how this works.

Space allows you to change the default value of a space in a font. This amount is added to the normal value and can also be negative.

Tightness allows you to control the amount of white space between characters. This amount is added to the normal character width and can also be negative.

Angle is in degrees.

Antialias_steps allows you to control the number of colours used for antialiasing text. Allowed values are 4 and 16. The higher value is recommended for text sizes lower than 20, where the effect in text quality is quite visible. With bigger sizes, use 4. It's less computationally intensive.

Parameters space and tightness are expressed in character space units, where 1 unit is 1/1000th of an em-square.

Parameters space, tightness, angle and antialias are optional.

This function returns an array containing the following elements:

0 lower left x-coordinate
1 lower left y-coordinate
2 upper right x-coordinate
3 upper right y-coordinate

See also imagepsbbox().

imagerectangle

(PHP 3, PHP 4 )

imagerectangle -- Draw a rectangle

Description

int imagerectangle ( resource image, int x1, int y1, int x2, int y2, int col)

imagerectangle() creates a rectangle of color col in image image starting at upper left coordinate x1, y1 and ending at bottom right coordinate x2, y2. 0, 0 is the top left corner of the image.

imagerotate

(PHP 4 >= 4.3.0)

imagerotate -- Rotate an image with a given angle

Description

ressource imagerotate ( resource src_im, float angle, int bgd_color)

Rotates the src_im image using a given angle in degree. bgd_color specifies the color of the uncovered zone after the rotation.

imagesetbrush

(PHP 4 >= 4.0.6)

imagesetbrush -- Set the brush image for line drawing

Description

int imagesetbrush ( resource image, resource brush)

imagesetbrush() sets the brush image to be used by all line drawing functions (such as imageline() and imagepolygon()) when drawing with the special colors IMG_COLOR_BRUSHED or IMG_COLOR_STYLEDBRUSHED.

Nota: You need not take special action when you are finished with a brush, but if you destroy the brush image, you must not use the IMG_COLOR_BRUSHED or IMG_COLOR_STYLEDBRUSHED colors until you have set a new brush image!

Nota: This function was added in PHP 4.0.6

imagesetpixel

(PHP 3, PHP 4 )

imagesetpixel -- Set a single pixel

Description

int imagesetpixel ( resource image, int x, int y, int col)

imagesetpixel() draws a pixel at x, y (top left is 0, 0) in image image of color col.

See also imagecreate() and imagecolorallocate().

imagesetstyle

(PHP 4 >= 4.0.6)

imagesetstyle -- Set the style for line drawing

Description

int imagesetstyle ( resource image, array style)

imagesetstyle() sets the style to be used by all line drawing functions (such as imageline() and imagepolygon()) when drawing with the special color IMG_COLOR_STYLED or lines of images with color IMG_COLOR_STYLEDBRUSHED.

The style parameter is an array of pixels. Following example script draws a dashed line from upper left to lower right corner of the canvas:

Exemplo 1. imagesetstyle() example

<?php
header ("Content-type: image/jpeg");
$im  = imagecreate (100, 100);
$w   = imagecolorallocate ($im, 255, 255, 255);
$red = imagecolorallocate ($im, 255, 0, 0);

/* Draw a dashed line, 5 red pixels, 5 white pixels */
$style = array ($red,$red,$red,$red,$red,$w,$w,$w,$w,$w);
imagesetstyle ($im, $style);
imageline ($im, 0, 0, 100, 100, IMG_COLOR_STYLED);

/* Draw a line of happy faces using imagesetbrush() with imagesetstyle */
$style = array ($w,$w,$w,$w,$w,$w,$w,$w,$w,$w,$w,$w,$red);
imagesetstyle ($im, $style);

$brush = imagecreatefrompng ("http://www.libpng.org/pub/png/images/smile.happy.png");
$w2 = imagecolorallocate($brush,255,255,255);
imagecolortransparent ($brush, $w2);
imagesetbrush ($im, $brush);
imageline ($im, 100, 0, 0, 100, IMG_COLOR_STYLEDBRUSHED);

imagejpeg ($im);
imagedestroy ($im);
?>

See also imagesetbrush(), imageline().

Nota: This function was added in PHP 4.0.6

imagesetthickness

(PHP 4 >= 4.0.6)

imagesetthickness -- Set the thickness for line drawing

Description

void imagesetthickness ( resource image, int thickness)

imagesetthickness() sets the thickness of the lines drawn when drawing rectangles, polygons, ellipses etc. etc. to thickness pixels.

Nota: This function was added in PHP 4.0.6 and requires GD 2.0.1 or later

imagesettile

(PHP 4 >= 4.0.6)

imagesettile -- Set the tile image for filling

Description

int imagesettile ( resource image, resource tile)

imagesettile() sets the tile image to be used by all region filling functions (such as imagefill() and imagefilledpolygon()) when filling with the special color IMG_COLOR_TILED.

A tile is an image used to fill an area with a repeated 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 the underlying area to shine through can be created.

Nota: You need not take special action when you are finished with a tile, but if you destroy the tile image, you must not use the IMG_COLOR_TILED color until you have set a new tile image!

Nota: This function was added in PHP 4.0.6

imagestring

(PHP 3, PHP 4 )

imagestring -- Draw a string horizontally

Description

int imagestring ( resource image, int font, int x, int y, string s, int col)

imagestring() draws the string s in the image identified by image at coordinates x, y (top left is 0, 0) in color col. If font is 1, 2, 3, 4 or 5, a built-in font is used.

See also imageloadfont().

imagestringup

(PHP 3, PHP 4 )

imagestringup -- Draw a string vertically

Description

int imagestringup ( resource image, int font, int x, int y, string s, int col)

imagestringup() draws the string s vertically in the image identified by image at coordinates x, y (top left is 0, 0) in color col. If font is 1, 2, 3, 4 or 5, a built-in font is used.

See also imageloadfont().

imagesx

(PHP 3, PHP 4 )

imagesx -- Get image width

Description

int imagesx ( resource image)

imagesx() returns the width of the image identified by image.

See also imagecreate() and imagesy().

imagesy

(PHP 3, PHP 4 )

imagesy -- Get image height

Description

int imagesy ( resource image)

imagesy() returns the height of the image identified by image.

See also imagecreate() and imagesx().

imagetruecolortopalette

(PHP 4 >= 4.0.6)

imagetruecolortopalette -- Convert a true color image to a palette image

Description

void imagetruecolortopalette ( resource image, bool dither, int ncolors)

imagetruecolortopalette() converts a truecolor image to a palette image. The code for this function was originally drawn from the Independent JPEG Group library 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 as well as possible. This does not work as well as might be hoped. It is usually best to simply produce a truecolor output image instead, which guarantees the highest output quality.

dither indicates if the image should be dithered - if it is TRUE then dithering will be used which will result in a more speckled image but with better color approximation.

ncolors sets the maximum number of colors that should be retained in the palette.

Nota: This function was added in PHP 4.0.6 and requires GD 2.0.1 or later

imagettfbbox

(PHP 3>= 3.0.1, PHP 4 )

imagettfbbox -- Give the bounding box of a text using TrueType fonts

Description

array imagettfbbox ( int size, int angle, string fontfile, string text)

This function calculates and returns the bounding box in pixels for a TrueType text.

text

The string to be measured.

size

The font size in pixels.

fontfile

The name of the TrueType font file. (Can also be an URL.) Depending on which version of the GD library that PHP is using, it may attempt to search for files that do not begin with a leading '/' by appending '.ttf' to the filename and searching along a library-defined font path.

angle

Angle in degrees in which text will be measured.

imagettfbbox() returns an array with 8 elements representing four points making the bounding box of the text:

0 lower left corner, X position
1 lower left corner, Y position
2 lower right corner, X position
3 lower right corner, Y position
4 upper right corner, X position
5 upper right corner, Y position
6 upper left corner, X position
7 upper left corner, Y position

The points are relative to the text regardless of the angle, so "upper left" means in the top left-hand corner seeing the text horizontallty.

This function requires both the GD library and the FreeType library.

See also imagettftext().

imagettftext

(PHP 3, PHP 4 )

imagettftext -- Write text to the image using TrueType fonts

Description

array imagettftext ( resource im, int size, int angle, int x, int y, int col, string fontfile, string text)

imagettftext() draws the string text in the image identified by image, starting at coordinates x, y (top left is 0, 0), at an angle of angle in color col, using the TrueType font file identified by fontfile. Depending on which version of the GD library that PHP is using, when fontfile does not begin with a leading '/', '.ttf' will be appended to the filename and the library will attempt to search for that filename along a library-defined font path.

The coordinates given by x, y will define the basepoint of the first character (roughly the lower-left corner of the character). This is different from the imagestring(), where x, y define the upper-right corner of the first character.

angle is in degrees, with 0 degrees being left-to-right reading text (3 o'clock direction), and higher values representing a counter-clockwise rotation. (i.e., a value of 90 would result in bottom-to-top reading text).

fontfile is the path to the TrueType font you wish to use.

text is the text string which may include UTF-8 character sequences (of the form: &#123;) to access characters in a font beyond the first 255.

Col is the color index. Using the negative of a color index has the effect of turning off antialiasing.

imagettftext() returns an array with 8 elements representing four points making the bounding box of the text. The order of the points is lower left, lower right, upper right, upper left. The points are relative to the text regardless of the angle, so "upper left" means in the top left-hand corner when you see the text horizontallty.

This example script will produce a black GIF 400x30 pixels, with the words "Testing..." in white in the font Arial.

Exemplo 1. imagettftext() example

<?php
  header("Content-type: image/jpeg");
  $im = imagecreate(400,30);
  $white = imagecolorallocate($im, 255,255,255);
  $black = imagecolorallocate($im, 0,0,0);
  
  // Replace path by your own font path
  imagettftext($im, 20, 0, 10, 20, $black, "/path/arial.ttf",
  "Testing... Omega: &amp;#937;");
  imagejpeg($im);
  imagedestroy($im);
?>

This function requires both the GD library and the FreeType library.

See also imagettfbbox().

imagetypes

(PHP 3 CVS only, PHP 4 >= 4.0.2)

imagetypes -- Return the image types supported by this PHP build

Description

int imagetypes ( void)

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 | IMG_PNG | IMG_WBMP. To check for PNG support, for example, do this:

Exemplo 1. imagetypes

<?php
if (imagetypes() & IMG_PNG) {
    echo "PNG Support is enabled";
}
?>

imagewbmp

(PHP 3>= 3.0.15, PHP 4 >= 4.0.1)

imagewbmp -- Output image to browser or file

Description

int imagewbmp ( resource image [, string filename [, int foreground]])

imagewbmp() creates the WBMP file in filename from the image image. The image argument is the return from the imagecreate() function.

The filename argument is optional, and if left off, the raw image stream will be output directly. By sending an image/vnd.wap.wbmp content-type using header(), you can create a PHP script that outputs WBMP images directly.

Nota: WBMP support is only available if PHP was compiled against GD-1.8 or later.

Using the optional foreground parameter, you can set the foreground color. Use an identifier obtained from imagecolorallocate(). The default foreground color is black.

See also image2wbmp(), imagepng(), imagegif(), imagejpeg(), imagetypes().

iptcembed

(PHP 3>= 3.0.7, PHP 4 )

iptcembed -- Embed binary IPTC data into a JPEG image

Description

array iptcembed ( string iptcdata, string jpeg_file_name [, int spool])

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

iptcparse

(PHP 3>= 3.0.6, PHP 4 )

iptcparse --  Parse a binary IPTC http://www.iptc.org/ block into single tags.

Description

array iptcparse ( string iptcblock)

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 if no IPTC data was found. See getimagesize() for a sample.

jpeg2wbmp

(PHP 4 >= 4.0.5)

jpeg2wbmp -- Convert JPEG image file to WBMP image file

Description

int jpeg2wbmp ( string jpegname, string wbmpname, int d_height, int d_width, int threshold)

Converts the jpegname JPEG file to WBMP format, and saves it as wbmpname. With the d_height and d_width you specify the height and width of the destination image.

Nota: WBMP support is only available if PHP was compiled against GD-1.8 or later.

See also png2wbmp().

png2wbmp

(PHP 4 >= 4.0.5)

png2wbmp -- Convert PNG image file to WBMP image file

Description

int png2wbmp ( string pngname, string wbmpname, int d_height, int d_width, int threshold)

Converts the pngname PNG file to WBMP format, and saves it as wbmpname. With the d_height and d_width you specify the height and width of the destination image.

Nota: WBMP support is only available if PHP was compiled against GD-1.8 or later.

See also jpeg2wbmp().

read_exif_data

(PHP 4 >= 4.0.1)

read_exif_data -- Reads header information stored in TIFF and JPEG images

Description

array exif_read_data ( string filename, string sections, bool arrays, bool thumbnail)

Nota: The read_exif_data() function is an alias for exif_read_data().

See also exif_thumbnail().

XLII. IMAP, POP3 and NNTP functions

Introdução

These functions are not limited to the IMAP protocol, despite their name. The underlying c-client library also supports NNTP, POP3 and local mailbox access methods.


Requisitos

This extension requires the c-client library to be installed. Grab the latest version from ftp://ftp.cac.washington.edu/imap/ and compile it.

It's important that you do not copy the IMAP source files directly into the system include directory as there may be conflicts. Instead, create a new directory inside the system include directory, such as /usr/local/imap-2000b/ (location and name depend on your setup and IMAP version), and inside this new directory create additional directories named lib/ and include/. From the c-client directory from your IMAP source tree, copy all the *.h files into include/ and all the *.c files into lib/. Additionally when you compiled IMAP, a file named c-client-a was created. Also put this in the lib/ directory but rename it as libc-client.a.

Nota: To build the c-client library with SSL or/and Kerberos support read the docs supplied with the package.


Instalação

To get these functions to work, you have to compile PHP with --with-imap[=DIR], where DIR is the c-client install prefix. From our example above, you would use --with-imap=/usr/local/imap-2000b. This location depends on where you created this directory according to the description above.

Nota: Depending how the c-client was configured, you might also need to add --with-imap-ssl=/path/to/openssl/ and/or --with-kerberos=/path/to/kerberos into the PHP configure line.

Atenção

The IMAP extension cannot be used in conjuction with the recode or YAZ extensions. This is due to the fact that they both share the same internal symbol.


Configuração durante execução

Esta extenção não define nenhum parâmetro de configuração no php.ini.


Tipos Resource


Constantes Predefinidas

As contantes abaixo são definidas por esta extensão e somente estarão disponíveis quando a extensão foi compilada com o PHP ou carregada dinamicamente durante a execução.

NIL (integer)

OP_DEBUG (integer)

OP_READONLY (integer)

OP_ANONYMOUS (integer)

OP_SHORTCACHE (integer)

OP_SILENT (integer)

OP_PROTOTYPE (integer)

OP_HALFOPEN (integer)

OP_EXPUNGE (integer)

OP_SECURE (integer)

CL_EXPUNGE (integer)

FT_UID (integer)

FT_PEEK (integer)

FT_NOT (integer)

FT_INTERNAL (integer)

FT_PREFETCHTEXT (integer)

ST_UID (integer)

ST_SILENT (integer)

ST_SET (integer)

CP_UID (integer)

CP_MOVE (integer)

SE_UID (integer)

SE_FREE (integer)

SE_NOPREFETCH (integer)

SO_FREE (integer)

SO_NOSERVER (integer)

SA_MESSAGES (integer)

SA_RECENT (integer)

SA_UNSEEN (integer)

SA_UIDNEXT (integer)

SA_UIDVALIDITY (integer)

SA_ALL (integer)

LATT_NOINFERIORS (integer)

LATT_NOSELECT (integer)

LATT_MARKED (integer)

LATT_UNMARKED (integer)

SORTDATE (integer)

SORTARRIVAL (integer)

SORTFROM (integer)

SORTSUBJECT (integer)

SORTTO (integer)

SORTCC (integer)

SORTSIZE (integer)

TYPETEXT (integer)

TYPEMULTIPART (integer)

TYPEMESSAGE (integer)

TYPEAPPLICATION (integer)

TYPEAUDIO (integer)

TYPEIMAGE (integer)

TYPEVIDEO (integer)

TYPEOTHER (integer)

ENC7BIT (integer)

ENC8BIT (integer)

ENCBINARY (integer)

ENCBASE64 (integer)

ENCQUOTEDPRINTABLE (integer)

ENCOTHER (integer)


Veja Também

This document can't go into detail on all the topics touched by the provided functions. Further information is provided by the documentation of the c-client library source (docs/internal.txt). and the following RFC documents:

  • RFC2821: Simple Mail Transfer Protocol (SMTP).

  • RFC2822: Standard for ARPA internet text messages.

  • RFC2060: Internet Message Access Protocol (IMAP) Version 4rev1.

  • RFC1939: Post Office Protocol Version 3 (POP3).

  • RFC977: Network News Transfer Protocol (NNTP).

  • RFC2076: Common Internet Message Headers.

  • RFC2045 , RFC2046 , RFC2047 , RFC2048 & RFC2049: Multipurpose Internet Mail Extensions (MIME).

A detailed overview is also available in the books Programming Internet Email by David Wood and Managing IMAP by Dianna Mullet & Kevin Mullet.

Índice
imap_8bit --  Convert an 8bit string to a quoted-printable string
imap_alerts --  This function returns all IMAP alert messages (if any) that have occurred during this page request or since the alert stack was reset
imap_append --  Append a string message to a specified mailbox
imap_base64 -- Decode BASE64 encoded text
imap_binary --  Convert an 8bit string to a base64 string
imap_body -- Read the message body
imap_bodystruct --  Read the structure of a specified body section of a specific message
imap_check -- Check current mailbox
imap_clearflag_full -- Clears flags on messages
imap_close -- Close an IMAP stream
imap_createmailbox -- Create a new mailbox
imap_delete --  Mark a messge for deletion from current mailbox
imap_deletemailbox -- Delete a mailbox
imap_errors --  This function returns all of the IMAP errors (if any) that have occurred during this page request or since the error stack was reset.
imap_expunge -- Delete all messages marked for deletion
imap_fetch_overview --  Read an overview of the information in the headers of the given message
imap_fetchbody --  Fetch a particular section of the body of the message
imap_fetchheader -- Returns header for a message
imap_fetchstructure --  Read the structure of a particular message
imap_get_quota --  Retrieve the quota level settings, and usage statics per mailbox
imap_get_quotaroot --  Retrieve the quota settings per user
imap_getmailboxes --  Read the list of mailboxes, returning detailed information on each one
imap_getsubscribed -- List all the subscribed mailboxes
imap_header -- Read the header of the message
imap_headerinfo -- Read the header of the message
imap_headers --  Returns headers for all messages in a mailbox
imap_last_error --  This function returns the last IMAP error (if any) that occurred during this page request
imap_list -- Read the list of mailboxes
imap_listmailbox -- Read the list of mailboxes
imap_listscan --  Read the list of mailboxes, takes a string to search for in the text of the mailbox
imap_listsubscribed -- List all the subscribed mailboxes
imap_lsub -- List all the subscribed mailboxes
imap_mail_compose --  Create a MIME message based on given envelope and body sections
imap_mail_copy -- Copy specified messages to a mailbox
imap_mail_move -- Move specified messages to a mailbox
imap_mail --  Send an email message
imap_mailboxmsginfo -- Get information about the current mailbox
imap_mime_header_decode -- Decode MIME header elements
imap_msgno --  This function returns the message sequence number for the given UID
imap_num_msg --  Gives the number of messages in the current mailbox
imap_num_recent -- Gives the number of recent messages in current mailbox
imap_open -- Open an IMAP stream to a mailbox
imap_ping -- Check if the IMAP stream is still active
imap_qprint -- Convert a quoted-printable string to an 8 bit string
imap_renamemailbox -- Rename an old mailbox to new mailbox
imap_reopen -- Reopen IMAP stream to new mailbox
imap_rfc822_parse_adrlist -- Parses an address string
imap_rfc822_parse_headers -- Parse mail headers from a string
imap_rfc822_write_address --  Returns a properly formatted email address given the mailbox, host, and personal info.
imap_scanmailbox --  Read the list of mailboxes, takes a string to search for in the text of the mailbox
imap_search --  This function returns an array of messages matching the given search criteria
imap_set_quota -- Sets a quota for a given mailbox
imap_setacl --  Sets the ACL for a giving mailbox
imap_setflag_full -- Sets flags on messages
imap_sort -- Sort an array of message headers
imap_status --  This function returns status information on a mailbox other than the current one
imap_subscribe -- Subscribe to a mailbox
imap_thread --  Return threaded by REFERENCES tree
imap_uid --  This function returns the UID for the given message sequence number
imap_undelete --  Unmark the message which is marked deleted
imap_unsubscribe -- Unsubscribe from a mailbox
imap_utf7_decode --  Decodes a modified UTF-7 encoded string.
imap_utf7_encode --  Converts 8bit data to modified UTF-7 text.
imap_utf8 --  Converts text to UTF8

imap_8bit

(PHP 3, PHP 4 )

imap_8bit --  Convert an 8bit string to a quoted-printable string

Description

string imap_8bit ( string string)

Convert an 8bit string to a quoted-printable string (according to RFC2045, section 6.7).

Returns a quoted-printable string.

See also imap_qprint().

imap_alerts

(PHP 3>= 3.0.12, PHP 4 )

imap_alerts --  This function returns all IMAP alert messages (if any) that have occurred during this page request or since the alert stack was reset

Description

array imap_alerts ( void)

This function returns an array of all of the IMAP alert messages generated since the last imap_alerts() call, or the beginning of the page. When imap_alerts() is called, the alert stack is subsequently cleared. The IMAP specification requires that these messages be passed to the user.

imap_append

(PHP 3, PHP 4 )

imap_append --  Append a string message to a specified mailbox

Description

bool imap_append ( resource imap_stream, string mbox, string message [, string options])

Returns TRUE on sucess, FALSE on error.

imap_append() appends a string message to the specified mailbox mbox. If the optional options is specified, writes the options to that mailbox also.

When talking to the Cyrus IMAP server, you must use "\r\n" as your end-of-line terminator instead of "\n" or the operation will fail.

Exemplo 1. imap_append() example

$stream = imap_open("{your.imap.host}INBOX.Drafts","username", "password");

$check = imap_check($stream);
print "Msg Count before append: ". $check->Nmsgs."\n";

imap_append($stream,"{your.imap.host}INBOX.Drafts"
                   ,"From: me@my.host\r\n"
                   ."To: you@your.host\r\n"
                   ."Subject: test\r\n"
                   ."\r\n"
                   ."this is a test message, please ignore\r\n"
                   );

$check = imap_check($stream);
print "Msg Count after append : ". $check->Nmsgs."\n";

imap_close($stream);

imap_base64

(PHP 3, PHP 4 )

imap_base64 -- Decode BASE64 encoded text

Description

string imap_base64 ( string text)

imap_base64() function decodes BASE-64 encoded text (see RFC2045, Section 6.8). The decoded message is returned as a string.

See also imap_binary().

imap_binary

(PHP 3>= 3.0.2, PHP 4 )

imap_binary --  Convert an 8bit string to a base64 string

Description

string imap_binary ( string string)

Convert an 8bit string to a base64 string (according to RFC2045, Section 6.8).

Returns a base64 string.

See also imap_base64().

imap_body

(PHP 3, PHP 4 )

imap_body -- Read the message body

Description

string imap_body ( resource imap_stream, int msg_number [, int options])

imap_body() returns the body of the message, numbered msg_number in the current mailbox. The optional flags are a bit mask with one or more of the following:

  • FT_UID - The msgno is a UID

  • FT_PEEK - Do not set the \Seen flag if not already set

  • FT_INTERNAL - The return string is in internal format, will not canonicalize to CRLF.

imap_body() will only return a verbatim copy of the message body. To extract single parts of a multipart MIME-encoded message you have to use imap_fetchstructure() to analyze its structure and imap_fetchbody() to extract a copy of a single body component.

imap_bodystruct

(PHP 3>= 3.0.4, PHP 4 )

imap_bodystruct --  Read the structure of a specified body section of a specific message

Description

object imap_bodystruct ( resource stream_id, int msg_no, int section)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

imap_check

(PHP 3, PHP 4 )

imap_check -- Check current mailbox

Description

object imap_check ( resource imap_stream)

Returns information about the current mailbox. Returns FALSE on failure.

The imap_check() function checks the current mailbox status on the server and returns the information in an object with following properties:

  • Date - last change of mailbox contents

  • Driver - protocol used to access this mailbox: POP3, IMAP, NNTP

  • Mailbox - the mailbox name

  • Nmsgs - number of messages in the mailbox

  • Recent - number of recent messages in the mailbox

imap_clearflag_full

(PHP 3>= 3.0.3, PHP 4 )

imap_clearflag_full -- Clears flags on messages

Description

bool imap_clearflag_full ( resource stream, string sequence, string flag, string options)

This function causes a store to delete the specified flag to the flags set for the messages in the specified sequence. The flags which you can unset are "\\Seen", "\\Answered", "\\Flagged", "\\Deleted", and "\\Draft" (as defined by RFC2060).

The options are a bit mask with one or more of the following:


ST_UID          The sequence argument contains UIDs instead of
                sequence numbers
      

imap_close

(PHP 3, PHP 4 )

imap_close -- Close an IMAP stream

Description

bool imap_close ( resource imap_stream [, int options])

Close the imap stream. Takes an optional flag CL_EXPUNGE, which will silently expunge the mailbox before closing, removing all messages marked for deletion.

imap_createmailbox

(PHP 3, PHP 4 )

imap_createmailbox -- Create a new mailbox

Description

bool imap_createmailbox ( resource imap_stream, string mbox)

imap_createmailbox() creates a new mailbox specified by mbox. Names containing international characters should be encoded by imap_utf7_encode()

Returns TRUE on success and FALSE on error.

See also imap_renamemailbox(), imap_deletemailbox() and imap_open() for the format of mbox names.

Exemplo 1. imap_createmailbox() example

$mbox = imap_open("{your.imap.host}","username","password",OP_HALFOPEN)
     or die("can't connect: ".imap_last_error());

$name1 = "phpnewbox";
$name2 = imap_utf7_encode("phpnewb&ouml;x");

$newname = $name1;

echo "Newname will be '$name1'<br>\n";

# we will now create a new mailbox "phptestbox" in your inbox folder,
# check its status after creation and finaly remove it to restore
# your inbox to its initial state 
if(@imap_createmailbox($mbox,imap_utf7_encode("{your.imap.host}INBOX.$newname"))) {
  $status = @imap_status($mbox,"{your.imap.host}INBOX.$newname",SA_ALL);
  if($status) {
    print("your new mailbox '$name1' has the following status:<br>\n");
    print("Messages:   ". $status->messages   )."<br>\n";
    print("Recent:     ". $status->recent     )."<br>\n";
    print("Unseen:     ". $status->unseen     )."<br>\n";
    print("UIDnext:    ". $status->uidnext    )."<br>\n";
    print("UIDvalidity:". $status->uidvalidity)."<br>\n";
    
    if(imap_renamemailbox($mbox,"{your.imap.host}INBOX.$newname","{your.imap.host}INBOX.$name2")) {
      echo "renamed new mailbox from '$name1' to '$name2'<br>\n";
      $newname=$name2;
    } else {
      print "imap_renamemailbox on new mailbox failed: ".imap_last_error()."<br>\n";
    }
  } else {
    print  "imap_status on new mailbox failed: ".imap_last_error()."<br>\n";
  }
  if(@imap_deletemailbox($mbox,"{your.imap.host}INBOX.$newname")) {
    print "new mailbox removed to restore initial state<br>\n";
  } else {
    print  "imap_deletemailbox on new mailbox failed: ".implode("<br>\n",imap_errors())."<br>\n";
  }
  
} else {
  print  "could not create new mailbox: ".implode("<br>\n",imap_errors())."<br>\n";
}

imap_close($mbox);

imap_delete

(PHP 3, PHP 4 )

imap_delete --  Mark a messge for deletion from current mailbox

Description

bool imap_delete ( int imap_stream, int msg_number [, int options])

Returns TRUE.

imap_delete() marks messages listed in msg_number for deletion. The optional flags parameter only has a single option, FT_UID, which tells the function to treat the msg_number argument as a UID. Messages marked for deletion will stay in the mailbox until either imap_expunge() is called or imap_close() is called with the optional parameter CL_EXPUNGE.

Nota: POP3 mailboxes do not have their message flags saved between connections, so imap_expunge() must be called during the same connection in order for messages marked for deletion to actually be purged.

Exemplo 1. imap_delete() Beispiel

$mbox = imap_open ("{your.imap.host}INBOX", "username", "password")
    or die ("can't connect: " . imap_last_error());

$check = imap_mailboxmsginfo ($mbox);
print "Messages before delete: " . $check->Nmsgs . "<br>\n" ;
imap_delete ($mbox, 1);
$check = imap_mailboxmsginfo ($mbox);
print "Messages after  delete: " . $check->Nmsgs . "<br>\n" ;
imap_expunge ($mbox);
$check = imap_mailboxmsginfo ($mbox);
print "Messages after expunge: " . $check->Nmsgs . "<br>\n" ;
imap_close ($mbox);

imap_deletemailbox

(PHP 3, PHP 4 )

imap_deletemailbox -- Delete a mailbox

Description

bool imap_deletemailbox ( resource imap_stream, string mbox)

imap_deletemailbox() deletes the specified mailbox (see imap_open() for the format of mbox names).

Returns TRUE on success and FALSE on error.

See also imap_createmailbox(), imap_renamemailbox(), and imap_open() for the format of mbox.

imap_errors

(PHP 3>= 3.0.12, PHP 4 )

imap_errors --  This function returns all of the IMAP errors (if any) that have occurred during this page request or since the error stack was reset.

Description

array imap_errors ( void)

This function returns an array of all of the IMAP error messages generated since the last imap_errors() call, or the beginning of the page. When imap_errors() is called, the error stack is subsequently cleared.

imap_expunge

(PHP 3, PHP 4 )

imap_expunge -- Delete all messages marked for deletion

Description

bool imap_expunge ( resource imap_stream)

imap_expunge() deletes all the messages marked for deletion by imap_delete(), imap_mail_move(), or imap_setflag_full().

Returns TRUE.

imap_fetch_overview

(PHP 3>= 3.0.4, PHP 4 )

imap_fetch_overview --  Read an overview of the information in the headers of the given message

Description

array imap_fetch_overview ( resource imap_stream, string sequence [, int options])

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 UIDs, if flags contains FT_UID. The returned value is an array of objects describing one message header each:

  • subject - the messages subject

  • from - who sent it

  • date - when was it sent

  • message_id - Message-ID

  • references - is a reference to this message id

  • size - size in bytes

  • uid - UID the message has in the mailbox

  • msgno - message sequence number in the maibox

  • recent - this message is flagged as recent

  • flagged - this message is flagged

  • answered - this message is flagged as answered

  • deleted - this message is flagged for deletion

  • seen - this message is flagged as already read

  • draft - this message is flagged as being a draft

Exemplo 1. imap_fetch_overview() example

$mbox = imap_open("{your.imap.host:143}","username","password")
     or die("can't connect: ".imap_last_error());
 
$overview = imap_fetch_overview($mbox,"2,4:6",0);
 
if(is_array($overview)) {
        reset($overview);
        while( list($key,$val) = each($overview)) {
                print     $val->msgno
                . " - " . $val->date
                . " - " . $val->subject
                . "\n";
        }
}
 
imap_close($mbox);

imap_fetchbody

(PHP 3, PHP 4 )

imap_fetchbody --  Fetch a particular section of the body of the message

Description

string imap_fetchbody ( resource imap_stream, int msg_number, string part_number [, flags options])

This function causes a fetch of a particular section of the body of the specified messages as a text string and returns that text string. The section specification is a string of integers delimited by period which index into a body part list as per the IMAP4 specification. Body parts are not decoded by this function.

The options for imap_fetchbody() is a bitmask with one or more of the following:

  • FT_UID - The msg_number is a UID

  • FT_PEEK - Do not set the \Seen flag if not already set

  • FT_INTERNAL - The return string is in "internal" format, without any attempt to canonicalize CRLF.

See also: imap_fetchstructure().

imap_fetchheader

(PHP 3>= 3.0.3, PHP 4 )

imap_fetchheader -- Returns header for a message

Description

string imap_fetchheader ( resource imap_stream, int msgno, int options)

This function causes a fetch of the complete, unfiltered RFC2822 format header of the specified message as a text string and returns that text string.

The options are:


FT_UID          The msgno argument is a UID 
FT_INTERNAL     The return string is in "internal" format,
                without any attempt to canonicalize to CRLF
                newlines
FT_PREFETCHTEXT The RFC822.TEXT should be pre-fetched at the
                same time.  This avoids an extra RTT on an
                IMAP connection if a full message text is
                desired (e.g. in a "save to local file"
                operation)
      

imap_fetchstructure

(PHP 3, PHP 4 )

imap_fetchstructure --  Read the structure of a particular message

Description

object imap_fetchstructure ( resource imap_stream, int msg_number [, int options])

This function fetches all the structured information for a given message. The optional flags parameter only has a single option, FT_UID, which tells the function to treat the msg_number argument as a UID. The returned object includes the envelope, internal date, size, flags and body structure along with a similar object for each mime attachement. The structure of the returned objects is as follows:

Tabela 1. Returned Objects for imap_fetchstructure()

type Primary body type
encoding Body transfer encoding
ifsubtype TRUE if there is a subtype string
subtype MIME subtype
ifdescription TRUE if there is a description string
description Content description string
ifid TRUE if there is an identification string
id Identification string
lines Number of lines
bytes Number of bytes
ifdisposition TRUE if there is a disposition string
disposition Disposition string
ifdparameters TRUE if the dparameters array exists
dparameters An array of objects where each object has an "attribute" and a "value" property corresponding to the parameters on the Content-disposition MIMEheader.
ifparameters TRUE if the parameters array exists
parameters An array of objects where each object has an "attribute" and a "value" property.
parts An array of objects identical in structure to the top-level object, each of which corresponds to a MIME body part.

Tabela 2. Primary body type

0 text
1 multipart
2 message
3 application
4 audio
5 image
6 video
7 other

Tabela 3. Transfer encodings

0 7BIT
1 8BIT
2 BINARY
3 BASE64
4 QUOTED-PRINTABLE
5 OTHER

See also: imap_fetchbody().

imap_get_quota

(PHP 4 >= 4.0.5)

imap_get_quota --  Retrieve the quota level settings, and usage statics per mailbox

Description

array imap_get_quota ( resource imap_stream, string quota_root)

Returns an array with integer values limit and usage for the given mailbox. The value of limit represents the total amount of space allowed for this mailbox. The usage value represents the mailboxes current level of capacity. Will return FALSE in the case of failure.

This function is currently only available to users of the c-client2000 or greater library.

NOTE: For this function to work, the mail stream is required to be opened as the mail-admin user. For a non-admin user version of this function, please see the imap_get_quotaroot() function of PHP.

imap_stream should be the value returned from an 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 user.name where name is the mailbox you wish to retrieve information about.

Exemplo 1. imap_get_quota() example

$mbox = imap_open("{your.imap.host}","mailadmin","password",OP_HALFOPEN)
      or die("can't connect: ".imap_last_error());
 
$quota_value = imap_get_quota($mbox, "user.kalowsky");
if(is_array($quota_value)) {
    print "Usage level is: " . $quota_value['usage'];
    print "Limit level is: " . $quota_value['limit'];
} 
 
imap_close($mbox);

As of PHP version 4.3, the function more properly reflects the functionality as dictated by the RFC 2087. The array return value has changed to support an unlimited number of returned resources (i.e. messages, or sub-folders) with each named resource receiving an individual array key. Each key value then contains an another array with the usage and limit values within it. The example below shows the updated returned output.

For backwards compatibility reasons, the originial access methods are still available for use, although it is suggested to update.

Exemplo 2. imap_get_quota() 4.3 or greater example

$mbox = imap_open("{your.imap.host}","mailadmin","password",OP_HALFOPEN)
      or die("can't connect: ".imap_last_error());
       
$quota_values = imap_get_quota($mbox, "user.kalowsky");
if(is_array($quota_values)) {
   $storage = $quota_values['STORAGE'];
   print "STORAGE usage level is: " .  $storage['usage'];
   print "STORAGE limit level is: " .  $storage['limit'];

   $message = $quota_values['MESSAGE']; 
   print "MESSAGE usage level is: " .  $message['usage'];
   print "MESSAGE usage level is: " .  $message['limit'];

   /* ...  */ 
} 

imap_close($mbox);

See also imap_open(), imap_set_quota(), imap_get_quotaroot().

imap_get_quotaroot

(PHP 4 >= 4.3.0)

imap_get_quotaroot --  Retrieve the quota settings per user

Description

array imap_get_quotaroot ( resource imap_stream, string quota_root)

Returns an array of integer values pertaining to the specified user mailbox. All values contain a key based upon the resource name, and a corresponding array with the usage and limit values within.

The limit value represents the total amount of space allowed for this user's total mailbox usage. The usage value represents the user's current total mailbox capacity. This function will return FALSE in the case of call failure, and an array of information about the connection upon an un-parsable response from the server.

This function is currently only available to users of the c-client2000 or greater library.

imap_stream should be the value returned from an imap_open() call. This stream should be opened as the user whose mailbox you wish to check. quota_root should normally be in the form of which mailbox (i.e. INBOX).

Exemplo 1. imap_get_quotaroot() example

$mbox = imap_open("{your.imap.host}","kalowsky","password",OP_HALFOPEN)
      or die("can't connect: ".imap_last_error());
 
$quota = imap_get_quotaroot($mbox, "INBOX");
if(is_array($quota)) {
   $storage = $quota_values['STORAGE'];
   print "STORAGE usage level is: " .  $storage['usage'];
   print "STORAGE limit level is: " .  $storage['limit'];

   $message = $quota_values['MESSAGE']; 
   print "MESSAGE usage level is: " .  $message['usage'];
   print "MESSAGE usage level is: " .  $message['limit'];

   /* ...  */ 

} 
 
imap_close($mbox);

See also imap_open(), imap_set_quota(), imap_get_quota().

imap_getmailboxes

(PHP 3>= 3.0.12, PHP 4 )

imap_getmailboxes --  Read the list of mailboxes, returning detailed information on each one

Description

array imap_getmailboxes ( resource imap_stream, string ref, string pattern)

Returns an array of objects containing mailbox information. Each object has the attributes name, specifying the full name of the mailbox; delimiter, which is the hierarchy delimiter for the part of the hierarchy this mailbox is in; and attributes. Attributes is a bitmask that can be tested against:

  • LATT_NOINFERIORS - This mailbox has no "children" (there are no mailboxes below this one).

  • LATT_NOSELECT - This is only a container, not a mailbox - you cannot open it.

  • LATT_MARKED - This mailbox is marked. Only used by UW-IMAPD.

  • LATT_UNMARKED - This mailbox is not marked. Only used by UW-IMAPD.

Mailbox names containing international Characters outside the printable ASCII range will be encoded and may be decoded by imap_utf7_decode().

ref should normally be just the server specification as described in imap_open(), and pattern specifies where in the mailbox hierarchy to start searching. If you want all mailboxes, pass '*' for pattern.

There are two special characters you can pass as part of the pattern: '*' and '%'. '*' means to return all mailboxes. If you pass pattern as '*', you will get a list of the entire mailbox hierarchy. '%' means to return the current level only. '%' as the pattern parameter will return only the top level mailboxes; '~/mail/%' on UW_IMAPD will return every mailbox in the ~/mail directory, but none in subfolders of that directory.

Exemplo 1. imap_getmailboxes() example

$mbox = imap_open("{your.imap.host}","username","password",OP_HALFOPEN)
      or die("can't connect: ".imap_last_error());
 
$list = imap_getmailboxes($mbox,"{your.imap.host}","*");
if(is_array($list)) {
  reset($list);
  while (list($key, $val) = each($list))
  {
    print "($key) ";
    print imap_utf7_decode($val->name).",";
    print "'".$val->delimiter."',";
    print $val->attributes."<br>\n";
  }
} else
  print "imap_getmailboxes failed: ".imap_last_error()."\n";
 
imap_close($mbox);

See also imap_getsubscribed().

imap_getsubscribed

(PHP 3>= 3.0.12, PHP 4 )

imap_getsubscribed -- List all the subscribed mailboxes

Description

array imap_getsubscribed ( resource imap_stream, string ref, string pattern)

This function is identical to imap_getmailboxes(), except that it only returns mailboxes that the user is subscribed to.

imap_header

(PHP 3, PHP 4 )

imap_header -- Read the header of the message

Description

object imap_header ( resource imap_stream, int msg_number [, int fromlength [, int subjectlength [, string defaulthost]]])

This function is an alias to imap_headerinfo() and is identical to it in every way.

imap_headerinfo

(PHP 3, PHP 4 )

imap_headerinfo -- Read the header of the message

Description

object imap_headerinfo ( resource imap_stream, int msg_number [, int fromlength [, int subjectlength [, string defaulthost]]])

This function returns an object of various header elements.


       remail, date, Date, subject, Subject, in_reply_to, message_id,
       newsgroups, followup_to, references

message flags:
   Recent -  'R' if recent and seen, 
             'N' if recent and not seen, 
             ' ' if not recent
   Unseen -  'U' if not seen AND not recent, 
             ' ' if seen OR not seen and recent
   Answered -'A' if answered, 
             ' ' if unanswered
   Deleted - 'D' if deleted, 
             ' ' if not deleted
   Draft -   'X' if draft, 
             ' ' if not draft
   Flagged - 'F' if flagged, 
             ' ' if not flagged

NOTE that the Recent/Unseen behavior is a little odd. If you want to
know if a message is Unseen, you must check for

Unseen == 'U' || Recent == 'N'

toaddress (full to: line, up to 1024 characters)

to[] (returns an array of objects from the To line, containing):
   personal
   adl
   mailbox
   host

fromaddress (full from: line, up to 1024 characters)

from[] (returns an array of objects from the From line, containing):
   personal
   adl
   mailbox
   host

ccaddress (full cc: line, up to 1024 characters)
cc[] (returns an array of objects from the Cc line, containing):
   personal
   adl
   mailbox
   host

bccaddress (full bcc line, up to 1024 characters)
bcc[] (returns an array of objects from the Bcc line, containing):
   personal
   adl
   mailbox
   host

reply_toaddress (full reply_to: line, up to 1024 characters)
reply_to[] (returns an array of objects from the Reply_to line,
containing):
   personal
   adl
   mailbox
   host

senderaddress (full sender: line, up to 1024 characters)
sender[] (returns an array of objects from the sender line, containing):
   personal
   adl
   mailbox
   host

return_path (full return-path: line, up to 1024 characters)
return_path[] (returns an array of objects from the return_path line,
containing):
   personal
   adl
   mailbox
   host

udate (mail message date in unix time)

fetchfrom (from line formatted to fit fromlength 
characters)

fetchsubject (subject line formatted to fit subjectlength characters)
      

imap_headers

(PHP 3, PHP 4 )

imap_headers --  Returns headers for all messages in a mailbox

Description

array imap_headers ( resource imap_stream)

Returns an array of string formatted with header info. One element per mail message.

imap_last_error

(PHP 3>= 3.0.12, PHP 4 )

imap_last_error --  This function returns the last IMAP error (if any) that occurred during this page request

Description

string imap_last_error ( void)

This function returns the full text of the last IMAP error message that occurred on the current page. The error stack is untouched; calling imap_last_error() subsequently, with no intervening errors, will return the same error.

imap_list

(PHP 3>= 3.0.4, PHP 4 )

imap_list -- Read the list of mailboxes

Description

array imap_list ( resource imap_stream, string ref, string pattern)

Returns an array containing the names of the mailboxes. See imap_getmailboxes() for a description of ref and pattern.

Exemplo 1. imap_list() example

$mbox = imap_open("{your.imap.host}","username","password",OP_HALFOPEN)
      or die("can't connect: ".imap_last_error());
 
$list = imap_list($mbox,"{your.imap.host}","*");
if(is_array($list)) {
  reset($list);
  while (list($key, $val) = each($list))
    print imap_utf7_decode($val)."<br>\n";
} else
  print "imap_list failed: ".imap_last_error()."\n";
 
imap_close($mbox);

imap_listmailbox

(PHP 3, PHP 4 )

imap_listmailbox -- Read the list of mailboxes

Description

array imap_listmailbox ( resource imap_stream, string ref, string pattern)

This function is an alias to imap_list() and is identical to it in every way.

imap_listscan

(no version information, might be only in CVS)

imap_listscan --  Read the list of mailboxes, takes a string to search for in the text of the mailbox

Description

array imap_listscan ( resource imap_stream, string ref, string pattern, string content)

Returns an array containing the names of the mailboxes that have content in the text of the mailbox. This function is similar to imap_listmailbox(), but it will additionally check for the presence of the string content inside the mailbox data. See imap_getmailboxes() for a description of ref and pattern.

imap_listsubscribed

(PHP 3, PHP 4 )

imap_listsubscribed -- List all the subscribed mailboxes

Description

array imap_listsubscribed ( resource imap_stream, string ref, string pattern)

This function is an alias to imap_lsub() and is identical to it in every way.

imap_lsub

(PHP 3>= 3.0.4, PHP 4 )

imap_lsub -- List all the subscribed mailboxes

Description

array imap_lsub ( resource imap_stream, string ref, string pattern)

Returns an array of all the mailboxes that you have subscribed. This is almost identical to imap_listmailbox(), but will only return mailboxes the user you logged in as has subscribed.

imap_mail_compose

(PHP 3>= 3.0.5, PHP 4 )

imap_mail_compose --  Create a MIME message based on given envelope and body sections

Description

string imap_mail_compose ( array envelope, array body)

Exemplo 1. imap_mail_compose() example

<?php

$envelope["from"]="musone@afterfive.com";
$envelope["to"]="musone@darkstar";
$envelope["cc"]="musone@edgeglobal.com";

$part1["type"]=TYPEMULTIPART;
$part1["subtype"]="mixed";

$filename="/tmp/imap.c.gz";
$fp=fopen($filename,"r");
$contents=fread($fp,filesize($filename));
fclose($fp);

$part2["type"]=TYPEAPPLICATION;
$part2["encoding"]=ENCBINARY;
$part2["subtype"]="octet-stream";
$part2["description"]=basename($filename);
$part2["contents.data"]=$contents;

$part3["type"]=TYPETEXT;
$part3["subtype"]="plain";
$part3["description"]="description3";
$part3["contents.data"]="contents.data3\n\n\n\t";

$body[1]=$part1;
$body[2]=$part2;
$body[3]=$part3;

echo nl2br(imap_mail_compose($envelope,$body));

?>

imap_mail_copy

(PHP 3, PHP 4 )

imap_mail_copy -- Copy specified messages to a mailbox

Description

bool imap_mail_copy ( resource imap_stream, string msglist, string mbox [, int options])

Returns TRUE on success and FALSE on error.

Copies mail messages specified by msglist to specified mailbox. msglist is a range not just message numbers (as described in RFC2060).

Flags is a bitmask of one or more of

  • CP_UID - the sequence numbers contain UIDS

  • CP_MOVE - Delete the messages from the current mailbox after copying

imap_mail_move

(PHP 3, PHP 4 )

imap_mail_move -- Move specified messages to a mailbox

Description

bool imap_mail_move ( resource imap_stream, string msglist, string mbox [, int options])

Returns TRUE on success and FALSE on error.

Moves mail messages specified by msglist to specified mailbox. msglist is a range not just message numbers (as described in RFC2060).

Flags is a bitmask and may contain the single option

  • CP_UID - the sequence numbers contain UIDS

imap_mail

(PHP 3>= 3.0.14, PHP 4 )

imap_mail --  Send an email message

Description

string imap_mail ( string to, string subject, string message [, string additional_headers [, string cc [, string bcc [, string rpath]]]])

This function allows sending of emails with correct handling of Cc and Bcc receivers. The parameters to, cc and bcc are all strings and are all parsed as rfc822 address lists. The receivers specified in bcc will get the 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.

imap_mailboxmsginfo

(PHP 3>= 3.0.2, PHP 4 )

imap_mailboxmsginfo -- Get information about the current mailbox

Description

object imap_mailboxmsginfo ( resource imap_stream)

Returns information about the current mailbox. Returns FALSE on failure.

The imap_mailboxmsginfo() function checks the current mailbox status on the server. It is similar to imap_status(), but will additionally sum up the size of all messages in the mailbox, which will take some additional time to execute. It returns the information in an object with following properties.

Tabela 1. Mailbox properties

Date date of last change
Driver driver
Mailbox name of the mailbox
Nmsgs number of messages
Recent number of recent messages
Unread number of unread messages
Deleted number of deleted messages
Size mailbox size

Exemplo 1. imap_mailboxmsginfo() example

<?php

$mbox = imap_open("{your.imap.host}INBOX","username", "password")
      or die("can't connect: ".imap_last_error());
 
$check = imap_mailboxmsginfo($mbox);
 
if($check) {
    print "Date: "    . $check->Date    ."<br>\n" ;
    print "Driver: "  . $check->Driver  ."<br>\n" ;
    print "Mailbox: " . $check->Mailbox ."<br>\n" ;
    print "Messages: ". $check->Nmsgs   ."<br>\n" ;
    print "Recent: "  . $check->Recent  ."<br>\n" ;
    print "Unread: "  . $check->Unread  ."<br>\n" ;
    print "Deleted: " . $check->Deleted ."<br>\n" ;
    print "Size: "    . $check->Size    ."<br>\n" ;
} else {
    print "imap_check() failed: ".imap_last_error(). "<br>\n";
}
 
imap_close($mbox);

?>

imap_mime_header_decode

(PHP 3>= 3.0.17, PHP 4 )

imap_mime_header_decode -- Decode MIME header elements

Description

array imap_mime_header_decode ( string text)

imap_mime_header_decode() function decodes MIME message header extensions that are non ASCII text (see 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, and in other words is in plain US-ASCII,the "charset" property of that element is set to "default".

Exemplo 1. imap_mime_header_decode() example

$text="=?ISO-8859-1?Q?Keld_J=F8rn_Simonsen?= <keld@dkuug.dk>";

$elements=imap_mime_header_decode($text);
for($i=0;$i<count($elements);$i++) {
    echo "Charset: {$elements[$i]->charset}\n";
    echo "Text: {$elements[$i]->text}\n\n";
}

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

imap_msgno

(PHP 3>= 3.0.3, PHP 4 )

imap_msgno --  This function returns the message sequence number for the given UID

Description

int imap_msgno ( resource imap_stream, int uid)

This function returns the message sequence number for the given UID. It is the inverse of imap_uid().

imap_num_msg

(PHP 3, PHP 4 )

imap_num_msg --  Gives the number of messages in the current mailbox

Description

int imap_num_msg ( resource imap_stream)

Return the number of messages in the current mailbox.

See also: imap_num_recent() and imap_status().

imap_num_recent

(PHP 3, PHP 4 )

imap_num_recent -- Gives the number of recent messages in current mailbox

Description

int imap_num_recent ( resource imap_stream)

Returns the number of recent messages in the current mailbox.

See also: imap_num_msg() and imap_status().

imap_open

(PHP 3, PHP 4 )

imap_open -- Open an IMAP stream to a mailbox

Description

resource imap_open ( string mailbox, string username, string password [, int options])

Returns an IMAP stream on success and FALSE on error. This function can also be used to open streams to POP3 and NNTP servers, but some functions and features are only available on IMAP servers.

A mailbox name consists of a server part and a mailbox path on this server. The special name INBOX stands for the current users personal mailbox. The server part, which is enclosed in '{' and '}', consists of the servers name or ip address, an optional port (prefixed by ':'), and an optional protocol specification (prefixed by '/'). The server part is mandatory in all mailbox parameters. Mailbox names that contain international characters besides those in the printable ASCII space have to be encoded with imap_utf7_encode().

The options are a bit mask with one or more of the following:

  • OP_READONLY - Open mailbox read-only

  • OP_ANONYMOUS - Dont use or update a .newsrc for news (NNTP only)

  • OP_HALFOPEN - For IMAP and NNTP names, open a connection but dont open a mailbox

  • CL_EXPUNGE - Expunge mailbox automatically upon mailbox close

To connect to an IMAP server running on port 143 on the local machine, do the following:

$mbox = imap_open ("{localhost:143}INBOX", "user_id", "password");

To connect to a POP3 server on port 110 on the local server, use:

$mbox = imap_open ("{localhost:110/pop3}INBOX", "user_id", "password");

To connect to an SSL IMAP or POP3 server, add /ssl after the protocol specification:

$mbox = imap_open ("{localhost:993/imap/ssl}INBOX", "user_id", "password");

To connect to an SSL IMAP or POP3 server with a self-signed certificate, add /ssl/novalidate-cert after the protocol specification:

$mbox = imap_open ("{localhost:995/pop3/ssl/novalidate-cert}", "user_id", "password");

To connect to an NNTP server on port 119 on the local server, use:

$nntp = imap_open ("{localhost:119/nntp}comp.test", "", "");

To connect to a remote server replace "localhost" with the name or the IP address of the server you want to connect to.

Exemplo 1. imap_open() example

$mbox = imap_open ("{your.imap.host:143}", "username", "password");

echo "<p><h1>Mailboxes</h1>\n";
$folders = imap_listmailbox ($mbox, "{your.imap.host:143}", "*");

if ($folders == false) {
    echo "Call failed<br>\n";
} else {
    while (list ($key, $val) = each ($folders)) {
        echo $val."<br>\n";
    }
}

echo "<p><h1>Headers in INBOX</h1>\n";
$headers = imap_headers ($mbox);

if ($headers == false) {
    echo "Call failed<br>\n";
} else {
    while (list ($key,$val) = each ($headers)) {
        echo $val."<br>\n";
    }
}

imap_close($mbox);

imap_ping

(PHP 3, PHP 4 )

imap_ping -- Check if the IMAP stream is still active

Description

bool imap_ping ( resource imap_stream)

Returns TRUE if the stream is still alive, FALSE otherwise.

imap_ping() function pings the stream to see it is still active. It may discover new mail; this is the preferred method for a periodic "new mail check" as well as a "keep alive" for servers which have inactivity timeout. (As PHP scripts do not tend to run that long, i can hardly imagine that this function will be usefull to anyone.)

imap_qprint

(PHP 3, PHP 4 )

imap_qprint -- Convert a quoted-printable string to an 8 bit string

Description

string imap_qprint ( string string)

Convert a quoted-printable string to an 8 bit string (according to RFC2045, section 6.7).

Returns an 8 bit (binary) string.

See also imap_8bit().

imap_renamemailbox

(PHP 3, PHP 4 )

imap_renamemailbox -- Rename an old mailbox to new mailbox

Description

bool imap_renamemailbox ( resource imap_stream, string old_mbox, string new_mbox)

This function renames on old mailbox to new mailbox (see imap_open() for the format of mbox names).

Returns TRUE on success and FALSE on error.

See also imap_createmailbox(), imap_deletemailbox(), and imap_open() for the format of mbox.

imap_reopen

(PHP 3, PHP 4 )

imap_reopen -- Reopen IMAP stream to new mailbox

Description

bool imap_reopen ( resource imap_stream, string mailbox [, string options])

This function reopens the specified stream to a new mailbox on an IMAP or NNTP server.

The options are a bit mask with one or more of the following:

  • OP_READONLY - Open mailbox read-only

  • OP_ANONYMOUS - Dont use or update a .newsrc for news (NNTP only)

  • OP_HALFOPEN - For IMAP and NNTP names, open a connection but dont open a mailbox.

  • CL_EXPUNGE - Expunge mailbox automatically upon mailbox close (see also imap_delete() and imap_expunge())

Returns TRUE on success and FALSE on error.

imap_rfc822_parse_adrlist

(PHP 3>= 3.0.2, PHP 4 )

imap_rfc822_parse_adrlist -- Parses an address string

Description

array imap_rfc822_parse_adrlist ( string address, string default_host)

This function parses the address string as defined in RFC2822 and for each address, returns an array of objects. The objects properties are:

  • mailbox - the mailbox name (username)

  • host - the host name

  • personal - the personal name

  • adl - at domain source route

Exemplo 1. imap_rfc822_parse_adrlist() example

$address_string = "Hartmut Holzgraefe <hartmut@cvs.php.net>, postmaster@somedomain.net, root";
$address_array  = imap_rfc822_parse_adrlist($address_string,"somedomain.net");
if(! is_array($address_array)) die("somethings wrong\n");
 
reset($address_array);
while(list($key,$val)=each($address_array)){
  print "mailbox : ".$val->mailbox."<br>\n";
  print "host    : ".$val->host."<br>\n";
  print "personal: ".$val->personal."<br>\n";
  print "adl     : ".$val->adl."<p>\n";
}

imap_rfc822_parse_headers

(PHP 4 )

imap_rfc822_parse_headers -- Parse mail headers from a string

Description

object imap_rfc822_parse_headers ( string headers [, string defaulthost])

This function returns an object of various header elements, similar to imap_header(), except without the flags and other elements that come from the IMAP server.

imap_rfc822_write_address

(PHP 3>= 3.0.2, PHP 4 )

imap_rfc822_write_address --  Returns a properly formatted email address given the mailbox, host, and personal info.

Description

string imap_rfc822_write_address ( string mailbox, string host, string personal)

Returns a properly formatted email address as defined in RFC2822 given the mailbox, host, and personal info.

Exemplo 1. imap_rfc822_write_address() example

print imap_rfc822_write_address("hartmut","cvs.php.net","Hartmut Holzgraefe")."\n";

imap_scanmailbox

(PHP 3, PHP 4 )

imap_scanmailbox --  Read the list of mailboxes, takes a string to search for in the text of the mailbox

Description

array imap_scanmailbox ( resource imap_stream, string ref, string pattern, string content)

This function is an alias to imap_listscan() and is identical to it in every way.

imap_search

(PHP 3>= 3.0.12, PHP 4 )

imap_search --  This function returns an array of messages matching the given search criteria

Description

array imap_search ( resource imap_stream, string criteria, int options)

This function performs a search on the mailbox currently opened in the given imap stream. criteria is a string, delimited by spaces, in which the following keywords are allowed. Any multi-word arguments (eg. FROM "joey smith") must be quoted.

  • ALL - return all messages matching the rest of the criteria

  • ANSWERED - match messages with the \\ANSWERED flag set

  • BCC "string" - match messages with "string" in the Bcc: field

  • BEFORE "date" - match messages with Date: before "date"

  • BODY "string" - match messages with "string" in the body of the message

  • CC "string" - match messages with "string" in the Cc: field

  • DELETED - match deleted messages

  • FLAGGED - match messages with the \\FLAGGED (sometimes referred to as Important or Urgent) flag set

  • FROM "string" - match messages with "string" in the From: field

  • KEYWORD "string" - match messages with "string" as a keyword

  • NEW - match new messages

  • OLD - match old messages

  • ON "date" - match messages with Date: matching "date"

  • RECENT - match messages with the \\RECENT flag set

  • SEEN - match messages that have been read (the \\SEEN flag is set)

  • SINCE "date" - match messages with Date: after "date"

  • SUBJECT "string" - match messages with "string" in the Subject:

  • TEXT "string" - match messages with text "string"

  • TO "string" - match messages with "string" in the To:

  • UNANSWERED - match messages that have not been answered

  • UNDELETED - match messages that are not deleted

  • UNFLAGGED - match messages that are not flagged

  • UNKEYWORD "string" - match messages that do not have the keyword "string"

  • UNSEEN - match messages which have not been read yet

For example, to match all unanswered messages sent by Mom, you'd use: "UNANSWERED FROM mom". Searches appear to be case insensitive. This list of criteria is from a reading of the UW c-client source code and may be uncomplete or inaccurate (see also RFC2060, section 6.4.4).

Valid values for flags are SE_UID, which causes the returned array to contain UIDs instead of messages sequence numbers.

imap_set_quota

(PHP 4 >= 4.0.5)

imap_set_quota -- Sets a quota for a given mailbox

Description

bool imap_set_quota ( resource imap_stream, string quota_root, int quota_limit)

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 opened as any other user.

This function is currently only available to users of the c-client2000 or greater library.

imap_stream is the stream pointer returned from a imap_open() call. This stream must be opened as the mail administrator, other wise this function will fail. quota_root is the mailbox to have a quota set. This should follow the IMAP standard format for a mailbox, 'user.name'. quota_limit is the maximum size (in KB) for the quota_root.

Returns TRUE on success and FALSE on error.

Exemplo 1. imap_set_quota() example

$mbox = imap_open ("{your.imap.host:143}", "mailadmin", "password");

if(!imap_set_quota($mbox, "user.kalowsky", 3000)) {
    print "Error in setting quota\n";
    return;
}

imap_close($mbox);

See also imap_open(), imap_set_quota().

imap_setacl

(PHP 4 >= 4.1.0)

imap_setacl --  Sets the ACL for a giving mailbox

Description

bool imap_setacl ( resource stream_id, string mailbox, string id, string rights)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

imap_setflag_full

(PHP 3>= 3.0.3, PHP 4 )

imap_setflag_full -- Sets flags on messages

Description

bool imap_setflag_full ( resource stream, string sequence, string flag, string options)

This function causes a store to add the specified flag to the flags set for the messages in the specified sequence.

The flags which you can set are "\\Seen", "\\Answered", "\\Flagged", "\\Deleted", and "\\Draft" (as defined by RFC2060).

The options are a bit mask with one or more of the following:


ST_UID          The sequence argument contains UIDs instead of
                sequence numbers
      

Exemplo 1. imap_setflag_full() example

$mbox = imap_open("{your.imap.host:143}","username","password")
     or die("can't connect: ".imap_last_error());
 
$status = imap_setflag_full($mbox,"2,5","\\Seen \\Flagged");
 
print gettype($status)."\n";
print $status."\n";
 
imap_close($mbox);

imap_sort

(PHP 3>= 3.0.3, PHP 4 )

imap_sort -- Sort an array of message headers

Description

array imap_sort ( resource stream, int criteria, int reverse [, int options [, string search_criteria]])

Returns an array of message numbers sorted by the given parameters.

Reverse is 1 for reverse-sorting.

Criteria can be one (and only one) of the following:


SORTDATE        message Date
SORTARRIVAL     arrival date
SORTFROM        mailbox in first From address
SORTSUBJECT     message Subject
SORTTO          mailbox in first To address 
SORTCC          mailbox in first cc address 
SORTSIZE        size of message in octets
      

The flags are a bitmask of one or more of the following:


SE_UID          Return UIDs instead of sequence numbers
SE_NOPREFETCH   Don't prefetch searched messages.
      

imap_status

(PHP 3>= 3.0.4, PHP 4 )

imap_status --  This function returns status information on a mailbox other than the current one

Description

object imap_status ( resource imap_stream, string mailbox, int options)

This function returns an object containing status information. Valid flags are:

  • SA_MESSAGES - set status->messages to the number of messages in the mailbox

  • SA_RECENT - set status->recent to the number of recent messages in the mailbox

  • SA_UNSEEN - set status->unseen to the number of unseen (new) messages in the mailbox

  • SA_UIDNEXT - set status->uidnext to the next uid to be used in the mailbox

  • SA_UIDVALIDITY - set status->uidvalidity to a constant that changes when uids for the mailbox may no longer be valid

  • SA_ALL - set all of the above

status->flags is also set, which contains a bitmask which can be checked against any of the above constants.

Exemplo 1. imap_status() example

$mbox = imap_open("{your.imap.host}","username","password",OP_HALFOPEN)
      or die("can't connect: ".imap_last_error());
 
$status = imap_status($mbox,"{your.imap.host}INBOX",SA_ALL);
if($status) {
  print("Messages:   ". $status->messages   )."<br>\n";
  print("Recent:     ". $status->recent     )."<br>\n";
  print("Unseen:     ". $status->unseen     )."<br>\n";
  print("UIDnext:    ". $status->uidnext    )."<br>\n";
  print("UIDvalidity:". $status->uidvalidity)."<br>\n"; 
} else
  print "imap_status failed: ".imap_last_error()."\n";
 
imap_close($mbox);

imap_subscribe

(PHP 3, PHP 4 )

imap_subscribe -- Subscribe to a mailbox

Description

bool imap_subscribe ( resource imap_stream, string mbox)

Subscribe to a new mailbox.

Returns TRUE on success and FALSE on error.

imap_thread

(PHP 4 >= 4.1.0)

imap_thread --  Return threaded by REFERENCES tree

Description

array imap_thread ( resource stream_id [, int options])

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

imap_uid

(PHP 3>= 3.0.3, PHP 4 )

imap_uid --  This function returns the UID for the given message sequence number

Description

int imap_uid ( resource imap_stream, int msgno)

This function returns the UID for the given message sequence number. An UID is an unique identifier that will not change over time while a message sequence number may change whenever the content of the mailbox changes. This function is the inverse of imap_msgno().

Nota: This is not supported by POP3 mailboxes.

imap_undelete

(PHP 3, PHP 4 )

imap_undelete --  Unmark the message which is marked deleted

Description

bool imap_undelete ( resource imap_stream, int msg_number)

This function removes the deletion flag for a specified message, which is set by imap_delete() or imap_mail_move().

Returns TRUE on success and FALSE on error.

imap_unsubscribe

(PHP 3, PHP 4 )

imap_unsubscribe -- Unsubscribe from a mailbox

Description

bool imap_unsubscribe ( string imap_stream, string mbox)

Unsubscribe from a specified mailbox.

Returns TRUE on success and FALSE on error.

imap_utf7_decode

(PHP 3>= 3.0.15, PHP 4 )

imap_utf7_decode --  Decodes a modified UTF-7 encoded string.

Description

string imap_utf7_decode ( string text)

Decodes modified UTF-7 text into 8bit data.

Returns the decoded 8bit data, or FALSE if the input string was not valid modified UTF-7. This function is needed to decode mailbox names that contain international 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).

imap_utf7_encode

(PHP 3>= 3.0.15, PHP 4 )

imap_utf7_encode --  Converts 8bit data to modified UTF-7 text.

Description

string imap_utf7_encode ( string data)

Converts 8bit data to modified UTF-7 text. This is needed to encode mailbox names that contain international 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).

Returns the modified UTF-7 text.

imap_utf8

(PHP 3>= 3.0.13, PHP 4 )

imap_utf8 --  Converts text to UTF8

Description

string imap_utf8 ( string text)

Converts the given text to UTF8 (as defined in RFC2044).

XLIII. Informix functions

Introdução

The Informix driver for Informix (IDS) 7.x, SE 7.x, Universal Server (IUS) 9.x and IDS 2000 is implemented in "ifx.ec" and "php3_ifx.h" in the informix extension directory. IDS 7.x support is fairly complete, with full support for BYTE and TEXT columns. IUS 9.x support is partly finished: the new data types are there, but SLOB and CLOB support is still under construction.


Requisitos

Configuration notes: You need a version of ESQL/C to compile the PHP Informix driver. ESQL/C versions from 7.2x on should be OK. ESQL/C is now part of the Informix Client SDK.

Make sure that the "INFORMIXDIR" variable has been set, and that $INFORMIXDIR/bin is in your PATH before you run the "configure" script.


Instalação

To be able to use the functions defined in this module you must compile your PHP interpreter using the configure line --with_informix[=DIR], where DIR is the Informix base install directory, defaults to nothing.


Configuração durante execução

O comportamento dessas funções podem ser modificado pelas configurações do php.ini.

Nota: Make sure that the Informix environment variables INFORMIXDIR and INFORMIXSERVER are available to the PHP ifx driver, and that the INFORMIX bin directory is in the PATH. Check this by running a script that contains a call to phpinfo() before you start testing. The phpinfo() output should list these environment variables. This is TRUE for both CGI php and Apache mod_php. You may have to set these environment variables in your Apache startup script.

The Informix shared libraries should also be available to the loader (check LD_LIBRARY_PATH or ld.so.conf/ldconfig).

Some notes on the use of BLOBs (TEXT and BYTE columns): BLOBs are normally addressed by BLOB identifiers. Select queries return a "blob id" for every BYTE and TEXT column. You can get at the contents with "string_var = ifx_get_blob($blob_id);" if you choose to get the BLOBs in memory (with : "ifx_blobinfile(0);"). If you prefer to receive the content of BLOB columns in a file, use "ifx_blobinfile(1);", and "ifx_get_blob($blob_id);" will get you the filename. Use normal file I/O to get at the blob contents.

For insert/update queries you must create these "blob id's" yourself with "ifx_create_blob();". You then plug the blob id's into an array, and replace the blob columns with a question mark (?) in the query string. For updates/inserts, you are responsible for setting the blob contents with ifx_update_blob().

The behaviour of BLOB columns can be altered by configuration variables that also can be set at runtime :

configuration variable : ifx.textasvarchar

configuration variable : ifx.byteasvarchar

runtime functions :

ifx_textasvarchar(0) : use blob id's for select queries with TEXT columns

ifx_byteasvarchar(0) : use blob id's for select queries with BYTE columns

ifx_textasvarchar(1) : return TEXT columns as if they were VARCHAR columns, so that you don't need to use blob id's for select queries.

ifx_byteasvarchar(1) : return BYTE columns as if they were VARCHAR columns, so that you don't need to use blob id's for select queries.

configuration variable : ifx.blobinfile

runtime function :

ifx_blobinfile_mode(0) : return BYTE columns in memory, the blob id lets you get at the contents.

ifx_blobinfile_mode(1) : return BYTE columns in a file, the blob id lets you get at the file name.

If you set ifx_text/byteasvarchar to 1, you can use TEXT and BYTE columns in select queries just like normal (but rather long) VARCHAR fields. Since all strings are "counted" in PHP, this remains "binary safe". It is up to you to handle this correctly. The returned data can contain anything, you are responsible for the contents.

If you set ifx_blobinfile to 1, use the file name returned by ifx_get_blob(..) to get at the blob contents. Note that in this case YOU ARE RESPONSIBLE FOR DELETING THE TEMPORARY FILES CREATED BY INFORMIX when fetching the row. Every new row fetched will create new temporary files for every BYTE column.

The location of the temporary files can be influenced by the environment variable "blobdir", default is "." (the current directory). Something like : putenv(blobdir=tmpblob"); will ease the cleaning up of temp files accidentally left behind (their names all start with "blb").

Automatically trimming "char" (SQLCHAR and SQLNCHAR) data: This can be set with the configuration variable

ifx.charasvarchar : if set to 1 trailing spaces will be automatically trimmed, to save you some "chopping".

NULL values: The configuration variable ifx.nullformat (and the runtime function ifx_nullformat()) when set to TRUE will return NULL columns as the string "NULL", when set to FALSE they return the empty string. This allows you to discriminate between NULL columns and empty columns.

Tabela 1. Informix configuration options

Name Default Changeable
ifx.allow_persistent "1" PHP_INI_SYSTEM
ifx.max_persistent "-1" PHP_INI_SYSTEM
ifx.max_links "-1" PHP_INI_SYSTEM
ifx.default_host NULL PHP_INI_SYSTEM
ifx.default_user NULL PHP_INI_SYSTEM
ifx.default_password NULL PHP_INI_SYSTEM
ifx.blobinfile "1" PHP_INI_ALL
ifx.textasvarchar "0" PHP_INI_ALL
ifx.byteasvarchar "0" PHP_INI_ALL
ifx.charasvarchar "0" PHP_INI_ALL
ifx.nullformat "0" PHP_INI_ALL
For further details and definition of the PHP_INI_* constants see ini_set().

Here is a short explanation of the configuration directives.

ifx.allow_persistent boolean

Whether to allow persistent Informix connections.

ifx.max_persistent integer

The maximum number of persistent Informix connections per process.

ifx.max_links integer

The maximum number of Informix connections per process, including persistent connections.

ifx.default_host string

The default host to connect to when no host is specified in ifx_connect() or ifx_pconnect(). Doesn't apply in safe mode.

ifx.default_user string

The default user id to use when none is specified in ifx_connect() or ifx_pconnect(). Doesn't apply in safe mode.

ifx.default_password string

The default password to use when none is specified in ifx_connect() or ifx_pconnect(). Doesn't apply in safe mode.

ifx.blobinfile boolean

Set to TRUE if you want to return blob columns in a file, FALSE if you want them in memory. You can override the setting at runtime with ifx_blobinfile_mode().

ifx.textasvarchar boolean

Set to TRUE if you want to return TEXT columns as normal strings in select statements, FALSE if you want to use blob id parameters. You can override the setting at runtime with ifx_textasvarchar().

ifx.byteasvarchar boolean

Set to TRUE if you want to return BYTE columns as normal strings in select queries, FALSE if you want to use blob id parameters. You can override the setting at runtime with ifx_textasvarchar().

ifx.charasvarchar boolean

Set to TRUE if you want to trim trailing spaces from CHAR columns when fetching them.

ifx.nullformat boolean

Set to TRUE if you want to return NULL columns as the literal string "NULL", FALSE if you want them returned as the empty string "". You can override this setting at runtime with ifx_nullformat().


Tipos Resource


Constantes Predefinidas

Esta extensão não possui nenhuma constante.

Índice
ifx_affected_rows -- Get number of rows affected by a query
ifx_blobinfile_mode -- Set the default blob mode for all select queries
ifx_byteasvarchar -- Set the default byte mode
ifx_close -- Close Informix connection
ifx_connect -- Open Informix server connection
ifx_copy_blob -- Duplicates the given blob object
ifx_create_blob -- Creates an blob object
ifx_create_char -- Creates an char object
ifx_do --  Execute a previously prepared SQL-statement
ifx_error -- Returns error code of last Informix call
ifx_errormsg -- Returns error message of last Informix call
ifx_fetch_row -- Get row as enumerated array
ifx_fieldproperties -- List of SQL fieldproperties
ifx_fieldtypes -- List of Informix SQL fields
ifx_free_blob -- Deletes the blob object
ifx_free_char -- Deletes the char object
ifx_free_result -- Releases resources for the query
ifx_get_blob -- Return the content of a blob object
ifx_get_char -- Return the content of the char object
ifx_getsqlca --  Get the contents of sqlca.sqlerrd[0..5] after a query
ifx_htmltbl_result --  Formats all rows of a query into a HTML table
ifx_nullformat --  Sets the default return value on a fetch row
ifx_num_fields -- Returns the number of columns in the query
ifx_num_rows -- Count the rows already fetched from a query
ifx_pconnect -- Open persistent Informix connection
ifx_prepare -- Prepare an SQL-statement for execution
ifx_query -- Send Informix query
ifx_textasvarchar -- Set the default text mode
ifx_update_blob -- Updates the content of the blob object
ifx_update_char -- Updates the content of the char object
ifxus_close_slob -- Deletes the slob object
ifxus_create_slob -- Creates an slob object and opens it
ifxus_free_slob -- Deletes the slob object
ifxus_open_slob -- Opens an slob object
ifxus_read_slob -- Reads nbytes of the slob object
ifxus_seek_slob -- Sets the current file or seek position
ifxus_tell_slob -- Returns the current file or seek position
ifxus_write_slob -- Writes a string into the slob object

ifx_affected_rows

(PHP 3>= 3.0.3, PHP 4 )

ifx_affected_rows -- Get number of rows affected by a query

Description

int ifx_affected_rows ( int result_id)

result_id is a valid result id returned by ifx_query() or ifx_prepare().

Returns the number of rows affected by a query associated with result_id.

For inserts, updates and deletes the number is the real number (sqlerrd[2]) of affected rows. For selects it is an estimate (sqlerrd[0]). Don't rely on it. The database server can never return the actual number of rows that will be returned by a SELECT because it has not even begun fetching them at this stage (just after the "PREPARE" when the optimizer has determined the query plan).

Useful after ifx_prepare() to limit queries to reasonable result sets.

See also: ifx_num_rows()

Exemplo 1. Informix affected rows

$rid = ifx_prepare ("select * from emp 
                     where name like " . $name, $connid);
if (! $rid) {
    ... error ...
}
$rowcount = ifx_affected_rows ($rid);
if ($rowcount > 1000) {
    printf ("Too many rows in result set (%d)\n<br>", $rowcount);
    die ("Please restrict your query<br>\n");
}

ifx_blobinfile_mode

(PHP 3>= 3.0.4, PHP 4 )

ifx_blobinfile_mode -- Set the default blob mode for all select queries

Description

void ifx_blobinfile_mode ( int mode)

Set the default blob mode for all select queries. Mode "0" means save Byte-Blobs in memory, and mode "1" means save Byte-Blobs in a file.

ifx_byteasvarchar

(PHP 3>= 3.0.4, PHP 4 )

ifx_byteasvarchar -- Set the default byte mode

Description

void ifx_byteasvarchar ( int mode)

Sets the default byte mode for all select-queries. Mode "0" will return a blob id, and mode "1" will return a varchar with text content.

ifx_close

(PHP 3>= 3.0.3, PHP 4 )

ifx_close -- Close Informix connection

Description

int ifx_close ( [int link_identifier])

Returns: always TRUE.

ifx_close() closes the link to an Informix database that's associated with the specified link identifier. If the link identifier isn't specified, the last opened link is assumed.

Note that this isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution.

ifx_close() will not close persistent links generated by ifx_pconnect().

See also: ifx_connect(), and ifx_pconnect().

Exemplo 1. Closing a Informix connection

$conn_id = ifx_connect ("mydb@ol_srv", "itsme", "mypassword");
... some queries and stuff ...
ifx_close($conn_id);

ifx_connect

(PHP 3>= 3.0.3, PHP 4 )

ifx_connect -- Open Informix server connection

Description

int ifx_connect ( [string database [, string userid [, string password]]])

Returns a connection identifier on success, or FALSE on error.

ifx_connect() establishes a connection to an Informix server. All of the arguments are optional, and if they're missing, defaults are taken from values supplied in configuration file (ifx.default_host for the host (Informix libraries will use INFORMIXSERVER environment value if not defined), ifx.default_user for user, ifx.default_password for the password (none if not defined).

In case a second call is made to ifx_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned.

The link to the server will be closed as soon as the execution of the script ends, unless it's closed earlier by explicitly calling ifx_close().

See also ifx_pconnect(), and ifx_close().

Exemplo 1. Connect to a Informix database

$conn_id = ifx_connect ("mydb@ol_srv1", "imyself", "mypassword");

ifx_copy_blob

(PHP 3>= 3.0.4, PHP 4 )

ifx_copy_blob -- Duplicates the given blob object

Description

int ifx_copy_blob ( int bid)

Duplicates the given blob object. bid is the ID of the blob object.

Returns FALSE on error otherwise the new blob object-id.

ifx_create_blob

(PHP 3>= 3.0.4, PHP 4 )

ifx_create_blob -- Creates an blob object

Description

int ifx_create_blob ( int type, int mode, string param)

Creates an blob object.

type: 1 = TEXT, 0 = BYTE

mode: 0 = blob-object holds the content in memory, 1 = blob-object holds the content in file.

param: if mode = 0: pointer to the content, if mode = 1: pointer to the filestring.

Return FALSE on error, otherwise the new blob object-id.

ifx_create_char

(PHP 3>= 3.0.6, PHP 4 )

ifx_create_char -- Creates an char object

Description

int ifx_create_char ( string param)

Creates an char object. param should be the char content.

ifx_do

(PHP 3>= 3.0.4, PHP 4 )

ifx_do --  Execute a previously prepared SQL-statement

Description

int ifx_do ( int result_id)

Retorna TRUE em caso de sucesso ou FALSE em falhas.

Executes a previously prepared query or opens a cursor for it.

Does NOT free result_id on error.

Also sets the real number of ifx_affected_rows() for non-select statements for retrieval by ifx_affected_rows()

See also: ifx_prepare().

ifx_error

(PHP 3>= 3.0.3, PHP 4 )

ifx_error -- Returns error code of last Informix call

Description

string ifx_error ( void)

The Informix error codes (SQLSTATE & SQLCODE) formatted as follows :

x [SQLSTATE = aa bbb SQLCODE=cccc]

where x = space : no error

E : error

N : no more data

W : warning

? : undefined

If the "x" character is anything other than space, SQLSTATE and SQLCODE describe the error in more detail.

See the Informix manual for the description of SQLSTATE and SQLCODE

Returns in a string one character describing the general results of a statement and both SQLSTATE and SQLCODE associated with the most recent SQL statement executed. The format of the string is "(char) [SQLSTATE=(two digits) (three digits) SQLCODE=(one digit)]". The first character can be ' ' (space) (success), 'W' (the statement caused some warning), 'E' (an error happened when executing the statement) or 'N' (the statement didn't return any data).

See also: ifx_errormsg()

ifx_errormsg

(PHP 3>= 3.0.4, PHP 4 )

ifx_errormsg -- Returns error message of last Informix call

Description

string ifx_errormsg ( [int errorcode])

Returns the Informix error message associated with the most recent Informix error, or, when the optional "errorcode" param is present, the error message corresponding to "errorcode".

See also: ifx_error()

printf("%s\n&lt;br>", ifx_errormsg(-201));

ifx_fetch_row

(PHP 3>= 3.0.3, PHP 4 )

ifx_fetch_row -- Get row as enumerated array

Description

array ifx_fetch_row ( int result_id [, mixed position])

Returns an associative array that corresponds to the fetched row, or FALSE if there are no more rows.

Blob columns are returned as integer blob id values for use in ifx_get_blob() unless you have used ifx_textasvarchar(1) or ifx_byteasvarchar(1), in which case blobs are returned as string values. Returns FALSE on error

result_id is a valid resultid returned by ifx_query() or ifx_prepare() (select type queries only!).

position is an optional parameter for a "fetch" operation on "scroll" cursors: "NEXT", "PREVIOUS", "CURRENT", "FIRST", "LAST" or a number. If you specify a number, an "absolute" row fetch is executed. This parameter is optional, and only valid for SCROLL cursors.

ifx_fetch_row() fetches one row of data from the result associated with the specified result identifier. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0, with the column name as key.

Subsequent calls to ifx_fetch_row() would return the next row in the result set, or FALSE if there are no more rows.

Exemplo 1. Informix fetch rows

$rid = ifx_prepare ("select * from emp where name like " . $name,
                     $connid, IFX_SCROLL);
if (! $rid) {
    ... error ...
}
$rowcount = ifx_affected_rows($rid);
if ($rowcount > 1000) {
    printf ("Too many rows in result set (%d)\n<br>", $rowcount);
    die ("Please restrict your query<br>\n");
}
if (! ifx_do ($rid)) {
   ... error ...
}
$row = ifx_fetch_row ($rid, "NEXT");
while (is_array($row)) {
    for(reset($row); $fieldname=key($row); next($row)) {
        $fieldvalue = $row[$fieldname];
        printf ("%s = %s,", $fieldname, $fieldvalue);
    }
    printf("\n<br>");
    $row = ifx_fetch_row ($rid, "NEXT");
}
ifx_free_result ($rid);

ifx_fieldproperties

(PHP 3>= 3.0.3, PHP 4 )

ifx_fieldproperties -- List of SQL fieldproperties

Description

array ifx_fieldproperties ( int result_id)

Returns an associative array with fieldnames as key and the SQL fieldproperties as data for a query with result_id. Returns FALSE on error.

Returns the Informix SQL fieldproperties of every field in the query as an associative array. Properties are encoded as: "SQLTYPE;length;precision;scale;ISNULLABLE" where SQLTYPE = the Informix type like "SQLVCHAR" etc. and ISNULLABLE = "Y" or "N".

Exemplo 1. Informix SQL fieldproperties

$properties = ifx_fieldproperties ($resultid);
if (! isset($properties)) {
  ... error ...
}
for ($i = 0; $i < count($properties); $i++) {
    $fname = key ($properties);
    printf ("%s:\t type =  %s\n", $fname, $properties[$fname]);
    next ($properties);
}

ifx_fieldtypes

(PHP 3>= 3.0.3, PHP 4 )

ifx_fieldtypes -- List of Informix SQL fields

Description

array ifx_fieldtypes ( int result_id)

Returns an associative array with fieldnames as key and the SQL fieldtypes as data for query with result_id. Returns FALSE on error.

Exemplo 1. Fieldnames and SQL fieldtypes

$types = ifx_fieldtypes ($resultid);
if (! isset ($types)) {
  ... error ...
}
for ($i = 0; $i < count($types); $i++) {
    $fname = key($types);
    printf("%s :\t type =  %s\n", $fname, $types[$fname]);
    next($types);
}

ifx_free_blob

(PHP 3>= 3.0.4, PHP 4 )

ifx_free_blob -- Deletes the blob object

Description

int ifx_free_blob ( int bid)

Deletes the blobobject for the given blob object-id bid. Retorna TRUE em caso de sucesso ou FALSE em falhas.

ifx_free_char

(PHP 3>= 3.0.6, PHP 4 )

ifx_free_char -- Deletes the char object

Description

int ifx_free_char ( int bid)

Deletes the charobject for the given char object-id bid. Retorna TRUE em caso de sucesso ou FALSE em falhas.

ifx_free_result

(PHP 3>= 3.0.3, PHP 4 )

ifx_free_result -- Releases resources for the query

Description

int ifx_free_result ( int result_id)

Releases resources for the query associated with result_id. Returns FALSE on error.

ifx_get_blob

(PHP 3>= 3.0.4, PHP 4 )

ifx_get_blob -- Return the content of a blob object

Description

int ifx_get_blob ( int bid)

Returns the content of the blob object for the given blob object-id bid.

ifx_get_char

(PHP 3>= 3.0.6, PHP 4 )

ifx_get_char -- Return the content of the char object

Description

int ifx_get_char ( int bid)

Returns the content of the char object for the given char object-id bid.

ifx_getsqlca

(PHP 3>= 3.0.8, PHP 4 )

ifx_getsqlca --  Get the contents of sqlca.sqlerrd[0..5] after a query

Description

array ifx_getsqlca ( int result_id)

result_id is a valid result id returned by ifx_query() or ifx_prepare().

Returns a pseudo-row (associative array) with sqlca.sqlerrd[0] ... sqlca.sqlerrd[5] after the query associated with result_id.

For inserts, updates and deletes the values returned are those as set by the server after executing the query. This gives access to the number of affected rows and the serial insert value. For SELECTs the values are those saved after the PREPARE statement. This gives access to the *estimated* number of affected rows. The use of this function saves the overhead of executing a "select dbinfo('sqlca.sqlerrdx')" query, as it retrieves the values that were saved by the ifx driver at the appropriate moment.

Exemplo 1. Retrieve Informix sqlca.sqlerrd[x] values

/* assume the first column of 'sometable' is a serial */
$qid = ifx_query("insert into sometable 
                  values (0, '2nd column', 'another column') ", $connid);
if (! $qid) {
    ... error ...
}
$sqlca = ifx_getsqlca ($qid);
$serial_value = $sqlca["sqlerrd1"];
echo "The serial value of the inserted row is : " . $serial_value<br>\n";

ifx_htmltbl_result

(PHP 3>= 3.0.3, PHP 4 )

ifx_htmltbl_result --  Formats all rows of a query into a HTML table

Description

int ifx_htmltbl_result ( int result_id [, string html_table_options])

Returns the number of rows fetched or FALSE on error.

Formats all rows of the result_id query into a html table. The optional second argument is a string of <table> tag options

Exemplo 1. Informix results as HTML table

$rid = ifx_prepare ("select * from emp where name like " . $name,
                     $connid, IFX_SCROLL);
if (! $rid) {
   ... error ...
}
$rowcount = ifx_affected_rows ($rid);
if ($rowcount > 1000) {
    printf ("Too many rows in result set (%d)\n<br>", $rowcount);
    die ("Please restrict your query<br>\n");
}
if (! ifx_do($rid) {
  ... error ...
}

ifx_htmltbl_result ($rid, "border=\"2\"");

ifx_free_result($rid);

ifx_nullformat

(PHP 3>= 3.0.4, PHP 4 )

ifx_nullformat --  Sets the default return value on a fetch row

Description

void ifx_nullformat ( int mode)

Sets the default return value of a NULL-value on a fetch row. Mode "0" returns "", and mode "1" returns "NULL".

ifx_num_fields

(PHP 3>= 3.0.3, PHP 4 )

ifx_num_fields -- Returns the number of columns in the query

Description

int ifx_num_fields ( int result_id)

Returns the number of columns in query for result_id or FALSE on error

After preparing or executing a query, this call gives you the number of columns in the query.

ifx_num_rows

(PHP 3>= 3.0.3, PHP 4 )

ifx_num_rows -- Count the rows already fetched from a query

Description

int ifx_num_rows ( int result_id)

Gives the number of rows fetched so far for a query with result_id after a ifx_query() or ifx_do() query.

ifx_pconnect

(PHP 3>= 3.0.3, PHP 4 )

ifx_pconnect -- Open persistent Informix connection

Description

int ifx_pconnect ( [string database [, string userid [, string password]]])

Returns: A positive Informix persistent link identifier on success, or FALSE on error

ifx_pconnect() acts very much like ifx_connect() with two major differences.

This function behaves exactly like ifx_connect() when PHP is not running as an Apache module. First, when connecting, the function would first try to find a (persistent) link that's already open with the same host, username and password. If one is found, an identifier for it will be returned instead of opening a new connection.

Second, the connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (ifx_close() will not close links established by ifx_pconnect()).

This type of links is therefore called 'persistent'.

See also: ifx_connect().

ifx_prepare

(PHP 3>= 3.0.4, PHP 4 )

ifx_prepare -- Prepare an SQL-statement for execution

Description

int ifx_prepare ( string query, int conn_id [, int cursor_def, mixed blobidarray])

Returns a integer result_id for use by ifx_do(). Sets affected_rows for retrieval by the ifx_affected_rows() function.

Prepares query on connection conn_id. For "select-type" queries a cursor is declared and opened. The optional cursor_type parameter allows you to make this a "scroll" and/or "hold" cursor. It's a bitmask and can be either IFX_SCROLL, IFX_HOLD, or both or'ed together.

For either query type the estimated number of affected rows is saved for retrieval by ifx_affected_rows().

If you have BLOB (BYTE or TEXT) columns in the query, you can add a blobidarray parameter containing the corresponding "blob ids", and you should replace those columns with a "?" in the query text.

If the contents of the TEXT (or BYTE) column allow it, you can also use "ifx_textasvarchar(1)" and "ifx_byteasvarchar(1)". This allows you to treat TEXT (or BYTE) columns just as if they were ordinary (but long) VARCHAR columns for select queries, and you don't need to bother with blob id's.

With ifx_textasvarchar(0) or ifx_byteasvarchar(0) (the default situation), select queries will return BLOB columns as blob id's (integer value). You can get the value of the blob as a string or file with the blob functions (see below).

See also: ifx_do().

ifx_query

(PHP 3>= 3.0.3, PHP 4 )

ifx_query -- Send Informix query

Description

int ifx_query ( string query, int link_identifier [, int cursor_type [, mixed blobidarray]])

Returns: A positive Informix result identifier on success, or FALSE on error.

A "result_id" resource used by other functions to retrieve the query results. Sets "affected_rows" for retrieval by the ifx_affected_rows() function.

ifx_query() sends a query to the currently active database on the server that's associated with the specified link identifier.

Executes query on connection conn_id. For "select-type" queries a cursor is declared and opened. The optional cursor_type parameter allows you to make this a "scroll" and/or "hold" cursor. It's a bitmask and can be either IFX_SCROLL, IFX_HOLD, or both or'ed together. Non-select queries are "execute immediate". IFX_SCROLL and IFX_HOLD are symbolic constants and as such shouldn't be between quotes. I you omit this parameter the cursor is a normal sequential cursor.

For either query type the number of (estimated or real) affected rows is saved for retrieval by ifx_affected_rows().

If you have BLOB (BYTE or TEXT) columns in an update query, you can add a blobidarray parameter containing the corresponding "blob ids", and you should replace those columns with a "?" in the query text.

If the contents of the TEXT (or BYTE) column allow it, you can also use "ifx_textasvarchar(1)" and "ifx_byteasvarchar(1)". This allows you to treat TEXT (or BYTE) columns just as if they were ordinary (but long) VARCHAR columns for select queries, and you don't need to bother with blob id's.

With ifx_textasvarchar(0) or ifx_byteasvarchar(0) (the default situation), select queries will return BLOB columns as blob id's (integer value). You can get the value of the blob as a string or file with the blob functions (see below).

See also: ifx_connect().

Exemplo 1. Show all rows of the "orders" table as a html table

ifx_textasvarchar(1);      // use "text mode" for blobs
$res_id = ifx_query("select * from orders", $conn_id);
if (! $res_id) {
    printf("Can't select orders : %s\n<br>%s<br>\n", ifx_error());
    ifx_errormsg();
    die;
}
ifx_htmltbl_result($res_id, "border=\"1\"");
ifx_free_result($res_id);

Exemplo 2. Insert some values into the "catalog" table

// create blob id's for a byte and text column
$textid = ifx_create_blob(0, 0, "Text column in memory");
$byteid = ifx_create_blob(1, 0, "Byte column in memory");
                      // store blob id's in a blobid array
$blobidarray[] = $textid;
$blobidarray[] = $byteid;
                      // launch query
$query = "insert into catalog (stock_num, manu_code, " .
         "cat_descr,cat_picture) values(1,'HRO',?,?)";
$res_id = ifx_query($query, $conn_id, $blobidarray);
if (! $res_id) {
  ... error ...
}
                     // free result id
ifx_free_result($res_id);

ifx_textasvarchar

(PHP 3>= 3.0.4, PHP 4 )

ifx_textasvarchar -- Set the default text mode

Description

void ifx_textasvarchar ( int mode)

Sets the default text mode for all select-queries. Mode "0" will return a blob id, and mode "1" will return a varchar with text content.

ifx_update_blob

(PHP 3>= 3.0.4, PHP 4 )

ifx_update_blob -- Updates the content of the blob object

Description

ifx_update_blob ( int bid, string content)

Updates the content of the blob object for the given blob object bid. content is a string with new data. Retorna TRUE em caso de sucesso ou FALSE em falhas.

ifx_update_char

(PHP 3>= 3.0.6, PHP 4 )

ifx_update_char -- Updates the content of the char object

Description

int ifx_update_char ( int bid, string content)

Updates the content of the char object for the given char object bid. content is a string with new data. Retorna TRUE em caso de sucesso ou FALSE em falhas.

ifxus_close_slob

(PHP 3>= 3.0.4, PHP 4 )

ifxus_close_slob -- Deletes the slob object

Description

int ifxus_close_slob ( int bid)

Deletes the slob object on the given slob object-id bid. Retorna TRUE em caso de sucesso ou FALSE em falhas.

ifxus_create_slob

(PHP 3>= 3.0.4, PHP 4 )

ifxus_create_slob -- Creates an slob object and opens it

Description

int ifxus_create_slob ( int mode)

Creates an slob object and opens it. Modes: 1 = LO_RDONLY, 2 = LO_WRONLY, 4 = LO_APPEND, 8 = LO_RDWR, 16 = LO_BUFFER, 32 = LO_NOBUFFER -> or-mask. You can also use constants named IFX_LO_RDONLY, IFX_LO_WRONLY etc. Return FALSE on error otherwise the new slob object-id.

ifxus_free_slob

(PHP 3>= 3.0.4, PHP 4 )

ifxus_free_slob -- Deletes the slob object

Description

int ifxus_free_slob ( int bid)

Deletes the slob object. bid is the Id of the slob object. Retorna TRUE em caso de sucesso ou FALSE em falhas.

ifxus_open_slob

(PHP 3>= 3.0.4, PHP 4 )

ifxus_open_slob -- Opens an slob object

Description

int ifxus_open_slob ( long bid, int mode)

Opens an slob object. bid should be an existing slob id. Modes: 1 = LO_RDONLY, 2 = LO_WRONLY, 4 = LO_APPEND, 8 = LO_RDWR, 16 = LO_BUFFER, 32 = LO_NOBUFFER -> or-mask. Returns FALSE on error otherwise the new slob object-id.

ifxus_read_slob

(PHP 3>= 3.0.4, PHP 4 )

ifxus_read_slob -- Reads nbytes of the slob object

Description

int ifxus_read_slob ( long bid, long nbytes)

Reads nbytes of the slob object. bid is a existing slob id and nbytes is the number of bytes read. Return FALSE on error otherwise the string.

ifxus_seek_slob

(PHP 3>= 3.0.4, PHP 4 )

ifxus_seek_slob -- Sets the current file or seek position

Description

int ifxus_seek_slob ( long bid, int mode, long offset)

Sets the current file or seek position of an open slob object. bid should be an existing slob id. Modes: 0 = LO_SEEK_SET, 1 = LO_SEEK_CUR, 2 = LO_SEEK_END and offset is an byte offset. Return FALSE on error otherwise the seek position.

ifxus_tell_slob

(PHP 3>= 3.0.4, PHP 4 )

ifxus_tell_slob -- Returns the current file or seek position

Description

int ifxus_tell_slob ( long bid)

Returns the current file or seek position of an open slob object bid should be an existing slob id. Return FALSE on error otherwise the seek position.

ifxus_write_slob

(PHP 3>= 3.0.4, PHP 4 )

ifxus_write_slob -- Writes a string into the slob object

Description

int ifxus_write_slob ( long bid, string content)

Writes a string into the slob object. bid is a existing slob id and content the content to write. Return FALSE on error otherwise bytes written.

XLIV. InterBase functions

Introdução

InterBase is a popular database put out by Borland/Inprise. More information about InterBase is available at http://www.interbase.com/. Oh, by the way, InterBase just joined the open source movement!

Nota: Full support for InterBase 6 was added in PHP 4.0.

This database uses a single quote (') character for escaping, a behavior similar to the Sybase database, add to your php.ini the following directive:

magic_quotes_sybase = On


Requisitos


Instalação

To enable InterBase support configure PHP --with-interbase[=DIR], where DIR is the InterBase base install directory, which defaults to /usr/interbase.

Note to Win32 Users: In order to enable this module on a Windows environment, you must copy gds32.dll from the DLL folder of the PHP/Win32 binary package to the SYSTEM32 folder of your windows machine. (Ex: C:\WINNT\SYSTEM32 or C:\WINDOWS\SYSTEM32). In case you installed the InterBase database server on the same machine PHP is running on, you will have this DLL already. Therfore you don't need to copy gds32.dll from the DLL folder.


Configuração durante execução

O comportamento dessas funções podem ser modificado pelas configurações do php.ini.

Tabela 1. InterBase configuration options

Name Default Changeable
ibase.allow_persistent "1" PHP_INI_SYSTEM
ibase.max_persistent "-1" PHP_INI_SYSTEM
ibase.max_links "-1" PHP_INI_SYSTEM
ibase.default_user NULL PHP_INI_ALL
ibase.default_password NULL PHP_INI_ALL
ibase.timestampformat "%m/%d/%Y%H:%M:%S" PHP_INI_ALL
ibase.dateformat "%m/%d/%Y" PHP_INI_ALL
ibase.timeformat "%H:%M:%S" PHP_INI_ALL
For further details and definition of the PHP_INI_* constants see ini_set().


Tipos Resource


Constantes Predefinidas

As contantes abaixo são definidas por esta extensão e somente estarão disponíveis quando a extensão foi compilada com o PHP ou carregada dinamicamente durante a execução.

IBASE_DEFAULT (integer)

IBASE_TEXT (integer)

IBASE_UNIXTIME (integer)

IBASE_READ (integer)

IBASE_COMMITTED (integer)

IBASE_CONSISTENCY (integer)

IBASE_NOWAIT (integer)

IBASE_TIMESTAMP (integer)

IBASE_DATE (integer)

IBASE_TIME (integer)

Índice
ibase_blob_add --  Add data into created blob
ibase_blob_cancel --  Cancel creating blob
ibase_blob_close --  Close blob
ibase_blob_create --  Create blob for adding data
ibase_blob_echo --  Output blob contents to browser
ibase_blob_get --  Get len bytes data from open blob
ibase_blob_import --  Create blob, copy file in it, and close it
ibase_blob_info --  Return blob length and other useful info
ibase_blob_open --  Open blob for retrieving data parts
ibase_close --  Close a connection to an InterBase database
ibase_commit -- Commit a transaction
ibase_connect --  Open a connection to an InterBase database
ibase_errmsg --  Returns error messages
ibase_execute -- Execute a previously prepared query
ibase_fetch_object -- Get an object from a InterBase database
ibase_fetch_row -- Fetch a row from an InterBase database
ibase_field_info --  Get information about a field
ibase_free_query --  Free memory allocated by a prepared query
ibase_free_result -- Free a result set
ibase_num_fields --  Get the number of fields in a result set
ibase_pconnect --  Creates an persistent connection to an InterBase database
ibase_prepare --  Prepare a query for later binding of parameter placeholders and execution
ibase_query -- Execute a query on an InterBase database
ibase_rollback -- Rolls back a transaction
ibase_timefmt --  Sets the format of timestamp, date and time type columns returned from queries
ibase_trans -- Begin a transaction

ibase_blob_add

(PHP 3>= 3.0.7, PHP 4 )

ibase_blob_add --  Add data into created blob

Description

int ibase_blob_add ( int blob_id, string data)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ibase_blob_cancel

(PHP 3>= 3.0.7, PHP 4 )

ibase_blob_cancel --  Cancel creating blob

Description

int ibase_blob_cancel ( int blob_id)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ibase_blob_close

(PHP 3>= 3.0.7, PHP 4 )

ibase_blob_close --  Close blob

Description

int ibase_blob_close ( int blob_id)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ibase_blob_create

(PHP 3>= 3.0.7, PHP 4 )

ibase_blob_create --  Create blob for adding data

Description

int ibase_blob_create ( [int link_identifier])

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ibase_blob_echo

(PHP 3>= 3.0.7, PHP 4 )

ibase_blob_echo --  Output blob contents to browser

Description

int ibase_blob_echo ( string blob_id_str)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ibase_blob_get

(PHP 3>= 3.0.7, PHP 4 )

ibase_blob_get --  Get len bytes data from open blob

Description

string ibase_blob_get ( int blob_id, int len)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ibase_blob_import

(PHP 3>= 3.0.7, PHP 4 )

ibase_blob_import --  Create blob, copy file in it, and close it

Description

string ibase_blob_import ( [int link_identifier, int file_id])

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ibase_blob_info

(PHP 3>= 3.0.7, PHP 4 )

ibase_blob_info --  Return blob length and other useful info

Description

object ibase_blob_info ( string blob_id_str)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ibase_blob_open

(PHP 3>= 3.0.7, PHP 4 )

ibase_blob_open --  Open blob for retrieving data parts

Description

int ibase_blob_open ( string blob_id)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ibase_close

(PHP 3>= 3.0.6, PHP 4 )

ibase_close --  Close a connection to an InterBase database

Description

int ibase_close ( [int connection_id])

Closes the link to an InterBase database that's associated with a connection id returned from ibase_connect(). If the connection id is omitted, the last opened link is assumed. Default transaction on link is committed, other transactions are rolled back.

ibase_commit

(PHP 3>= 3.0.7, PHP 4 )

ibase_commit -- Commit a transaction

Description

int ibase_commit ( [int link_identifier, int trans_number])

Commits transaction trans_number which was created with ibase_trans().

ibase_connect

(PHP 3>= 3.0.6, PHP 4 )

ibase_connect --  Open a connection to an InterBase database

Description

int ibase_connect ( string database [, string username [, string password [, string charset [, int buffers [, int dialect [, string role]]]]]])

Establishes a connection to an InterBase server. The database argument has to be a valid path to database file on the server it resides on. If the server is not local, it must be prefixed with either 'hostname:' (TCP/IP), '//hostname/' (NetBEUI) or 'hostname@' (IPX/SPX), depending on the connection protocol used. username and password can also be specified with PHP configuration directives ibase.default_user and ibase.default_password. charset is the default character set for a database. buffers is the number of database buffers to allocate for the server-side cache. If 0 or omitted, server chooses its own default. dialect selects the default SQL dialect for any statement executed within a connection, and it defaults to the highest one supported by client libraries.

In case a second call is made to ibase_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned. The link to the server will be closed as soon as the execution of the script ends, unless it's closed earlier by explicitly calling ibase_close().

Exemplo 1. ibase_connect() example

<?php
    $host = 'localhost:/path/to/your.gdb';

    $dbh = ibase_connect($host, $username, $password);
    $stmt = 'SELECT * FROM tblname';
    $sth = ibase_query($dbh, $stmt);
    while ($row = ibase_fetch_object($sth)) {
        echo $row->email, "\n";
    }
    ibase_free_result($sth);
    ibase_close($dbh);
?>

Nota: The optional buffers parameter was added in PHP 4.0.0.

Nota: The optional dialect parameter was added in PHP 4.0.0 and is functional only with InterBase 6 and up.

Nota: The optional role parameter was added in PHP 4.0.0 and is functional only with InterBase 5 and up.

See also ibase_pconnect().

ibase_errmsg

(PHP 3>= 3.0.7, PHP 4 )

ibase_errmsg --  Returns error messages

Description

string ibase_errmsg ( void)

Returns a string containing an error message.

ibase_execute

(PHP 3>= 3.0.6, PHP 4 )

ibase_execute -- Execute a previously prepared query

Description

int ibase_execute ( int query [, int bind_args])

Execute a query prepared by ibase_prepare(). This is a lot more effective than using ibase_query() if you are repeating a same kind of query several times with only some parameters changing.

<?php
    $updates = array(
        1 => 'Eric',
        5 => 'Filip',
        7 => 'Larry'
    );

    $query = ibase_prepare("UPDATE FOO SET BAR = ? WHERE BAZ = ?");

    while (list($baz, $bar) = each($updates)) {
        ibase_execute($query, $bar, $baz);
    }
?>

ibase_fetch_object

(PHP 3>= 3.0.7, PHP 4 )

ibase_fetch_object -- Get an object from a InterBase database

Description

object ibase_fetch_object ( int result_id)

Fetches a row as a pseudo-object from a result_id obtained either by ibase_query() or ibase_execute().

<php
    $dbh = ibase_connect ($host, $username, $password);
    $stmt = 'SELECT * FROM tblname';
    $sth = ibase_query ($dbh, $stmt);
    while ($row = ibase_fetch_object ($sth)) {
        print $row->email . "\n";
    }
    ibase_close ($dbh);
?>

Subsequent call to ibase_fetch_object() would return the next row in the result set, or FALSE if there are no more rows.

See also ibase_fetch_row().

ibase_fetch_row

(PHP 3>= 3.0.6, PHP 4 )

ibase_fetch_row -- Fetch a row from an InterBase database

Description

array ibase_fetch_row ( int result_identifier)

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

ibase_fetch_row() fetches one row of data from the result associated with the specified result_identifier. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0.

Subsequent call to ibase_fetch_row() would return the next row in the result set, or FALSE if there are no more rows.

ibase_field_info

(PHP 3>= 3.0.7, PHP 4 )

ibase_field_info --  Get information about a field

Description

array ibase_field_info ( int result, int field number)

Returns an array with information about a field after a select query has been run. The array is in the form of name, alias, relation, length, type.

$rs=ibase_query("SELECT * FROM tablename"); 
$coln = ibase_num_fields($rs);
for ($i=0; $i < $coln; $i++) {
    $col_info = ibase_field_info($rs, $i); 
    echo "name: ".$col_info['name']."\n"; 
    echo "alias: ".$col_info['alias']."\n"; 
    echo "relation: ".$col_info['relation']."\n"; 
    echo "length: ".$col_info['length']."\n"; 
    echo "type: ".$col_info['type']."\n"; 
    }

ibase_free_query

(PHP 3>= 3.0.6, PHP 4 )

ibase_free_query --  Free memory allocated by a prepared query

Description

int ibase_free_query ( int query)

Free a query prepared by ibase_prepare().

ibase_free_result

(PHP 3>= 3.0.6, PHP 4 )

ibase_free_result -- Free a result set

Description

int ibase_free_result ( int result_identifier)

Free's a result set the has been created by ibase_query().

ibase_num_fields

(PHP 3>= 3.0.7, PHP 4 )

ibase_num_fields --  Get the number of fields in a result set

Description

int ibase_num_fields ( int result_id)

Returns an integer containing the number of fields in a result set.

<?php
       $dbh = ibase_connect ($host, $username, $password);
       $stmt = 'SELECT * FROM tblname';
       $sth = ibase_query ($dbh, $stmt);

       if (ibase_num_fields($sth) > 0) {
       while ($row = ibase_fetch_object ($sth)) {
       print $row->email . "\n";
       }
       } else {
       die ("No Results were found for your query");
       }

       ibase_close ($dbh);
       ?>

See also: ibase_field_info().

ibase_pconnect

(PHP 3>= 3.0.6, PHP 4 )

ibase_pconnect --  Creates an persistent connection to an InterBase database

Description

int ibase_pconnect ( string database [, string username [, string password [, string charset [, int buffers [, int dialect [, string role]]]]]])

ibase_pconnect() acts very much like ibase_connect() with two major differences. First, when connecting, the function will first try to find a (persistent) link that's already opened with the same parameters. If one is found, an identifier for it will be returned instead of opening a new connection. Second, the connection to the InterBase server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (ibase_close() will not close links established by ibase_pconnect()). This type of link is therefore called 'persistent'.

Nota: buffers was added in PHP4-RC2.

Nota: dialect was added in PHP4-RC2. It is functional only with InterBase 6 and versions higher than that.

Nota: role was added in PHP4-RC2. It is functional only with InterBase 5 and versions higher than that.

See also ibase_connect() for the meaning of parameters passed to this function. They are exactly the same.

ibase_prepare

(PHP 3>= 3.0.6, PHP 4 )

ibase_prepare --  Prepare a query for later binding of parameter placeholders and execution

Description

int ibase_prepare ( [int link_identifier, string query])

Prepare a query for later binding of parameter placeholders and execution (via ibase_execute()).

ibase_query

(PHP 3>= 3.0.6, PHP 4 )

ibase_query -- Execute a query on an InterBase database

Description

int ibase_query ( [int link_identifier, string query [, int bind_args]])

Performs a query on an InterBase database. If the query is not successful, returns FALSE. If it is successful and there are resulting rows (such as with a SELECT query), returns a result identifier. If the query was successful and there were no results, returns TRUE. Returns FALSE if the query fails.

See also ibase_errmsg(), ibase_fetch_row(), ibase_fetch_object(), and ibase_free_result().

ibase_rollback

(PHP 3>= 3.0.7, PHP 4 )

ibase_rollback -- Rolls back a transaction

Description

int ibase_rollback ( [int link_identifier, int trans_number])

Rolls back transaction trans_number which was created with ibase_trans().

ibase_timefmt

(PHP 3>= 3.0.6, PHP 4 )

ibase_timefmt --  Sets the format of timestamp, date and time type columns returned from queries

Description

int ibase_timefmt ( string format [, int columntype])

Sets the format of timestamp, date or time type columns returned from queries. Internally, the columns are formatted by c-function strftime(), so refer to it's documentation regarding to the format of the string. columntype is one of the constants IBASE_TIMESTAMP, IBASE_DATE and IBASE_TIME. If omitted, defaults to IBASE_TIMESTAMP for backwards compatibility.

<?php
       // InterBase 6 TIME-type columns will be returned in
       // the form '05 hours 37 minutes'. 
       ibase_timefmt("%H hours %M minutes", IBASE_TIME);
       ?>

You can also set defaults for these formats with PHP configuration directives ibase.timestampformat, ibase.dateformat and ibase.timeformat.

Nota: columntype was added in PHP 4.0. It has any meaning only with InterBase version 6 and higher.

Nota: A backwards incompatible change happened in PHP 4.0 when PHP configuration directive ibase.timeformat was renamed to ibase.timestampformat and directives ibase.dateformat and ibase.timeformat were added, so that the names would match better their functionality.

ibase_trans

(PHP 3>= 3.0.7, PHP 4 )

ibase_trans -- Begin a transaction

Description

int ibase_trans ( [int trans_args [, int link_identifier]])

Begins a transaction.

XLV. Ingres II functions

Introdução

These functions allow you to access Ingres II database servers.

Nota: If you already used PHP extensions to access other database servers, note that Ingres doesn't allow concurrent queries and/or transaction over one connection, thus you won't find any result or transaction handle in this extension. The result of a query must be treated before sending another query, and a transaction must be commited or rolled back before opening another transaction (which is automaticaly done when sending the first query).

Atenção

Este módulo é EXPERIMENTAL. Isso quer dizer que o comportamento neste módulo --- incluindo suas funções e seus nomes, e TUDO mais que está documentado sobre esse módulo --- poderá mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use este módulo por sua própria conta e risco.


Requisitos

To compile PHP with Ingres support, you need the Open API library and header files included with Ingres II.


Instalação

In order to have these functions available, you must compile PHP with Ingres support by using the --with-ingres[=DIR] option, where DIR is the Ingres base directory, which defaults to /II/ingres. If the II_SYSTEM environment variable isn't correctly set you may have to use --with-ingres=DIR to specify your Ingres installation directory.

When using this extension with Apache, if Apache does not start and complains with "PHP Fatal error: Unable to start ingres_ii module in Unknown on line 0" then make sure the environement variable II_SYSTEM is correctly set. Adding "export II_SYSTEM="/home/ingres/II" in the script that starts Apache, just before launching httpd, should be fine.


Configuração durante execução

O comportamento dessas funções podem ser modificado pelas configurações do php.ini.

Tabela 1. Ingres II configuration options

Name Default Changeable
ingres.allow_persistent "1" PHP_INI_SYSTEM
ingres.max_persistent "-1" PHP_INI_SYSTEM
ingres.max_links "-1" PHP_INI_SYSTEM
ingres.default_database NULL PHP_INI_ALL
ingres.default_user NULL PHP_INI_ALL
ingres.default_password NULL PHP_INI_ALL
For further details and definition of the PHP_INI_* constants see ini_set().


Tipos Resource

Esta extensão não possui nenhum tipo resource.


Constantes Predefinidas

As contantes abaixo são definidas por esta extensão e somente estarão disponíveis quando a extensão foi compilada com o PHP ou carregada dinamicamente durante a execução.

INGRES_ASSOC (integer)

INGRES_NUM (integer)

INGRES_BOTH (integer)

Índice
ingres_autocommit -- Switch autocommit on or off
ingres_close -- Close an Ingres II database connection
ingres_commit -- Commit a transaction
ingres_connect --  Open a connection to an Ingres II database
ingres_fetch_array -- Fetch a row of result into an array
ingres_fetch_object -- Fetch a row of result into an object.
ingres_fetch_row --  Fetch a row of result into an enumerated array
ingres_field_length -- Get the length of a field
ingres_field_name -- Get the name of a field in a query result.
ingres_field_nullable -- Test if a field is nullable
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 result
ingres_num_fields --  Get the number of fields returned by the last query
ingres_num_rows --  Get the number of rows affected or returned by the last query
ingres_pconnect --  Open a persistent connection to an Ingres II database
ingres_query -- Send a SQL query to Ingres II
ingres_rollback -- Roll back a transaction

ingres_autocommit

(PHP 4 >= 4.0.2)

ingres_autocommit -- Switch autocommit on or off

Description

bool ingres_autocommit ( [resource link])

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

ingres_autocommit() is called before opening a transaction (before the first call to ingres_query() or just after a call to ingres_rollback() or ingres_commit()) to switch the "autocommit" mode of the server on or off (when the script begins the autocommit mode is off).

When the autocommit mode is on, every query is automaticaly commited by the server, as if ingres_commit() was called after every call to ingres_query().

See also ingres_query(), ingres_rollback(), and ingres_commit().

ingres_close

(PHP 4 >= 4.0.2)

ingres_close -- Close an Ingres II database connection

Description

bool ingres_close ( [resource link])

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Returns TRUE on success, or FALSE on failure.

ingres_close() closes the connection to the Ingres server that's associated with the specified link. If the link parameter isn't specified, the last opened link is used.

ingres_close() isn't usually necessary, as it won't close persistent connections and all non-persistent connections are automatically closed at the end of the script.

See also ingres_connect() and ingres_pconnect().

ingres_commit

(PHP 4 >= 4.0.2)

ingres_commit -- Commit a transaction

Description

bool ingres_commit ( [resource link])

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

ingres_commit() commits the currently open transaction, making all changes made to the database permanent.

This closes the transaction. A new one can be open by sending a query with ingres_query().

You can also have the server commit automaticaly after every query by calling ingres_autocommit() before opening the transaction.

See also ingres_query(), ingres_rollback(), and ingres_autocommit().

ingres_connect

(PHP 4 >= 4.0.2)

ingres_connect --  Open a connection to an Ingres II database

Description

resource ingres_connect ( [string database [, string username [, string password]]])

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Returns a Ingres II link resource on success, or FALSE on failure.

ingres_connect() opens a connection with the Ingres database designated by database, which follows the syntax [node_id::]dbname[/svr_class].

If some parameters are missing, ingres_connect() uses the values in php.ini for ingres.default_database, ingres.default_user, and ingres.default_password.

The connection is closed when the script ends or when ingres_close() is called on this link.

All the other ingres functions use the last opened link as a default, so you need to store the returned value only if you use more than one link at a time.

Exemplo 1. ingres_connect() example

<?php
    $link = ingres_connect ("mydb", "user", "pass")
        or die ("Could not connect");
    print ("Connected successfully");
    ingres_close ($link);
?>

Exemplo 2. ingres_connect() example using default link

<?php
    ingres_connect ("mydb", "user", "pass")
        or die ("Could not connect");
    print ("Connected successfully");
    ingres_close ();
?>

See also ingres_pconnect() and ingres_close().

ingres_fetch_array

(PHP 4 >= 4.0.2)

ingres_fetch_array -- Fetch a row of result into an array

Description

array ingres_fetch_array ( [int result_type [, resource link]])

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

ingres_fetch_array() Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

This function is an extended version of ingres_fetch_row(). In addition to storing the data in the numeric indices of the result array, it also stores the data in associative indices, using the field names as keys.

If two or more columns of the result have the same field names, the last column will take precedence. To access the other column(s) of the same name, you must use the numeric index of the column or make an alias for the column.

ingres_query(select t1.f1 as foo t2.f1 as bar from t1, t2);
$result = ingres_fetch_array();
$foo = $result["foo"];
$bar = $result["bar"];

result_type can be INGRES_NUM for enumerated array, INGRES_ASSOC for associative array, or INGRES_BOTH (default).

Speed-wise, the function is identical to ingres_fetch_object(), and almost as quick as ingres_fetch_row() (the difference is insignificant).

Exemplo 1. ingres_fetch_array() example

<?php
ingres_connect ($database, $user, $password);

ingres_query ("select * from table");
while ($row = ingres_fetch_array()) {
    echo $row["user_id"];  # using associative array
    echo $row["fullname"];
    echo $row[1];          # using enumerated array
    echo $row[2];
}
?>

See also ingres_query(), ingres_num_fields(), ingres_field_name(), ingres_fetch_object(), and ingres_fetch_row().

ingres_fetch_object

(PHP 4 >= 4.0.2)

ingres_fetch_object -- Fetch a row of result into an object.

Description

object ingres_fetch_object ( [int result_type [, resource link]])

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

ingres_fetch_object() Returns an object that corresponds to the fetched row, or FALSE if there are no more rows.

This function is similar to ingres_fetch_array(), with one difference - an object is returned, instead of an array. Indirectly, that means that you can only access the data by the field names, and not by their offsets (numbers are illegal property names).

The optional argument result_type is a constant and can take the following values: INGRES_ASSOC, INGRES_NUM, and INGRES_BOTH.

Speed-wise, the function is identical to ingres_fetch_array(), and almost as quick as ingres_fetch_row() (the difference is insignificant).

Exemplo 1. ingres_fetch_object() example

<?php
ingres_connect ($database, $user, $password);
ingres_query ("select * from table");
while ($row = ingres_fetch_object()) {
    echo $row->user_id;
    echo $row->fullname;
}
?>

See also ingres_query(), ingres_num_fields(), ingres_field_name(), ingres_fetch_array(), and ingres_fetch_row().

ingres_fetch_row

(PHP 4 >= 4.0.2)

ingres_fetch_row --  Fetch a row of result into an enumerated array

Description

array ingres_fetch_row ( [resource link])

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

ingres_fetch_row() returns an array that corresponds to the fetched row, or FALSE if there are no more rows. Each result column is stored in an array offset, starting at offset 1.

Subsequent call to ingres_fetch_row() would return the next row in the result set, or FALSE if there are no more rows.

Exemplo 1. ingres_fetch_row() example

<?php
ingres_connect ($database, $user, $password);

ingres_query ("select * from table");
while ($row = ingres_fetch_row()) {
    echo $row[1];
    echo $row[2];
}
?>

See also ingres_num_fields(), ingres_query(), ingres_fetch_array(), and ingres_fetch_object().

ingres_field_length

(PHP 4 >= 4.0.2)

ingres_field_length -- Get the length of a field

Description

int ingres_field_length ( int index [, resource link])

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

ingres_field_length() returns the length of a field. This is the number of bytes used by the server to store the field. For detailed information, see the Ingres/OpenAPI User Guide - Appendix C.

index is the number of the field and must be between 1 and the value given by ingres_num_fields().

See also ingres_query(), ingres_fetch_array(), ingres_fetch_object(), and ingres_fetch_row().

ingres_field_name

(PHP 4 >= 4.0.2)

ingres_field_name -- Get the name of a field in a query result.

Description

string ingres_field_name ( int index [, resource link])

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

ingres_field_name() returns the name of a field in a query result, or FALSE on failure.

index is the number of the field and must be between 1 and the value given by ingres_num_fields().

See also ingres_query(), ingres_fetch_array(), ingres_fetch_object() and ingres_fetch_row().

ingres_field_nullable

(PHP 4 >= 4.0.2)

ingres_field_nullable -- Test if a field is nullable

Description

bool ingres_field_nullable ( int index [, resource link])

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

ingres_field_nullable() returns TRUE if the field can be set to the NULL value and FALSE if it can't.

index is the number of the field and must be between 1 and the value given by ingres_num_fields().

See also ingres_query(), ingres_fetch_array(), ingres_fetch_object(), and ingres_fetch_row().

ingres_field_precision

(PHP 4 >= 4.0.2)

ingres_field_precision -- Get the precision of a field

Description

int ingres_field_precision ( int index [, resource link])

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

ingres_field_precision() returns the precision of a field. This value is used only for decimal, float and money SQL data types. For detailed information, see the Ingres/OpenAPI User Guide - Appendix C.

index is the number of the field and must be between 1 and the value given by ingres_num_fields().

See also ingres_query(), ingres_fetch_array(), ingres_fetch_object(), and ingres_fetch_row().

ingres_field_scale

(PHP 4 >= 4.0.2)

ingres_field_scale -- Get the scale of a field

Description

int ingres_field_scale ( int index [, resource link])

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

ingres_field_scale() returns the scale of a field. This value is used only for the decimal SQL data type. For detailed information, see the Ingres/OpenAPI User Guide - Appendix C.

index is the number of the field and must be between 1 and the value given by ingres_num_fields().

See also ingres_query(), ingres_fetch_array(), ingres_fetch_object(), and ingres_fetch_row().

ingres_field_type

(PHP 4 >= 4.0.2)

ingres_field_type --  Get the type of a field in a query result

Description

string ingres_field_type ( int index [, resource link])

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

ingres_field_type() returns the type of a field in a query result, or FALSE on failure. Examples of types returned are "IIAPI_BYTE_TYPE", "IIAPI_CHA_TYPE", "IIAPI_DTE_TYPE", "IIAPI_FLT_TYPE", "IIAPI_INT_TYPE", "IIAPI_VCH_TYPE". Some of these types can map to more than one SQL type depending on the length of the field (see ingres_field_length()). For example "IIAPI_FLT_TYPE" can be a float4 or a float8. For detailed information, see the Ingres/OpenAPI User Guide - Appendix C.

index is the number of the field and must be between 1 and the value given by ingres_num_fields().

See also ingres_query(), ingres_fetch_array(), ingres_fetch_object(), and ingres_fetch_row().

ingres_num_fields

(PHP 4 >= 4.0.2)

ingres_num_fields --  Get the number of fields returned by the last query

Description

int ingres_num_fields ( [resource link])

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

ingres_num_fields() returns the number of fields in the results returned by the Ingres server after a call to ingres_query()

See also ingres_query(), ingres_fetch_array(), ingres_fetch_object(), and ingres_fetch_row().

ingres_num_rows

(PHP 4 >= 4.0.2)

ingres_num_rows --  Get the number of rows affected or returned by the last query

Description

int ingres_num_rows ( [resource link])

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

For delete, insert or update queries, ingres_num_rows() returns the number of rows affected by the query. For other queries, ingres_num_rows() returns the number of rows in the query's result.

Nota: This function is mainly meant to get the number of rows modified in the database. If this function is called before using ingres_fetch_array(), ingres_fetch_object() or ingres_fetch_row() the server will delete the result's data and the script won't be able to get them.

You should instead retrieve the result's data using one of these fetch functions in a loop until it returns FALSE, indicating that no more results are available.

See also ingres_query(), ingres_fetch_array(), ingres_fetch_object(), and ingres_fetch_row().

ingres_pconnect

(PHP 4 >= 4.0.2)

ingres_pconnect --  Open a persistent connection to an Ingres II database

Description

resource ingres_pconnect ( [string database [, string username [, string password]]])

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Returns a Ingres II link resource on success, or FALSE on failure.

See ingres_connect() for parameters details and examples. There are only 2 differences between ingres_pconnect() and ingres_connect() : First, when connecting, the function will first try to find a (persistent) link that's already opened with the same parameters. If one is found, an identifier for it will be returned instead of opening a new connection. Second, the connection to the Ingres server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (ingres_close() will not close links established by ingres_pconnect()). This type of link is therefore called 'persistent'.

See also ingres_connect() and ingres_close().

ingres_query

(PHP 4 >= 4.0.2)

ingres_query -- Send a SQL query to Ingres II

Description

bool ingres_query ( string query [, resource link])

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Returns TRUE on success, or FALSE on failure.

ingres_query() sends the given query to the Ingres server. This query must be a valid SQL query (see the Ingres SQL reference guide)

The query becomes part of the currently open transaction. If there is no open transaction, ingres_query() opens a new transaction. To close the transaction, you can either call ingres_commit() to commit the changes made to the database or ingres_rollback() to cancel these changes. When the script ends, any open transaction is rolled back (by calling ingres_rollback()). You can also use ingres_autocommit() before opening a new transaction to have every SQL query immediatly commited.

Some types of SQL queries can't be sent with this function:

Exemplo 1. ingres_query() example

<?php
ingres_connect ($database, $user, $password);

ingres_query ("select * from table");
while ($row = ingres_fetch_row()) {
    echo $row[1];
    echo $row[2];
}
?>

See also ingres_fetch_array(), ingres_fetch_object(), ingres_fetch_row(), ingres_commit(), ingres_rollback(), and ingres_autocommit().

ingres_rollback

(PHP 4 >= 4.0.2)

ingres_rollback -- Roll back a transaction

Description

bool ingres_rollback ( [resource link])

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

ingres_rollback() rolls back the currently open transaction, actually canceling all changes made to the database during the transaction.

This closes the transaction. A new one can be open by sending a query with ingres_query().

See also ingres_query(), ingres_commit(), and ingres_autocommit().

XLVI. IRC Gateway Functions

Introdução

With IRCG you can rapidly stream XML data to thousands of concurrently connected users. This can be used to build powerful, extensible interactive platforms such as online games and webchats. IRCG also features support for a non-streaming mode where a helper application reformats incoming data and supplies static file snippets in special formats such as cHTML (i-mode) or WML (WAP). These static files are then delivered by the high-performance web server.

Up to v3, IRCG runs under these platforms:

  • AIX

  • FreeBSD

  • HP-UX

  • Irix

  • Linux

  • Solaris

  • Tru64


Instalação

Detailed installation instructions can be found here. We urge you to use the provided installation script.


Configuração durante execução

Esta extenção não define nenhum parâmetro de configuração no php.ini.


Tipos Resource


Constantes Predefinidas

Esta extensão não possui nenhuma constante.

Índice
ircg_channel_mode --  Set channel mode flags for user
ircg_disconnect --  Close connection to server
ircg_fetch_error_msg --  Returns the error from previous IRCG operation
ircg_get_username --  Get username for connection
ircg_html_encode --  Encodes HTML preserving output
ircg_ignore_add --  Add a user to your ignore list on a server
ircg_ignore_del --  Remove a user from your ignore list on a server
ircg_is_conn_alive --  Check connection status
ircg_join --  Join a channel on a connected server
ircg_kick --  Kick a user out of a channel on server
ircg_lookup_format_messages --  Check for the existence of a format message set
ircg_msg --  Send message to channel or user on server
ircg_nick --  Change nickname on server
ircg_nickname_escape --  Encode special characters in nickname to be IRC-compliant
ircg_nickname_unescape --  Decodes encoded nickname
ircg_notice --  Send a notice to a user on server
ircg_part --  Leave a channel on server
ircg_pconnect --  Connect to an IRC server
ircg_register_format_messages --  Register a format message set
ircg_set_current --  Set current connection for output
ircg_set_file --  Set logfile for connection
ircg_set_on_die --  Set action to be executed when connection dies
ircg_topic --  Set topic for channel on server
ircg_whois --  Query server for user information

ircg_channel_mode

(PHP 4 >= 4.0.5)

ircg_channel_mode --  Set channel mode flags for user

Description

boolean ircg_channel_mode ( resource connection, string channel, string mode_spec, string nick)

Set channel mode flags for channel on server connected to by connection. Mode flags are passed in mode_spec and are applied to the user specified by nick.

Mode flags are set or cleared by specifying a mode character and prepending it with a plus or minus character, respectively. E.g. operator mode is granted by '+o' and revoked by '-o', as passed as mode_spec.

ircg_disconnect

(PHP 4 >= 4.0.4)

ircg_disconnect --  Close connection to server

Description

boolean ircg_disconnect ( resource connection, string reason)

ircg_disconnect() will close a connection to a server previously established with ircg_pconnect().

See also: ircg_pconnect().

ircg_fetch_error_msg

(PHP 4 >= 4.1.0)

ircg_fetch_error_msg --  Returns the error from previous IRCG operation

Description

array ircg_fetch_error_msg ( resource connection)

ircg_fetch_error_msg() returns the error from a failed connection.

Nota: Error code is stored in first array element, error text in second. The error code is equivalent to IRC reply codes as defined by RFC 2812.

Exemplo 1. ircg_fetch_error_msg() example

if (!ircg_join ($id, "#php")) {
    $error = ircg_fetch_error_msg($id);
    print ("Can't join channel #php. Error code: 
            $error[0] Description: $error[1]");
}

ircg_get_username

(PHP 4 >= 4.1.0)

ircg_get_username --  Get username for connection

Description

string ircg_get_username ( resource connection)

Function ircg_get_username() returns the username for the specified connection connection. Returns FALSE if connection died or is not valid.

ircg_html_encode

(PHP 4 >= 4.0.5)

ircg_html_encode --  Encodes HTML preserving output

Description

boolean ircg_html_encode ( string html_string)

Encodes a HTML string html_string for output. This exposes the interface which the IRCG extension uses internally to reformat data coming from an IRC link. The function causes IRC color/font codes to be encoded in HTML and escapes certain entities.

ircg_ignore_add

(PHP 4 >= 4.0.5)

ircg_ignore_add --  Add a user to your ignore list on a server

Description

boolean ircg_ignore_add ( resource connection, string nick)

This function adds user nick to the ignore list of connection connection. Afterwards, IRCG will suppress all messages from this user through the associated connection.

See also: ircg_ignore_del().

ircg_ignore_del

(PHP 4 >= 4.0.5)

ircg_ignore_del --  Remove a user from your ignore list on a server

Description

boolean ircg_ignore_del ( resource connection, string nick)

This function removes user nick from the IRCG ignore list associated with connection.

See also: ircg_ignore_add().

ircg_is_conn_alive

(PHP 4 >= 4.0.5)

ircg_is_conn_alive --  Check connection status

Description

boolean ircg_is_conn_alive ( resource connection)

ircg_is_conn_alive() returns TRUE if connection is still alive and working or FALSE, if the connection has died for some reason.

ircg_join

(PHP 4 >= 4.0.4)

ircg_join --  Join a channel on a connected server

Description

boolean ircg_join ( resource connection, string channel [, string key])

Join the channel channel on the server connected to by connection. IRCG will optionally pass the room key key.

ircg_kick

(PHP 4 >= 4.0.5)

ircg_kick --  Kick a user out of a channel on server

Description

boolean ircg_kick ( resource connection, string channel, string nick, string reason)

Kick user nick from channel on server connected to by connection. reason should give a short message describing why this action was performed.

ircg_lookup_format_messages

(PHP 4 >= 4.0.5)

ircg_lookup_format_messages --  Check for the existence of a format message set

Description

boolean ircg_lookup_format_messages ( string name)

Check for the existence of the format message set name. Sets may be registered with ircg_register_format_messages(), a default set named ircg is always available. Returns TRUE, if the set exists and FALSE otherwise.

See also: ircg_register_format_messages()

ircg_msg

(PHP 4 >= 4.0.4)

ircg_msg --  Send message to channel or user on server

Description

boolean ircg_msg ( resource connection, string recipient, string message [, boolean suppress])

ircg_msg() will send the message to a channel or user on the server connected to by connection. A recipient starting with # or & will send the message to a channel, anything else will be interpreted as a username.

Setting the optional parameter suppress to a TRUE value will suppress output of your message to your own connection. This so-called loopback is necessary, because the IRC server does not echo PRIVMSG commands back to us.

ircg_nick

(PHP 4 >= 4.0.5)

ircg_nick --  Change nickname on server

Description

boolean ircg_nick ( resource connection, string nick)

Change your nickname on the given connection to the one given in nick, if possible.

Will return TRUE on success and FALSE on failure.

ircg_nickname_escape

(PHP 4 >= 4.0.6)

ircg_nickname_escape --  Encode special characters in nickname to be IRC-compliant

Description

string ircg_nickname_escape ( string nick)

Function ircg_nickname_escape() returns an encoded nickname specified by nick wich is IRC-compliant.

See also: ircg_nickname_unescape()

ircg_nickname_unescape

(PHP 4 >= 4.0.6)

ircg_nickname_unescape --  Decodes encoded nickname

Description

string ircg_nickname_unescape ( string nick)

Function ircg_nickname_unescape() returns a decoded nickname, which is specified in nick.

See also: ircg_nickname_escape()

ircg_notice

(PHP 4 >= 4.0.5)

ircg_notice --  Send a notice to a user on server

Description

boolean ircg_notice ( resource connection, string , string message)

This function will send the message text to the user nick on the server connected to by connection. IRC servers and other software will not automatically generate replies to NOTICEs in contrast to other message types.

ircg_part

(PHP 4 >= 4.0.4)

ircg_part --  Leave a channel on server

Description

boolean ircg_part ( resource connection, string channel)

Leave the channel channel on the server connected to by connection.

ircg_pconnect

(PHP 4 >= 4.0.4)

ircg_pconnect --  Connect to an IRC server

Description

resource ircg_pconnect ( string username [, string server_ip [, int server_port [, string msg_format [, array ctcp_messages [, array user_settings]]]]])

ircg_pconnect() will try to establish a connection to an IRC server and return a connection resource handle for further use.

The only mandatory parameter is username, this will set your initial nickname on the server. server_ip and server_port are optional and default to 127.0.0.1 and 6667.

Nota: For now parameter server_ip will not do any hostname lookups and will only accept IP addresses in numerical form. DNS lookups are expensive and should be done in the context of IRCG.

You can customize the output of IRC messages and events by selecting a format message set previously created with ircg_register_format_messages() by specifying the set's name in msg_format.

If you want to handle CTCP messages such as ACTION (/me), you need to define a mapping from CTCP type (e.g. ACTION) to a custom format string. Do this by passing an associative array as ctcp_messages. The keys of the array are the CTCP type and the respective value is the format message.

You can define "ident", "password", and "realname" tokens which are sent to the IRC server by setting these in an associative array. Pass that array as user_settings.

See also: ircg_disconnect(), ircg_is_conn_alive(), ircg_register_format_messages().

ircg_register_format_messages

(PHP 4 >= 4.0.5)

ircg_register_format_messages --  Register a format message set

Description

boolean ircg_register_format_messages ( string name, array messages)

With ircg_register_format_messages() you can customize the way your IRC output looks like or which script functions are invoked on the client side.

  • Plain channel message

  • Private message received

  • Private message sent

  • Some user leaves channel

  • Some user enters channel

  • Some user was kicked from the channel

  • Topic has been changed

  • Error

  • Fatal error

  • Join list end(?)

  • Self part(?)

  • Some user changes his nick

  • Some user quits his connection

  • Mass join begin

  • Mass join element

  • Mass join end

  • Whois user

  • Whois server

  • Whois idle

  • Whois channel

  • Whois end

  • Voice status change on user

  • Operator status change on user

  • Banlist

  • Banlist end

  • %f - from

  • %t - to

  • %c - channel

  • %r - plain message

  • %m - encoded message

  • %j - js encoded message

  • 1 - mod encode

  • 2 - nickname decode

See also: ircg_lookup_format_messages().

ircg_set_current

(PHP 4 >= 4.0.4)

ircg_set_current --  Set current connection for output

Description

boolean ircg_set_current ( resource connection)

Select the current HTTP connection for output in this execution context. Every output sent from the server connected to by connection will be copied to standard output while using default formatting or a format message set specified by ircg_register_format_messages().

See also: ircg_register_format_messages().

ircg_set_file

(PHP 4 >= 4.2.0)

ircg_set_file --  Set logfile for connection

Description

bool ircg_set_file ( resource connection, string path)

Function ircg_set_file() specifies a logfile path in which all output from connection connection will be logged. Returns TRUE on success, otherwise FALSE.

ircg_set_on_die

(PHP 4 >= 4.2.0)

ircg_set_on_die --  Set action to be executed when connection dies

Description

bool ircg_set_on_die ( resource connection, string host, int port, string data)

In case of the termination of connection connection IRCG will connect to host at port (Note: host must be an IPv4 address, IRCG does not resolve host-names due to blocking issues), send data to the new host connection and will wait until the remote part closes connection. This can be used to trigger a PHP script for example.

This feature requires IRCG 3.

ircg_topic

(PHP 4 >= 4.0.5)

ircg_topic --  Set topic for channel on server

Description

boolean ircg_topic ( resource connection, string channel, string new_topic)

Change the topic for channel channel on the server connected to by connection to new_topic.

ircg_whois

(PHP 4 >= 4.0.5)

ircg_whois --  Query server for user information

Description

boolean ircg_whois ( resource connection, string nick)

Sends a query to the connected server connection to ask for information about the specified user nick.

XLVII. PHP / Java Integration

Introdução

There are two possible ways to bridge PHP and Java: you can either integrate PHP into a Java Servlet environment, which is the more stable and efficient solution, or integrate Java support into PHP. The former is provided by a SAPI module that interfaces with the Servlet server, the latter by this Java extension.

The Java extension provides a simple and effective means for creating and invoking methods on Java objects from PHP. The JVM is created using JNI, and everything runs in-process.

Atenção

Este módulo é EXPERIMENTAL. Isso quer dizer que o comportamento neste módulo --- incluindo suas funções e seus nomes, e TUDO mais que está documentado sobre esse módulo --- poderá mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use este módulo por sua própria conta e risco.


Requisitos

You need a Java VM installed on your machine to use this extension.


Instalação

To include Java support in your PHP build you must add the option --with-java[=DIR] where DIR points to the base install directory of your JDK. This extension can only be built as a shared dl. More build instructions for this extension can be found in php4/ext/java/README.

Note to Win32 Users: In order to enable this module on a Windows environment, you must copy jvm.dll from the DLL folder of the PHP/Win32 binary package to the SYSTEM32 folder of your windows machine. (Ex:C:\WINNT\SYSTEM32 or C:\WINDOWS\SYSTEM32)


Configuração durante execução

O comportamento dessas funções podem ser modificado pelas configurações do php.ini.

Tabela 1. Java configuration options

Name Default Changeable
java.class.path NULL PHP_INI_ALL
java.home NULL PHP_INI_ALL
java.library.path NULL PHP_INI_ALL
java.library JAVALIB PHP_INI_ALL
For further details and definition of the PHP_INI_* constants see ini_set().


Tipos Resource

Esta extensão não possui nenhum tipo resource.


Constantes Predefinidas

Esta extensão não possui nenhuma constante.


Exemplos

Exemplo 1. Java Example

<?php
  // get instance of Java class java.lang.System in PHP
  $system = new Java('java.lang.System');

  // demonstrate property access
  print 'Java version='.$system->getProperty('java.version').' <br>';
  print 'Java vendor=' .$system->getProperty('java.vendor').' <br>';
  print 'OS='.$system->getProperty('os.name').' '.
              $system->getProperty('os.version').' on '.
              $system->getProperty('os.arch').' <br>';

  // java.util.Date example
  $formatter = new Java('java.text.SimpleDateFormat',
                        "EEEE, MMMM dd, yyyy 'at' h:mm:ss a zzzz");

  print $formatter->format(new Java('java.util.Date'));
?>

Exemplo 2. AWT Example

<?php
  // This example is only intented to be run as a CGI.

  $frame  = new Java('java.awt.Frame', 'PHP');
  $button = new Java('java.awt.Button', 'Hello Java World!');

  $frame->add('North', $button);
  $frame->validate();
  $frame->pack();
  $frame->visible = True;

  $thread = new Java('java.lang.Thread');
  $thread->sleep(10000);

  $frame->dispose();
?>
Notes:

  • new Java() will create an instance of a class if a suitable constructor is available. If no parameters are passed and the default constructor is useful as it provides access to classes like java.lang.System which expose most of their functionallity through static methods.

  • Accessing a member of an instance will first look for bean properties then public fields. In other words, print $date.time will first attempt to be resolved as $date.getTime(), then as $date.time.

  • Both static and instance members can be accessed on an object with the same syntax. Furthermore, if the java object is of type java.lang.Class, then static members of the class (fields and methods) can be accessed.

  • Exceptions raised result in PHP warnings, and NULL results. The warnings may be eliminated by prefixing the method call with an "@" sign. The following APIs may be used to retrieve and reset the last error:

  • Overload resolution is in general a hard problem given the differences in types between the two languages. The PHP Java extension employs a simple, but fairly effective, metric for determining which overload is the best match.

    Additionally, method names in PHP are not case sensitive, potentially increasing the number of overloads to select from.

    Once a method is selected, the parameters are cooerced if necessary, possibly with a loss of data (example: double precision floating point numbers will be converted to boolean).

  • In the tradition of PHP, arrays and hashtables may pretty much be used interchangably. Note that hashtables in PHP may only be indexed by integers or strings; and that arrays of primitive types in Java can not be sparse. Also note that these constructs are passed by value, so may be expensive in terms of memory and time.


Java Servlet SAPI

The Java Servlet SAPI builds upon the mechanism defined by the Java extension to enable the entire PHP processor to be run as a servlet. The primary advanatage of this from a PHP perspective is that web servers which support servlets typically take great care in pooling and reusing JVMs. Build instructions for the Servlet SAPI module can be found in php4/sapi/README. Notes:

  • While this code is intended to be able to run on any servlet engine, it has only been tested on Apache's Jakarta/tomcat to date. Bug reports, success stories and/or patches required to get this code to run on other engines would be appreciated.

  • PHP has a habit of changing the working directory. sapi/servlet will eventually change it back, but while PHP is running the servlet engine may not be able to load any classes from the CLASSPATH which are specified using a relative directory syntax, or find the work directory used for administration and JSP compilation tasks.

Índice
java_last_exception_clear -- Clear last Java exception
java_last_exception_get -- Get last Java exception

java_last_exception_clear

(PHP 4 >= 4.0.2)

java_last_exception_clear -- Clear last Java exception

Description

void java_last_exception_clear ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

See java_last_exception_get() for an example.

java_last_exception_get

(PHP 4 >= 4.0.2)

java_last_exception_get -- Get last Java exception

Description

exception java_last_exception_get ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

The following example demonstrates the usage of Java's exception handler from within PHP:

Exemplo 1. Java exception handler

<?php
  $stack = new Java('java.util.Stack');
  $stack->push(1);

  // This should succeed
  $result = $stack->pop();
  $ex = java_last_exception_get();
  if (!$ex) print "$result\n";

  // This should fail (error suppressed by @)
  $result = @$stack->pop();
  $ex = java_last_exception_get();
  if ($ex) print $ex->toString();

  // Clear last exception
  java_last_exception_clear();
?>

XLVIII. LDAP functions

Introdução

LDAP is the Lightweight Directory Access Protocol, and is a protocol used to access "Directory Servers". The Directory is a special kind of database that holds information in a tree structure.

The concept is similar to your hard disk directory structure, except that in this context, the root directory is "The world" and the first level subdirectories are "countries". Lower levels of the directory structure contain entries for companies, organisations or places, while yet lower still we find directory entries for people, and perhaps equipment or documents.

To refer to a file in a subdirectory on your hard disk, you might use something like:


     /usr/local/myapp/docs
    

The forwards slash marks each division in the reference, and the sequence is read from left to right.

The equivalent to the fully qualified file reference in LDAP is the "distinguished name", referred to simply as "dn". An example dn might be:


     cn=John Smith,ou=Accounts,o=My Company,c=US
    

The comma marks each division in the reference, and the sequence is read from right to left. You would read this dn as:


     country = US
     organization = My Company
     organizationalUnit = Accounts
     commonName = John Smith
    

In the same way as there are no hard rules about how you organise the directory structure of a hard disk, a directory server manager can set up any structure that is meaningful for the purpose. However, there are some conventions that are used. The message is that you can not write code to access a directory server unless you know something about its structure, any more than you can use a database without some knowledge of what is available.

Lots of information about LDAP can be found at

The Netscape SDK contains a helpful Programmer's Guide in HTML format.


Requisitos

You will need to get and compile LDAP client libraries from either the University of Michigan ldap-3.3 package or the Netscape Directory SDK 3.0 to compile PHP with LDAP support.


Instalação

LDAP support in PHP is not enabled by default. You will need to use the --with-ldap[=DIR] configuration option when compiling PHP to enable LDAP support. DIR is the LDAP base install directory.

Note to Win32 Users: In order to enable this module on a Windows environment, you must copy libsasl.dll from the DLL folder of the PHP/Win32 binary package to the SYSTEM32 folder of your windows machine. (Ex: C:\WINNT\SYSTEM32 or C:\WINDOWS\SYSTEM32)


Configuração durante execução

O comportamento dessas funções podem ser modificado pelas configurações do php.ini.

Tabela 1. LDAP configuration options

Name Default Changeable
ldap.max_links "-1" PHP_INI_SYSTEM
For further details and definition of the PHP_INI_* constants see ini_set().


Tipos Resource

Esta extensão não possui nenhum tipo resource.


Constantes Predefinidas

As contantes abaixo são definidas por esta extensão e somente estarão disponíveis quando a extensão foi compilada com o PHP ou carregada dinamicamente durante a execução.

LDAP_DEREF_NEVER (integer)

LDAP_DEREF_SEARCHING (integer)

LDAP_DEREF_FINDING (integer)

LDAP_DEREF_ALWAYS (integer)

LDAP_OPT_DEREF (integer)

LDAP_OPT_SIZELIMIT (integer)

LDAP_OPT_TIMELIMIT (integer)

LDAP_OPT_PROTOCOL_VERSION (integer)

LDAP_OPT_ERROR_NUMBER (integer)

LDAP_OPT_REFERRALS (integer)

LDAP_OPT_RESTART (integer)

LDAP_OPT_HOST_NAME (integer)

LDAP_OPT_ERROR_STRING (integer)

LDAP_OPT_MATCHED_DN (integer)

LDAP_OPT_SERVER_CONTROLS (integer)

LDAP_OPT_CLIENT_CONTROLS (integer)

LDAP_OPT_DEBUG_LEVEL (integer)

GSLC_SSL_NO_AUTH (integer)

GSLC_SSL_ONEWAY_AUTH (integer)

GSLC_SSL_TWOWAY_AUTH (integer)


Exemplos

Retrieve information for all entries where the surname starts with "S" from a directory server, displaying an extract with name and email address.

Exemplo 1. LDAP search example

<?php
// basic sequence with LDAP is connect, bind, search, interpret search
// result, close connection

echo "<h3>LDAP query test</h3>";
echo "Connecting ...";
$ds=ldap_connect("localhost");  // must be a valid LDAP server!
echo "connect result is ".$ds."<p>";

if ($ds) { 
    echo "Binding ..."; 
    $r=ldap_bind($ds);     // this is an "anonymous" bind, typically
                           // read-only access
    echo "Bind result is ".$r."<p>";

    echo "Searching for (sn=S*) ...";
    // Search surname entry
    $sr=ldap_search($ds,"o=My Company, c=US", "sn=S*");  
    echo "Search result is ".$sr."<p>";

    echo "Number of entires returned is ".ldap_count_entries($ds,$sr)."<p>";

    echo "Getting entries ...<p>";
    $info = ldap_get_entries($ds, $sr);
    echo "Data for ".$info["count"]." items returned:<p>";

    for ($i=0; $i<$info["count"]; $i++) {
        echo "dn is: ". $info[$i]["dn"] ."<br>";
        echo "first cn entry is: ". $info[$i]["cn"][0] ."<br>";
        echo "first email entry is: ". $info[$i]["mail"][0] ."<p>";
    }

    echo "Closing connection";
    ldap_close($ds);

} else {
    echo "<h4>Unable to connect to LDAP server</h4>";
}
?>

Using the PHP LDAP calls

Before you can use the LDAP calls you will need to know ..

  • The name or address of the directory server you will use

  • The "base dn" of the server (the part of the world directory that is held on this server, which could be "o=My Company,c=US")

  • Whether you need a password to access the server (many servers will provide read access for an "anonymous bind" but require a password for anything else)

The typical sequence of LDAP calls you will make in an application will follow this pattern:


  ldap_connect()    // establish connection to server
     |
  ldap_bind()       // anonymous or authenticated "login"
     |
  do something like search or update the directory
  and display the results
     |
  ldap_close()      // "logout"

Índice
ldap_8859_to_t61 --  Translate 8859 characters to t61 characters
ldap_add -- Add entries to LDAP directory
ldap_bind -- Bind to LDAP directory
ldap_close -- Close link to LDAP server
ldap_compare -- Compare value of attribute found in entry specified with DN
ldap_connect -- Connect to an LDAP server
ldap_count_entries -- Count the number of entries in a search
ldap_delete -- Delete an entry from a directory
ldap_dn2ufn -- Convert DN to User Friendly Naming format
ldap_err2str --  Convert LDAP error number into string error message
ldap_errno --  Return the LDAP error number of the last LDAP command
ldap_error --  Return the LDAP error message of the last LDAP command
ldap_explode_dn -- Splits DN into its component parts
ldap_first_attribute -- Return first attribute
ldap_first_entry -- Return first result id
ldap_first_reference --  Return first reference
ldap_free_result -- Free result memory
ldap_get_attributes -- Get attributes from a search result entry
ldap_get_dn -- Get the DN of a result entry
ldap_get_entries -- Get all result entries
ldap_get_option -- Get the current value for given option
ldap_get_values_len -- Get all binary values from a result entry
ldap_get_values -- Get all values from a result entry
ldap_list -- Single-level search
ldap_mod_add -- Add attribute values to current attributes
ldap_mod_del -- Delete attribute values from current attributes
ldap_mod_replace -- Replace attribute values with new ones
ldap_modify -- Modify an LDAP entry
ldap_next_attribute -- Get the next attribute in result
ldap_next_entry -- Get next result entry
ldap_next_reference --  Get next reference
ldap_parse_reference --  Extract information from reference entry
ldap_parse_result --  Extract information from result
ldap_read -- Read an entry
ldap_rename -- Modify the name of an entry
ldap_search -- Search LDAP tree
ldap_set_option -- Set the value of the given option
ldap_set_rebind_proc --  Set a callback function to do re-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_unbind -- Unbind from LDAP directory

ldap_8859_to_t61

(PHP 4 >= 4.0.2)

ldap_8859_to_t61 --  Translate 8859 characters to t61 characters

Description

string ldap_8859_to_t61 ( string value)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ldap_add

(PHP 3, PHP 4 )

ldap_add -- Add entries to LDAP directory

Description

bool ldap_add ( resource link_identifier, string dn, array entry)

Retorna TRUE em caso de sucesso ou FALSE em falhas.

The ldap_add() function is used to add entries in the LDAP directory. The DN of the entry to be added is specified by dn. Array entry specifies the information about the entry. The values in the entries are indexed by individual attributes. In case of multiple values for an attribute, they are indexed using integers starting with 0.


    entry["attribute1"] = value
    entry["attribute2"][0] = value1
    entry["attribute2"][1] = value2

Exemplo 1. Complete example with authenticated bind

<?php
$ds=ldap_connect("localhost");  // assuming the LDAP server is on this host

if ($ds) {
    // bind with appropriate dn to give update access
    $r=ldap_bind($ds,"cn=root, o=My Company, c=US", "secret");

    // prepare data
    $info["cn"]="John Jones";
    $info["sn"]="Jones";
    $info["mail"]="jonj@here.and.now";
    $info["objectclass"]="person";

    // add data to directory
    $r=ldap_add($ds, "cn=John Jones, o=My Company, c=US", $info);

    ldap_close($ds);
} else {
    echo "Unable to connect to LDAP server"; 
}
?>

ldap_bind

(PHP 3, PHP 4 )

ldap_bind -- Bind to LDAP directory

Description

bool ldap_bind ( resource link_identifier [, string bind_rdn [, string bind_password]])

Binds to the LDAP directory with specified RDN and password. Retorna TRUE em caso de sucesso ou FALSE em falhas.

ldap_bind() does a bind operation on the directory. bind_rdn and bind_password are optional. If not specified, anonymous bind is attempted.

Exemplo 1. Using LDAP Bind

<?php

// using ldap bind
$ldaprdn  = 'uname';     // ldap rdn or dn
$ldappass = 'password';  // associated password

// connect to ldap server
$ldapconn = ldap_connect("ldap.example.com")
    or die("Could not connect to LDAP server.");

if ($ldapconn) {

    // binding to ldap server
    $ldapbind = ldap_bind($ldapconn, $ldaprdn, $ldappass);

    // verify binding
    if ($ldapbind) {
        echo "LDAP bind successful...";
    } else {
        echo "LDAP bind failed...";
    }
        
}

?>

Exemplo 2. Using LDAP Bind Anonymously

<?php

//using ldap bind anonymously

// connect to ldap server
$ldapconn = ldap_connect("ldap.example.com")
    or die("Could not connect to LDAP server.");

if ($ldapconn) {

    // binding anonymously
    $ldapbind = ldap_bind($ldapconn);

    if ($ldapbind) {
        echo "LDAP bind anonymous successful...";
    } else {
        echo "LDAP bind anonymous failed...";
    }
 
}
    
?>

ldap_close

(PHP 3, PHP 4 )

ldap_close -- Close link to LDAP server

Description

bool ldap_close ( resource link_identifier)

Retorna TRUE em caso de sucesso ou FALSE em falhas.

ldap_close() closes the link to the LDAP server that's associated with the specified link_identifier.

This call is internally identical to ldap_unbind(). The LDAP API uses the call ldap_unbind(), so perhaps you should use this in preference to ldap_close().

Nota: This function is an alias of ldap_unbind().

ldap_compare

(PHP 4 >= 4.0.2)

ldap_compare -- Compare value of attribute found in entry specified with DN

Description

bool ldap_compare ( resource link_identifier, string dn, string attribute, string value)

Returns TRUE if value matches otherwise returns FALSE. Returns -1 on error.

ldap_compare() is used to compare value of attribute to value of same attribute in LDAP directory entry specified with dn.

The following example demonstrates how to check whether or not given password matches the one defined in DN specified entry.

Exemplo 1. Complete example of password check

<?php

$ds=ldap_connect("localhost");  // assuming the LDAP server is on this host
      
if ($ds) {

    // bind 
    if(ldap_bind($ds)) {

        // prepare data
        $dn = "cn=Matti Meikku, ou=My Unit, o=My Company, c=FI";
        $value = "secretpassword";
        $attr = "password"; 

        // compare value
        $r=ldap_compare($ds, $dn, $attr, $value);

        if ($r === -1) {
            echo "Error: ".ldap_error($ds);
        } elseif ($r === TRUE) {
            echo "Password correct.";
        } elseif ($r === FALSE) {
            echo "Wrong guess! Password incorrect.";
        }

    } else {
        echo "Unable to bind to LDAP server.";
    }          

    ldap_close($ds);

} else {
    echo "Unable to connect to LDAP server.";
}
?>

Atenção

ldap_compare() can NOT be used to compare BINARY values!

Nota: This function was added in 4.0.2.

ldap_connect

(PHP 3, PHP 4 )

ldap_connect -- Connect to an LDAP server

Description

resource ldap_connect ( [string hostname [, int port]])

Returns a positive LDAP link identifier on success, or FALSE on error.

ldap_connect() establishes a connection to a LDAP server on a specified hostname and port. Both the arguments are optional. If no arguments are specified then the link identifier of the already opened link will be returned. If only hostname is specified, then the port defaults to 389.

If you are using OpenLDAP 2.x.x you can specify a URL instead of the hostname. To use LDAP with SSL, compile OpenLDAP 2.x.x with SSL support, configure PHP with SSL, and use ldaps://hostname/ as host parameter. The port parameter is not used when using URLs.

Nota: URL and SSL support were added in 4.0.4.

Exemplo 1. Example of connecting to LDAP server.

<?php

// LDAP variables
$ldaphost = "ldap.example.com";  // your ldap servers
$ldapport = 389;                 // your ldap server's port number

// Connecting to LDAP
$ldapconn = ldap_connect( $ldaphost, $ldapport ) 
          or die( "Could not connect to {$ldaphost}" );

?>

Exemplo 2. Example of connecting securely to LDAP server.

<?php

// make sure your host is the correct one
// that you issued your secure certificate to
$ldaphost = "ldaps://ldap.example.com/";

// Connecting to LDAP
$ldapconn = ldap_connect( $ldaphost ) 
          or die( "Could not connect to {$ldaphost}" );

?>

ldap_count_entries

(PHP 3, PHP 4 )

ldap_count_entries -- Count the number of entries in a search

Description

int ldap_count_entries ( resource link_identifier, resource result_identifier)

Returns number of entries in the result or FALSE on error.

ldap_count_entries() returns the number of entries stored in the result of previous search operations. result_identifier identifies the internal ldap result.

ldap_delete

(PHP 3, PHP 4 )

ldap_delete -- Delete an entry from a directory

Description

bool ldap_delete ( resource link_identifier, string dn)

Retorna TRUE em caso de sucesso ou FALSE em falhas.

ldap_delete() function delete a particular entry in LDAP directory specified by dn.

ldap_dn2ufn

(PHP 3, PHP 4 )

ldap_dn2ufn -- Convert DN to User Friendly Naming format

Description

string ldap_dn2ufn ( string dn)

ldap_dn2ufn() function is used to turn a DN, specified by dn, into a more user-friendly form, stripping off type names.

ldap_err2str

(PHP 3>= 3.0.13, PHP 4 )

ldap_err2str --  Convert LDAP error number into string error message

Description

string ldap_err2str ( int errno)

Returns string error message.

This function returns the string error message explaining the error number errno. While LDAP errno numbers are standardized, different libraries return different or even localized textual error messages. Never check for a specific error message text, but always use an error number to check.

See also ldap_errno() and ldap_error().

Exemplo 1. Enumerating all LDAP error messages

<?php
  for($i=0; $i<100; $i++) {
    printf("Error $i: %s<br>\n", ldap_err2str($i));
  }
?>

ldap_errno

(PHP 3>= 3.0.12, PHP 4 )

ldap_errno --  Return the LDAP error number of the last LDAP command

Description

int ldap_errno ( resource link_identifier)

Return the LDAP error number of the last LDAP command for this link.

This function returns the standardized error number returned by the last LDAP command for the given link_identifier. This number can be converted into a textual error message using ldap_err2str().

Unless you lower your warning level in your php.ini sufficiently or prefix your LDAP commands with @ (at) characters to suppress warning output, the errors generated will also show up in your HTML output.

Exemplo 1. Generating and catching an error

<?php
// This example contains an error, which we will catch.
$ld = ldap_connect("localhost");
$bind = ldap_bind($ld);
// syntax error in filter expression (errno 87),
// must be "objectclass=*" to work.
$res =  @ldap_search($ld, "o=Myorg, c=DE", "objectclass");
if (!$res) {
    printf("LDAP-Errno: %s<br>\n", ldap_errno($ld));
    printf("LDAP-Error: %s<br>\n", ldap_error($ld));
    die("Argh!<br>\n");
}
$info = ldap_get_entries($ld, $res);
printf("%d matching entries.<br>\n", $info["count"]);
?>

See also ldap_err2str() and ldap_error().

ldap_error

(PHP 3>= 3.0.12, PHP 4 )

ldap_error --  Return the LDAP error message of the last LDAP command

Description

string ldap_error ( resource link_identifier)

Returns string error message.

This function returns the string error message explaining the error generated by the last LDAP command for the given link_identifier While LDAP errno numbers are standardized, different libraries return different or even localized textual error messages. Never check for a specific error message text, but always use an error number to check.

Unless you lower your warning level in your php.ini sufficiently or prefix your LDAP commands with @ (at) characters to suppress warning output, the errors generated will also show up in your HTML output.

See also ldap_err2str() and ldap_errno().

ldap_explode_dn

(PHP 3, PHP 4 )

ldap_explode_dn -- Splits DN into its component parts

Description

array ldap_explode_dn ( string dn, int with_attrib)

ldap_explode_dn() function is used to split the DN returned by ldap_get_dn() and breaks it up into its component parts. Each part is known as Relative Distinguished Name, or RDN. ldap_explode_dn() returns an array of all those components. with_attrib is used to request if the RDNs are returned with only values or their attributes as well. To get RDNs with the attributes (i.e. in attribute=value format) set with_attrib to 0 and to get only values set it to 1.

ldap_first_attribute

(PHP 3, PHP 4 )

ldap_first_attribute -- Return first attribute

Description

string ldap_first_attribute ( resource link_identifier, resource result_entry_identifier, int ber_identifier)

Returns the first attribute in the entry on success and FALSE on error.

Similar to reading entries, attributes are also read one by one from a particular entry. ldap_first_attribute() returns the first attribute in the entry pointed by the result_entry_identifier. Remaining attributes are retrieved by calling ldap_next_attribute() successively. ber_identifier is the identifier to internal memory location pointer. It is passed by reference. The same ber_identifier is passed to the ldap_next_attribute() function, which modifies that pointer.

See also ldap_get_attributes()

ldap_first_entry

(PHP 3, PHP 4 )

ldap_first_entry -- Return first result id

Description

resource ldap_first_entry ( resource link_identifier, resource result_identifier)

Returns the result entry identifier for the first entry on success and FALSE on error.

Entries in the LDAP result are read sequentially using the ldap_first_entry() and ldap_next_entry() functions. ldap_first_entry() returns the entry identifier for first entry in the result. This entry identifier is then supplied to ldap_next_entry() routine to get successive entries from the result.

See also ldap_get_entries().

ldap_first_reference

(PHP 4 >= 4.0.5)

ldap_first_reference --  Return first reference

Description

resource ldap_first_reference ( resource link, resource result)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ldap_free_result

(PHP 3, PHP 4 )

ldap_free_result -- Free result memory

Description

bool ldap_free_result ( resource result_identifier)

Retorna TRUE em caso de sucesso ou FALSE em falhas.

ldap_free_result() frees up the memory allocated internally to store the result and pointed by the result_identifier. All result memory will be automatically freed when the script terminates.

Typically all the memory allocated for the ldap result gets freed at the end of the script. In case the script is making successive searches which return large result sets, ldap_free_result() could be called to keep the runtime memory usage by the script low.

ldap_get_attributes

(PHP 3, PHP 4 )

ldap_get_attributes -- Get attributes from a search result entry

Description

array ldap_get_attributes ( resource link_identifier, resource result_entry_identifier)

Returns a complete entry information in a multi-dimensional array on success and FALSE on error.

ldap_get_attributes() function is used to simplify reading the attributes and values from an entry in the search result. The return value is a multi-dimensional array of attributes and values.

Having located a specific entry in the directory, you can find out what information is held for that entry by using this call. You would use this call for an application which "browses" directory entries and/or where you do not know the structure of the directory entries. In many applications you will be searching for a specific attribute such as an email address or a surname, and won't care what other data is held.


return_value["count"] = number of attributes in the entry
return_value[0] = first attribute
return_value[n] = nth attribute

return_value["attribute"]["count"] = number of values for attribute
return_value["attribute"][0] = first value of the attribute
return_value["attribute"][i] = (i+1)th value of the attribute

Exemplo 1. Show the list of attributes held for a particular directory entry

// $ds is the link identifier for the directory

// $sr is a valid search result from a prior call to
// one of the ldap directory search calls

$entry = ldap_first_entry($ds, $sr);

$attrs = ldap_get_attributes($ds, $entry);

echo $attrs["count"]." attributes held for this entry:<p>";

for ($i=0; $i<$attrs["count"]; $i++)
    echo $attrs[$i]."<br>";

See also ldap_first_attribute() and ldap_next_attribute()

ldap_get_dn

(PHP 3, PHP 4 )

ldap_get_dn -- Get the DN of a result entry

Description

string ldap_get_dn ( resource link_identifier, resource result_entry_identifier)

Returns the DN of the result entry and FALSE on error.

ldap_get_dn() function is used to find out the DN of an entry in the result.

ldap_get_entries

(PHP 3, PHP 4 )

ldap_get_entries -- Get all result entries

Description

array ldap_get_entries ( resource link_identifier, resource result_identifier)

Returns a complete result information in a multi-dimenasional array on success and FALSE on error.

ldap_get_entries() function is used to simplify reading multiple entries from the result, specified with result_identifier, and then reading the attributes and multiple values. The entire information is returned by one function call in a multi-dimensional array. The structure of the array is as follows.

The attribute index is converted to lowercase. (Attributes are case-insensitive for directory servers, but not when used as array indices.)


return_value["count"] = number of entries in the result
return_value[0] : refers to the details of first entry

return_value[i]["dn"] =  DN of the ith entry in the result

return_value[i]["count"] = number of attributes in ith entry
return_value[i][j] = jth attribute in the ith entry in the result

return_value[i]["attribute"]["count"] = number of values for 
                                        attribute in ith entry
return_value[i]["attribute"][j] = jth value of attribute in ith entry

See also ldap_first_entry() and ldap_next_entry()

ldap_get_option

(PHP 4 >= 4.0.4)

ldap_get_option -- Get the current value for given option

Description

bool ldap_get_option ( resource link_identifier, int option, mixed retval)

Sets retval to the value of the specified option. Retorna TRUE em caso de sucesso ou FALSE em falhas.

The parameter option can be one of: LDAP_OPT_DEREF, LDAP_OPT_SIZELIMIT, LDAP_OPT_TIMELIMIT, LDAP_OPT_PROTOCOL_VERSION, LDAP_OPT_ERROR_NUMBER, LDAP_OPT_REFERRALS, LDAP_OPT_RESTART, LDAP_OPT_HOST_NAME, LDAP_OPT_ERROR_STRING, LDAP_OPT_MATCHED_DN. These are described in draft-ietf-ldapext-ldap-c-api-xx.txt

Nota: This function is only available when using OpenLDAP 2.x.x OR Netscape Directory SDK x.x, and was added in PHP 4.0.4

Exemplo 1. Check protocol version

// $ds is a valid link identifier for a directory server
if (ldap_get_option($ds, LDAP_OPT_PROTOCOL_VERSION, $version))
    echo "Using protocol version $version";
else
    echo "Unable to determine protocol version";

See also ldap_set_option().

ldap_get_values_len

(PHP 3>= 3.0.13, PHP 4 )

ldap_get_values_len -- Get all binary values from a result entry

Description

array ldap_get_values_len ( resource link_identifier, resource result_entry_identifier, string attribute)

Returns an array of values for the attribute on success and FALSE on error.

ldap_get_values_len() function is used to read all the values of the attribute in the entry in the result. entry is specified by the result_entry_identifier. The number of values can be found by indexing "count" in the resultant array. Individual values are accessed by integer index in the array. The first index is 0.

This function is used exactly like ldap_get_values() except that it handles binary data and not string data.

Nota: This function was added in 4.0.

ldap_get_values

(PHP 3, PHP 4 )

ldap_get_values -- Get all values from a result entry

Description

array ldap_get_values ( resource link_identifier, resource result_entry_identifier, string attribute)

Returns an array of values for the attribute on success and FALSE on error.

ldap_get_values() function is used to read all the values of the attribute in the entry in the result. entry is specified by the result_entry_identifier. The number of values can be found by indexing "count" in the resultant array. Individual values are accessed by integer index in the array. The first index is 0.

This call needs a result_entry_identifier, so needs to be preceded by one of the ldap search calls and one of the calls to get an individual entry.

You application will either be hard coded to look for certain attributes (such as "surname" or "mail") or you will have to use the ldap_get_attributes() call to work out what attributes exist for a given entry.

LDAP allows more than one entry for an attribute, so it can, for example, store a number of email addresses for one person's directory entry all labeled with the attribute "mail"


return_value["count"] = number of values for attribute
return_value[0] = first value of attribute
return_value[i] = ith value of attribute

Exemplo 1. List all values of the "mail" attribute for a directory entry

// $ds is a valid link identifier for a directory server

// $sr is a valid search result from a prior call to
//     one of the ldap directory search calls

// $entry is a valid entry identifier from a prior call to
//        one of the calls that returns a directory entry

$values = ldap_get_values($ds, $entry,"mail");

echo $values["count"]." email addresses for this entry.<p>";

for ($i=0; $i < $values["count"]; $i++)
    echo $values[$i]."<br>";

ldap_list

(PHP 3, PHP 4 )

ldap_list -- Single-level search

Description

resource ldap_list ( resource link_identifier, string base_dn, string filter [, array attributes [, int attrsonly [, int sizelimit [, int timelimit [, int deref]]]]])

Returns a search result identifier or FALSE on error.

ldap_list() performs the search for a specified filter on the directory with the scope LDAP_SCOPE_ONELEVEL.

LDAP_SCOPE_ONELEVEL means that the search should only return information that is at the level immediately below the base_dn given in the call. (Equivalent to typing "ls" and getting a list of files and folders in the current working directory.)

This call takes 5 optional parameters. See ldap_search() notes.

Nota: These optional parameters were added in 4.0.2: attrsonly, sizelimit, timelimit, deref.

Exemplo 1. Produce a list of all organizational units of an organization

// $ds is a valid link identifier for a directory server

$basedn = "o=My Company, c=US";
$justthese = array("ou");

$sr=ldap_list($ds, $basedn, "ou=*", $justthese);

$info = ldap_get_entries($ds, $sr);

for ($i=0; $i<$info["count"]; $i++)
    echo $info[$i]["ou"][0] ;

Nota: From 4.0.5 on it's also possible to do parallel searches. See ldap_search() for details.

ldap_mod_add

(PHP 3>= 3.0.8, PHP 4 )

ldap_mod_add -- Add attribute values to current attributes

Description

bool ldap_mod_add ( resource link_identifier, string dn, array entry)

Retorna TRUE em caso de sucesso ou FALSE em falhas.

This function adds attribute(s) to the specified dn. It performs the modification at the attribute level as opposed to the object level. Object-level additions are done by the ldap_add() function.

ldap_mod_del

(PHP 3>= 3.0.8, PHP 4 )

ldap_mod_del -- Delete attribute values from current attributes

Description

bool ldap_mod_del ( resource link_identifier, string dn, array entry)

Retorna TRUE em caso de sucesso ou FALSE em falhas.

This function removes attribute(s) from the specified dn. It performs the modification at the attribute level as opposed to the object level. Object-level deletions are done by the ldap_delete() function.

ldap_mod_replace

(PHP 3>= 3.0.8, PHP 4 )

ldap_mod_replace -- Replace attribute values with new ones

Description

bool ldap_mod_replace ( resoure link_identifier, string dn, array entry)

Retorna TRUE em caso de sucesso ou FALSE em falhas.

This function replaces attribute(s) from the specified dn. It performs the modification at the attribute level as opposed to the object level. Object-level modifications are done by the ldap_modify() function.

ldap_modify

(PHP 3, PHP 4 )

ldap_modify -- Modify an LDAP entry

Description

bool ldap_modify ( resource link_identifier, string dn, array entry)

Retorna TRUE em caso de sucesso ou FALSE em falhas.

ldap_modify() function is used to modify the existing entries in the LDAP directory. The structure of the entry is same as in ldap_add().

ldap_next_attribute

(PHP 3, PHP 4 )

ldap_next_attribute -- Get the next attribute in result

Description

string ldap_next_attribute ( resource link_identifier, resource result_entry_identifier, resource ber_identifier)

Returns the next attribute in an entry on success and FALSE on error.

ldap_next_attribute() is called to retrieve the attributes in an entry. The internal state of the pointer is maintained by the ber_identifier. It is passed by reference to the function. The first call to ldap_next_attribute() is made with the result_entry_identifier returned from ldap_first_attribute().

See also ldap_get_attributes()

ldap_next_entry

(PHP 3, PHP 4 )

ldap_next_entry -- Get next result entry

Description

resource ldap_next_entry ( resource link_identifier, resource result_entry_identifier)

Returns entry identifier for the next entry in the result whose entries are being read starting with ldap_first_entry(). If there are no more entries in the result then it returns FALSE.

ldap_next_entry() function is used to retrieve the entries stored in the result. Successive calls to the ldap_next_entry() return entries one by one till there are no more entries. The first call to ldap_next_entry() is made after the call to ldap_first_entry() with the result_entry_identifier as returned from the ldap_first_entry().

See also ldap_get_entries()

ldap_next_reference

(PHP 4 >= 4.0.5)

ldap_next_reference --  Get next reference

Description

resource ldap_next_reference ( resource link, resource entry)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ldap_parse_reference

(PHP 4 >= 4.0.5)

ldap_parse_reference --  Extract information from reference entry

Description

bool ldap_parse_reference ( resource link, resource entry, array referrals)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ldap_parse_result

(PHP 4 >= 4.0.5)

ldap_parse_result --  Extract information from result

Description

bool ldap_parse_result ( resource link, resource result, int errcode, string matcheddn, string errmsg, array referrals)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ldap_read

(PHP 3, PHP 4 )

ldap_read -- Read an entry

Description

resource ldap_read ( resource link_identifier, string base_dn, string filter [, array attributes [, int attrsonly [, int sizelimit [, int timelimit [, int deref]]]]])

Returns a search result identifier or FALSE on error.

ldap_read() performs the search for a specified filter on the directory with the scope LDAP_SCOPE_BASE. So it is equivalent to reading an entry from the directory.

An empty filter is not allowed. If you want to retrieve absolutely all information for this entry, use a filter of "objectClass=*". If you know which entry types are used on the directory server, you might use an appropriate filter such as "objectClass=inetOrgPerson".

This call takes 5 optional parameters. See ldap_search() notes.

Nota: These optional parameters were added in 4.0.2: attrsonly, sizelimit, timelimit, deref.

From 4.0.5 on it's also possible to do parallel searches. See ldap_search() for details.

ldap_rename

(PHP 4 >= 4.0.5)

ldap_rename -- Modify the name of an entry

Description

bool ldap_rename ( resource link_identifier, string dn, string newrdn, string newparent, bool deleteoldrdn)

The entry specified by dn is renamed/moved. The new RDN is specified by newrdn and the new parent/superior entry is specified by newparent. If the parameter deleteoldrdn is TRUE the old RDN value(s) is removed, else the old RDN value(s) is retained as non-distinguished values of the entry. Retorna TRUE em caso de sucesso ou FALSE em falhas.

Nota: This function currently only works with LDAPv3. You may have to use ldap_set_option() prior to binding to use LDAPv3. This function is only available when using OpenLDAP 2.x.x OR Netscape Directory SDK x.x, and was added in PHP 4.0.5.

ldap_search

(PHP 3, PHP 4 )

ldap_search -- Search LDAP tree

Description

resource ldap_search ( resource link_identifier, string base_dn, string filter [, array attributes [, int attrsonly [, int sizelimit [, int timelimit [, int deref]]]]])

Returns a search result identifier or FALSE on error.

ldap_search() performs the search for a specified filter on the directory with the scope of LDAP_SCOPE_SUBTREE. This is equivalent to searching the entire directory. base_dn specifies the base DN for the directory.

There is a optional fourth parameter, that can be added to restrict the attributes and values returned by the server to just those required. This is much more efficient than the default action (which is to return all attributes and their associated values). The use of the fourth parameter should therefore be considered good practice.

The fourth parameter is a standard PHP string array of the required attributes, eg array("mail","sn","cn") Note that the "dn" is always returned irrespective of which attributes types are requested.

Note too that some directory server hosts will be configured to return no more than a preset number of entries. If this occurs, the server will indicate that it has only returned a partial results set. This occurs also if the sixth parameter sizelimit has been used to limit the count of fetched entries.

The fifth parameter attrsonly should be set to 1 if only attribute types are wanted. If set to 0 both attributes types and attribute values are fetched which is the default behaviour.

With the sixth parameter sizelimit it is possible to limit the count of entries fetched. Setting this to 0 means no limit. NOTE: This parameter can NOT override server-side preset sizelimit. You can set it lower though.

The seventh parameter timelimit sets the number of seconds how long is spend on the search. Setting this to 0 means no limit. NOTE: This parameter can NOT override server-side preset timelimit. You can set it lower though.

The eigth parameter deref specifies how aliases should be handled during the search. It can be one of the following:

  • LDAP_DEREF_NEVER - (default) aliases are never dereferenced.

  • LDAP_DEREF_SEARCHING - aliases should be dereferenced during the search but not when locating the base object of the search.

  • LDAP_DEREF_FINDING - aliases should be dereferenced when locating the base object but not during the search.

  • LDAP_DEREF_ALWAYS - aliases should be dereferenced always.

Nota: These optional parameters were added in 4.0.2: attrsonly, sizelimit, timelimit, deref.

The search filter can be simple or advanced, using boolean operators in the format described in the LDAP doumentation (see the Netscape Directory SDK for full information on filters).

The example below retrieves the organizational unit, surname, given name and email address for all people in "My Company" where the surname or given name contains the substring $person. This example uses a boolean filter to tell the server to look for information in more than one attribute.

Exemplo 1. LDAP search

// $ds is a valid link identifier for a directory server

// $person is all or part of a person's name, eg "Jo"

$dn = "o=My Company, c=US";
$filter="(|(sn=$person*)(givenname=$person*))";
$justthese = array( "ou", "sn", "givenname", "mail");

$sr=ldap_search($ds, $dn, $filter, $justthese);

$info = ldap_get_entries($ds, $sr);

print $info["count"]." entries returned<p>";

From 4.0.5 on it's also possible to do parallel searches. To do this you use an array of link identifiers, rather than a single identifier, as the first argument. If you don't want the same base DN and the same filter for all the searches, you can also use an array of base DNs and/or an array of filters. Those arrays must be of the same size as the link identifier array since the first entries of the arrays are used for one search, the second entries are used for another, and so on. When doing parallel searches an array of search result identifiers is returned, except in case of error, then the entry corresponding to the search will be FALSE. This is very much like the value normally returned, except that a result identifier is always returned when a search was made. There are some rare cases where the normal search returns FALSE while the parallel search returns an identifier.

ldap_set_option

(PHP 4 >= 4.0.4)

ldap_set_option -- Set the value of the given option

Description

bool ldap_set_option ( resource link_identifier, int option, mixed newval)

Sets the value of the specified option to be newval. Retorna TRUE em caso de sucesso ou FALSE em falhas. on error.

The parameter option can be one of: LDAP_OPT_DEREF, LDAP_OPT_SIZELIMIT, LDAP_OPT_TIMELIMIT, LDAP_OPT_PROTOCOL_VERSION, LDAP_OPT_ERROR_NUMBER, LDAP_OPT_REFERRALS, LDAP_OPT_RESTART, LDAP_OPT_HOST_NAME, LDAP_OPT_ERROR_STRING, LDAP_OPT_MATCHED_DN, LDAP_OPT_SERVER_CONTROLS, LDAP_OPT_CLIENT_CONTROLS. Here's a brief description, see draft-ietf-ldapext-ldap-c-api-xx.txt for details.

The options LDAP_OPT_DEREF, LDAP_OPT_SIZELIMIT, LDAP_OPT_TIMELIMIT, LDAP_OPT_PROTOCOL_VERSION and LDAP_OPT_ERROR_NUMBER have integer value, LDAP_OPT_REFERRALS and LDAP_OPT_RESTART have boolean value, and the options LDAP_OPT_HOST_NAME, LDAP_OPT_ERROR_STRING and LDAP_OPT_MATCHED_DN have string value. The first example illustrates their use. The options LDAP_OPT_SERVER_CONTROLS and LDAP_OPT_CLIENT_CONTROLS require a list of controls, this means that the value must be an array of controls. A control consists of an oid identifying the control, an optional value, and an optional flag for criticality. In PHP a control is given by an array containing an element with the key oid and string value, and two optional elements. The optional elements are key value with string value and key iscritical with boolean value. iscritical defaults to FALSE if not supplied. See also the second example below.

Nota: This function is only available when using OpenLDAP 2.x.x OR Netscape Directory SDK x.x, and was added in PHP 4.0.4.

Exemplo 1. Set protocol version

// $ds is a valid link identifier for a directory server
if (ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3))
    echo "Using LDAPv3";
else
    echo "Failed to set protocol version to 3";

Exemplo 2. Set server controls

// $ds is a valid link identifier for a directory server
// control with no value
$ctrl1 = array("oid" => "1.2.752.58.10.1", "iscritical" => TRUE);
// iscritical defaults to FALSE
$ctrl2 = array("oid" => "1.2.752.58.1.10", "value" => "magic");
// try to set both controls
if (!ldap_set_option($ds, LDAP_OPT_SERVER_CONTROLS, array($ctrl1, $ctrl2)))
    echo "Failed to set server controls";

See also ldap_get_option().

ldap_set_rebind_proc

(PHP 4 >= 4.2.0)

ldap_set_rebind_proc --  Set a callback function to do re-binds on referral chasing.

Description

bool ldap_set_rebind_proc ( resource link, string callback)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ldap_sort

(PHP 4 >= 4.2.0)

ldap_sort --  Sort LDAP result entries

Description

bool ldap_sort ( resource link, resource result, string sortfilter)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ldap_start_tls

(PHP 4 >= 4.2.0)

ldap_start_tls --  Start TLS

Description

bool ldap_start_tls ( resource link)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ldap_t61_to_8859

(PHP 4 >= 4.0.2)

ldap_t61_to_8859 --  Translate t61 characters to 8859 characters

Description

string ldap_t61_to_8859 ( string value)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ldap_unbind

(PHP 3, PHP 4 )

ldap_unbind -- Unbind from LDAP directory

Description

bool ldap_unbind ( resource link_identifier)

Retorna TRUE em caso de sucesso ou FALSE em falhas.

ldap_unbind() function unbinds from the LDAP directory.

XLIX. Funções de E-Mail

Introdução

A função mail() te permite enviar email


Requisitos

Nenhuma biblioteca externa é necessária para compilar esta extensão.


Instalação

Não há nenhuma instalação nescessária para utilizar estas funções, elas fazem parte do núcleo do PHP.


Configuração durante execução

Diretivas de configuração para Mail

SMTP string

Apenas para usuários de Windows: PHP usaria nome DNS ou endereço IP do servidor SMTP para enviar email com a função mail().

SMTP int

Apenas usuários de Windows: Número da porta para conectar ao servidor especificado com a configuração de SMTP quando enviando mail com mail(); por definição 25. Apenas disponível desde PHP 4.3.0.

sendmail_from string

O "From:" endereço de email seria usado no envio de PHP em Windows.

sendmail_path string

Onde o programa sendmail pode ser encontrado, geralmente /usr/sbin/sendmail ou /usr/lib/sendmail configure faz uma tentativa de localiza-lo para você e define um path padrão, mas se falhar, você pode defini-lo aqui.

Sistemas não utilizando sendmail definiriam esta diretiva para sendmail wrapper/replacement deles. Por exemplo, Qmail usuários pode normalmente definí-los para /var/qmail/bin/sendmail ou /var/qmail/bin/qmail-inject.

qmail-inject não requer qualquer opção para processar o mail corretamente.


Tipos Resource

Esta extensão não possui nenhum tipo resource.


Constantes Predefinidas

Esta extensão não possui nenhuma constante.

Índice
ezmlm_hash -- Calcula o valor do hash necessário para EZMLM
mail -- Envia email

ezmlm_hash

(PHP 3>= 3.0.17, PHP 4 >= 4.0.2)

ezmlm_hash -- Calcula o valor do hash necessário para EZMLM

Descrição

int ezmlm_hash ( string addr)

ezmlm_hash() calcula valor do hash necessário quando mantendo listas de email EZMLM num banco de dados MySQL .

Exemplo 1. Calculando o hash e inscrevendo um usuário

$user = "joecool@example.com";
$hash = ezmlm_hash ($user);
$query = sprintf ("INSERT INTO sample VALUES (%s, '%s')", $hash, $user);
$db->query($query); // using PHPLIB db interface

mail

(PHP 3, PHP 4 )

mail -- Envia email

Descrição

bool mail ( string to, string subject, string message [, string additional_headers [, string additional_parameters]])

mail() automaticamente envia a mensagem especificada em message para o destinatário especificado em to. Destinatários múltiplos podem podem ser especificados colocando uma vírgula entre cada endereço em to. Email com anexos e tipos de conteúdo especiais podem ser enviados usando esta função. Esta é completada via MIME-encoding- para mais informações, veja Zend article or the PEAR Mime Classes.

Os seguintes RFC's pode ser úteis: RFC 1896, RFC 2045, RFC 2046, RFC 2047, RFC 2048, and RFC 2049.

mail() retorna TRUE se o email enviado foi aceito para entrega, do contrário FALSE.

Atenção

A implentação do Windows de mail() difere bastante da implentação Unix. Primeiro, ele não usa um binary local para compor mensagens mas apenas opera com sockets diretos o que significa que uma MTA é necessária prestando atenção num socket de rede (que pode ser ou o localhost ou uma máquina remota). Segundo, os cabeçalhos personalizados como From:, Cc:, Bcc: e Date: são not interpretados por MTA em primeiro lugar, mas são analizados pelo PHP. PHP < 4.3 somente elementos suportados Cc: elemento de cabeçalho (e foi caso-sensitivo). PHP >= 4.3 suporta todos os elementos de cabeçalho suportados e não distante caso-sensitivo.

Exemplo 1. Enviando email.

mail("joecool@example.com", "My Subject", "Line 1\nLine 2\nLine 3");

Se uma string como quarto argumento é passada, esta string é insrida no fim do cabeçalho. É usado tipicamente para adicionar cabeçalhos extras. Cabeçalhos extras múltiplos são separados com sinal de retorno e novalinha.

Nota: Você deve utilizar \r\n para separar headers, embora alguns agentes de transferência de email Unix mail podem trabalhar com uma simples linha somente (\n).

Exemplo 2. Enviando email com cabeçalhos extras.

mail("nobody@example.com", "the subject", $message,
     "From: webmaster@$SERVER_NAME\r\n"
    ."Reply-To: webmaster@$SERVER_NAME\r\n"
    ."X-Mailer: PHP/" . phpversion());

O parâmetro additional_parameters pode ser usado para passar parâmetros adicionais para o programa configurado para usar quando enviar email usando a definição de configuração sendmail_path. Por exemplo, isto pode ser usado para definir o endereço do envelope remetente quando usar sendmail. Você pode precisar adicionar o usuário que seu servidor web executa como para sua configuração de sendmail para evitar que um cabeçalho 'X-Warning' seja adicionado á mensagem quando você define o envelope remetente usando este método.

Exemplo 3. Enviando email com cabeçalhos extras e definindo um parâmetro de uma linha de comando adicional.

mail("nobody@example.com", "the subject", $message,
     "From: webmaster@$SERVER_NAME", "-fwebmaster@$SERVER_NAME");

Nota: O quinto parâmetro foi adicionado no PHP 4.0.5.

Você pode utilizar strings simples utilizando técnicas para construir mensagens complexas.

Exemplo 4. Enviando email complexo.

/* recipients */
$to  = "Mary <mary@example.com>" . ", " ; //note the comma
$to .= "Kelly <kelly@example.com>";

/* subject */
$subject = "Birthday Reminders for August";

/* message */
$message = '
<html>
<head>
 <title>Birthday Reminders for August</title>
</head>
<body>
<p>Here are the birthdays upcoming in August!</p>
<table>
 <tr>
  <th>Person</th><th>Day</th><th>Month</th><th>Year</th>
 </tr>
 <tr>
  <td>Joe</td><td>3rd</td><td>August</td><td>1970</td>
 </tr>
 <tr>
  <td>Sally</td><td>17th</td><td>August</td><td>1973</td>
 </tr>
</table>
</body>
</html>
';

/* To send HTML mail, you can set the Content-type header. */
$headers  = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";

/* additional headers */
$headers .= "From: Birthday Reminder <birthday@example.com>\r\n";

$headers .= "Cc: birthdayarchive@example.com\r\n";
$headers .= "Bcc: birthdaycheck@example.com\r\n";

/* and now mail it */
mail($to, $subject, $message, $headers);

Nota: Certifique-se que você não tem nenhum caractere novalinha em to ou subject, ou o email não será enviado corretamente.

L. mailparse functions

Introdução

Atenção

Este módulo é EXPERIMENTAL. Isso quer dizer que o comportamento neste módulo --- incluindo suas funções e seus nomes, e TUDO mais que está documentado sobre esse módulo --- poderá mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use este módulo por sua própria conta e risco.

Índice
mailparse_determine_best_xfer_encoding --  Figures out the best way of encoding the content read from the file pointer fp, which must be seek-able
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 --  Extracts/decodes a message section. If callbackfunc is not specified, the contents will be sent to "stdout"
mailparse_msg_free -- Frees a handle allocated by mailparse_msg_crea
mailparse_msg_get_part_data -- Returns an associative array of info about the message
mailparse_msg_get_part -- Returns a handle on a given section in a mimemessage
mailparse_msg_get_structure -- Returns an array of mime section names in the supplied message
mailparse_msg_parse_file -- Parse file and return a resource representing the structure
mailparse_msg_parse -- Incrementally parse data into buffer
mailparse_rfc822_parse_addresses --  Parse addresses and returns a hash containing that data
mailparse_stream_encode --  Streams data from source file pointer, apply encoding and write to destfp
mailparse_uudecode_all --  Scans the data from fp and extract each embedded uuencoded file. Returns an array listing filename information

mailparse_determine_best_xfer_encoding

(4.1.0 - 4.1.2 only)

mailparse_determine_best_xfer_encoding --  Figures out the best way of encoding the content read from the file pointer fp, which must be seek-able

Description

int mailparse_determine_best_xfer_encoding ( resource fp)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mailparse_msg_create

(4.1.0 - 4.1.2 only)

mailparse_msg_create -- Returns a handle that can be used to parse a message

Description

int mailparse_msg_create ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mailparse_msg_extract_part_file

(4.1.0 - 4.1.2 only)

mailparse_msg_extract_part_file -- Extracts/decodes a message section, decoding the transfer encoding

Description

string mailparse_msg_extract_part_file ( resource rfc2045, string filename [, string callbackfunc])

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mailparse_msg_extract_part

(4.1.0 - 4.1.2 only)

mailparse_msg_extract_part --  Extracts/decodes a message section. If callbackfunc is not specified, the contents will be sent to "stdout"

Description

void mailparse_msg_extract_part ( resource rfc2045, string msgbody [, string callbackfunc])

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mailparse_msg_free

(4.1.0 - 4.1.2 only)

mailparse_msg_free -- Frees a handle allocated by mailparse_msg_crea

Description

void mailparse_msg_free ( resource rfc2045buf)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mailparse_msg_get_part_data

(4.1.0 - 4.1.2 only)

mailparse_msg_get_part_data -- Returns an associative array of info about the message

Description

array mailparse_msg_get_part_data ( resource rfc2045)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mailparse_msg_get_part

(4.1.0 - 4.1.2 only)

mailparse_msg_get_part -- Returns a handle on a given section in a mimemessage

Description

int mailparse_msg_get_part ( resource rfc2045, string mimesection)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mailparse_msg_get_structure

(4.1.0 - 4.1.2 only)

mailparse_msg_get_structure -- Returns an array of mime section names in the supplied message

Description

array mailparse_msg_get_structure ( resource rfc2045)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mailparse_msg_parse_file

(4.1.0 - 4.1.2 only)

mailparse_msg_parse_file -- Parse file and return a resource representing the structure

Description

resource mailparse_msg_parse_file ( string filename)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mailparse_msg_parse

(4.1.0 - 4.1.2 only)

mailparse_msg_parse -- Incrementally parse data into buffer

Description

void mailparse_msg_parse ( resource rfc2045buf, string data)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mailparse_rfc822_parse_addresses

(4.1.0 - 4.1.2 only)

mailparse_rfc822_parse_addresses --  Parse addresses and returns a hash containing that data

Description

array mailparse_rfc822_parse_addresses ( string addresses)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mailparse_stream_encode

(4.1.0 - 4.1.2 only)

mailparse_stream_encode --  Streams data from source file pointer, apply encoding and write to destfp

Description

bool mailparse_stream_encode ( resource sourcefp, resource destfp, string encoding)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mailparse_uudecode_all

(no version information, might be only in CVS)

mailparse_uudecode_all --  Scans the data from fp and extract each embedded uuencoded file. Returns an array listing filename information

Description

array mailparse_uudecode_all ( resource fp)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

LI. Matemática e Trigonometria

Introdução

Estas funções matemáticas somente suportam valores dentro do tamanho integer and float do seu computador. (estes correspondem atualmente aos tipos do C long e double) Se você precisa manipular números maiores, procure funções de matemática com precisão arbitrária.


Requisitos

Nenhuma biblioteca externa é necessária para compilar esta extensão.


Instalação

Não há nenhuma instalação nescessária para utilizar estas funções, elas fazem parte do núcleo do PHP.


Configuração durante execução

Esta extenção não define nenhum parâmetro de configuração no php.ini.


Tipos Resource

Esta extensão não possui nenhum tipo resource.


Constantes Predefinidas

As constantes listadas abaixo estão sempre disponíveis como parte do núcleo do PHP.

Tabela 1. Constantes matemáticas

Constante Valor Descrição
M_PI 3.14159265358979323846 Pi
M_E 2.7182818284590452354 e
M_LOG2E 1.4426950408889634074 log_2 e
M_LOG10E 0.43429448190325182765 log_10 e
M_LN2 0.69314718055994530942 log_e 2
M_LN10 2.30258509299404568402 log_e 10
M_PI_2 1.57079632679489661923 pi/2
M_PI_4 0.78539816339744830962 pi/4
M_1_PI 0.31830988618379067154 1/pi
M_2_PI 0.63661977236758134308 2/pi
M_SQRTPI 1.77245385090551602729 raiz_quadrada(pi) [4.0.2]
M_2_SQRTPI 1.12837916709551257390 2/raiz_quadrada(pi)
M_SQRT2 1.41421356237309504880 raiz_quadrada(2)
M_SQRT3 1.73205080756887729352 raiz_quadrada(3) [4.0.2]
M_SQRT1_2 0.70710678118654752440 1/raiz_quadrada(2)
M_LNPI 1.14472988584940017414 log_e(pi) [4.0.2]
M_EULER 0.57721566490153286061 Constante de Euler [4.0.2]
Somente M_PI está disponível nas versões do PHP anteriores a 4.0.0, inclusive. Todas as outras constantes foram disponibilizadas a partir da 4.0.0. Constantes marcadas com [4.0.2] foram acrescentadas no PHP 4.0.2.

Índice
abs -- Valor absoluto
acos -- Cosseno Inverso (arco cosseno)
acosh -- Coseno Hiperbólico Inverso
asin -- Seno Inverso (arco seno)
asinh -- Seno Hiperbólico Inverso
atan2 -- Tangente inversa de duas variáveis
atan -- Tangente Inversa (arco tangente)
atanh -- Tangente hiperbólica inversa
base_convert -- Converte um número entre bases arbitrárias
bindec -- Binário para decimal
ceil -- Arredonda frações para cima
cos -- Coseno
cosh -- Coseno hiperbólico
decbin -- Decimal para binário
dechex -- Decimal para hexadecimal
decoct -- Decimal para octal
deg2rad --  Converte o número em graus ao equivalente em radianos
exp -- Calcula o expoente de e (Neperiano ou base logarítmica natural)
expm1 --  Retorna exp(numero) - 1, computado de forma que é preciso mesmo quando o valor do número é perto de zero.
floor -- Arredonda frações para baixo
fmod -- Returns the floating point remainder (modulo) of the division of the arguments
getrandmax -- Retorna o maior valor aletório possível
hexdec -- Hexadecimal para decimal
hypot --  Retorna a raiz quadrada de (num1*num1 + num2*num2)
is_finite -- 
is_infinite -- 
is_nan -- 
lcg_value -- Gerador congruente linear combinado
log10 -- Logaritmo Base 10
log1p --  Retorna o log(1 + numero), calculado de forma que o valor do número seja próximo de zero.
log -- Logaritmo natural
max -- Localiza o maior número
min -- Localiza o menor número
mt_getrandmax -- Retorna o maior valor aletório possível
mt_rand -- Gerador melhorado de números aleatórios
mt_srand -- Semeia o gerador melhorado de números aleatórios
octdec -- Octal para decimal
pi -- Obtêm o valor de pi
pow -- Potência
rad2deg --  Converte o número em radianos para o equivalente em graus
rand -- Gera um número aleatório
round -- Arredonda um número
sin -- Seno
sinh -- Seno hiperbólico
sqrt -- Raiz quadrada
srand -- Semeia o gerador de números aletórios
tan -- Tangente
tanh -- Tangente hiperbólica

abs

(PHP 3, PHP 4 )

abs -- Valor absoluto

Descrição

mixed abs ( mixed número)

Retorna o valor absoluto de um número. Se o argumento número é do tipo float, o número retornado também é float, em outro caso será inteiro (mas poderá retornar float se o resultado tiver magnitude maior que inteiro).

Exemplo 1. exemplo de abs()

$abs = abs(-4.2); // $abs = 4.2; (double/float)
$abs2 = abs(5);   // $abs2 = 5; (inteiro)
$abs3 = abs(-5);  // $abs3 = 5; (inteiro)

acos

(PHP 3, PHP 4 )

acos -- Cosseno Inverso (arco cosseno)

Descrição

float acos ( float arg)

Retorna o inverso do coseno de arg em radianos. acos() é a função complementar de cos(), o que significa que a==cos(acos(a)) para qualquer valor de var que esteja dentro dos limites de acos().

Veja também acosh(), asin() e atan().

acosh

(PHP 4 >= 4.1.0)

acosh -- Coseno Hiperbólico Inverso

Descrição

float acosh ( float arg)

Retorna o coseno hiperbólico de arg, isto é, o valor cujo coseno hiperbólico é arg.

Nota: esta função não é implementada na plataforma Windows

Veja também acos(), asinh() e atanh().

asin

(PHP 3, PHP 4 )

asin -- Seno Inverso (arco seno)

Descrição

float asin ( float arg)

Retorna o inverso do seno de arg em radianos. asin() é a função complementar de sin(), o que significa que a==sin(asin(a)) para qualquer valor de var que esteja dentro dos limites de asin().

Veja também asinh(), acos() e atan().

asinh

(PHP 4 >= 4.1.0)

asinh -- Seno Hiperbólico Inverso

Descrição

float asinh ( float arg)

Retorna o inverso do seno hiperbólico de arg, isto é, o valor cujo seno hiperbólico é arg.

Nota: esta função não é implementada na plataforma Windows

Veja também asin(), acosh() e atanh().

atan2

(PHP 3>= 3.0.5, PHP 4 )

atan2 -- Tangente inversa de duas variáveis

Descrição

float atan2 ( float y, float x)

Esta função calcula a tangente inversa de duas variaveis x e y. Esta função é o equivalente a calcular a tangente inversa de y / x, exceto que os sinais de ambos os argumentos são usados para determinar o quadrante do resultado.

Esta função retorna o resultado em radianos, estando entre -PI e PI (inclusive).

Veja também acos() e atan().

atan

(PHP 3, PHP 4 )

atan -- Tangente Inversa (arco tangente)

Descrição

float atan ( float arg)

Retorna o inverso da tangente de arg em radianos. atan() é a função complementar de tan(), o que significa que var == tan(atan(var)) para qualquer valor de a que esteja dentro dos limites de atan().

Veja também atanh(), asin() e acos().

atanh

(PHP 4 >= 4.1.0)

atanh -- Tangente hiperbólica inversa

Descrição

float atanh ( float arg)

Retorna a tangente hiperbólica inversa de arg, isto é, o valor cuja tangente hiperbólica é arg.

Nota: esta função não é implementada na plataforma Windows

Veja também atan(), asinh() e acosh().

base_convert

(PHP 3>= 3.0.6, PHP 4 )

base_convert -- Converte um número entre bases arbitrárias

Descrição

string base_convert ( string number, int frombase, int tobase)

Retorna uma string contendo number representado na base tobase. A base atual de number é especificada em frombase. Tanto frombase quanto tobase tem que estar entre 2 e 36, inclusive. Digitos em números com base maior do que 10 serão representados com letras a-z, com a significando 10, b significando 11 e z significando 35.

Exemplo 1. base_convert()

$binary = base_convert ($hexadecimal, 16, 2);

bindec

(PHP 3, PHP 4 )

bindec -- Binário para decimal

Descrição

int bindec ( string binary_string)

Retorna o equivalente decimal do número binário representado pelo argumento binary_string.

bindec() converte um número binário em um integer. O maior número que pode ser convertido é 31 bits de ums (1) ou 2147483647 em decimal.

Veja também a função decbin().

ceil

(PHP 3, PHP 4 )

ceil -- Arredonda frações para cima

Descrição

float ceil ( float valor)

Retorna o próximo maior valor inteiro arredondando para cima do valor, se fracionário. O valor retornado de ceil() é do tipo float porque a dimensão dos valores suportados por float é normalmente maior do que o do tipo int.

Exemplo 1. exemplos ceil()

echo ceil(4.3);    // 5
echo ceil(9.999);  // 10

Veja também floor() e round().

cos

(PHP 3, PHP 4 )

cos -- Coseno

Descrição

float cos ( float arg)

cos() retorna o coseno de arg. O parametro arg deve estar em radianos.

Veja também acos(), sin() tan() e deg2rad().

cosh

(PHP 4 >= 4.1.0)

cosh -- Coseno hiperbólico

Descrição

float cosh ( float arg)

Retorna o coseno hiperbólico de arg, definido por (exp(arg) + exp(-arg))/2.

Veja também cos(), acosh(), sin() e tan().

decbin

(PHP 3, PHP 4 )

decbin -- Decimal para binário

Descrição

string decbin ( int numero)

Retorna uma string contendo a representação binária do parâmetro numero. O maior número que pode ser convertido é 4294967295 em decimal, resultando em uma strings de 32 números 1.

Veja também a função bindec().

dechex

(PHP 3, PHP 4 )

dechex -- Decimal para hexadecimal

Descrição

string dechex ( int numero)

Retorna uma string contendo a representação hexadecimal do argumento numero. O maior número que pode ser convertido é 2147483647 em decimal, resultando em "7fffffff".

Veja também hexdec().

decoct

(PHP 3, PHP 4 )

decoct -- Decimal para octal

Descrição

string decoct ( int numero)

Retorna uma string contendo a representação octal do parâmetro numero. O maior número que pode ser convertido é 2147483647 em decimal, resultando em "17777777777".

Veja também octdec().

deg2rad

(PHP 3>= 3.0.4, PHP 4 )

deg2rad --  Converte o número em graus ao equivalente em radianos

Descrição

float deg2rad ( float numero)

Esta função converte numero de graus ao equivalente em radianos.

Veja também rad2deg().

exp

(PHP 3, PHP 4 )

exp -- Calcula o expoente de e (Neperiano ou base logarítmica natural)

Descrição

float exp ( float arg)

Retorna e a potência de arg.

Veja também pow().

expm1

(PHP 4 >= 4.1.0)

expm1 --  Retorna exp(numero) - 1, computado de forma que é preciso mesmo quando o valor do número é perto de zero.

Descrição

float expm1 ( float numero)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

floor

(PHP 3, PHP 4 )

floor -- Arredonda frações para baixo

Descrição

float floor ( float valor)

Retorna o próximo menor valor inteiro ao se arredondar para baixo o valor, se necessário. O valor retornado de floor() é do tipo float porque o tipo float normalmente abrange mais números possíveis do que integer.

Exemplo 1. exemplos de floor()

echo floor(4.3);   // 4
echo floor(9.999); // 9

Veja também ceil() e round().

fmod

(PHP 4 >= 4.2.0)

fmod -- Returns the floating point remainder (modulo) of the division of the arguments

Description

float fmod ( float x, float y)

Returns the floating point remainder of dividing the dividend (x) by the divisor (y). The reminder (r) is defined as: x = i * y + r, for some integer i. If y is non-zero, r has the same sign as x and a magnitude less than the magnitude of y.

Exemplo 1. Using fmod()

$x = 5.7;
$y = 1.3;
$r = fmod($x, $y);
// $r equals 0.5, because 4 * 1.3 + 0.5 = 5.7

getrandmax

(PHP 3, PHP 4 )

getrandmax -- Retorna o maior valor aletório possível

Descrição

int getrandmax ( void)

Retorna o valor máximo que pode ser gerado em uma chamada a função rand().

Veja também rand(), srand() e mt_getrandmax().

hexdec

(PHP 3, PHP 4 )

hexdec -- Hexadecimal para decimal

Descrição

int hexdec ( string hex_string)

Retorna o decimal equivalente do número hexadecimal representado pelo argumento hex_string. hexdec() converte uma string hexadecimal para um número decimal. O maior número que pode ser convertido é 7fffffff (ou 2147483647 em decimal).

hexdec() substituirá qualquer caracter não hexadecimal que encontrar por 0. Desta forma, todos os zeros a esqueda são ignorados, mas zeros a direita serão avaliados.

Exemplo 1. exemplos hexdec()

var_dump(hexdec("See"));
var_dump(hexdec("ee"));
// ambos exibem "int(238)"

var_dump(hexdec("that"));
var_dump(hexdec("a0"));
// ambos exibem int(160)

Veja também dechex().

hypot

(PHP 4 >= 4.1.0)

hypot --  Retorna a raiz quadrada de (num1*num1 + num2*num2)

Descrição

float hypot ( float num1, float num2)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

is_finite

(PHP 4 >= 4.2.0)

is_finite -- 

Descrição

bool is_finite ( float val)

Retorna TRUE se val é número finito legal dentro dos limites permitidos para um número float PHP nesta plataforma.

is_infinite

(PHP 4 >= 4.2.0)

is_infinite -- 

Descrição

bool is_infinite ( float val)

Retorna TRUE se val é infinito (positivo ou negativo), como por exemplo o resultado de log(0) ou qualquer outro valor muito grande para caber num float desta plataforma.

is_nan

(PHP 4 >= 4.2.0)

is_nan -- 

Descrição

bool is_nan ( float val)

Retona TRUE se val 'não for um número', como o resultado de acos(1.01).

lcg_value

(PHP 4 )

lcg_value -- Gerador congruente linear combinado

Descrição

float lcg_value ( void)

lcg_value() retorna um pseudo número aleatório nos limites de (0, 1). A função combina duas congruências geradas, com períodos de 2^31 - 85 e 2^31 - 249. O período desta função é igual ao produto de ambos os primos.

log10

(PHP 3, PHP 4 )

log10 -- Logaritmo Base 10

Descrição

float log10 ( float arg)

Retorna o logaritmo na base 10 de arg.

log1p

(PHP 4 >= 4.1.0)

log1p --  Retorna o log(1 + numero), calculado de forma que o valor do número seja próximo de zero.

Descrição

float log1p ( float number)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

log

(PHP 3, PHP 4 )

log -- Logaritmo natural

Descrição

float log ( float arg)

Retorna o logaritmo natural de arg.

max

(PHP 3, PHP 4 )

max -- Localiza o maior número

Descrição

mixed max ( mixed arg1, mixed arg2, mixed argn)

max() retorna o maior número dos parâmetros.

Se o primeiro parâmetro é um array, max() retorna o maior valor do array. Se o primeiro parâmetro é um inteiro, string ou float, você precisa informar pelo menos dois parâmetros, e max() retornará o maior desses números. Você pode comparar uma quantidade ilimitada de números.

Se um ou mais dos valores forem float, todos os valores serão tratados como floats, e um float será retornado. Se nenhum dos valores for float, todos serão tratados como inteiros, e um inteiro é retornado.

min

(PHP 3, PHP 4 )

min -- Localiza o menor número

Descrição

number min ( number arg1, number arg2 [, ...])

number min ( array numbers)

min() retorna o menor número dos parâmetros.

Na primeira variante, você precisa pelo menos dois parâmetros, e min() retornará o menor desses valores. Você pode comparar um número ilimitado de valores. Se uma das variáveis é indefinida, min() falhará.

Na segunda variante, min() retorna o menor dos valores em numbers.

Se um ou mais dos valores for um float, todos os valores serão tratados como floats, e um float será retornado. Se nenhum dos valores é um float, todos eles serão tratados como inteiros, e um inteiro será retornado. Em caso de falha, min() retorna NULL e um erro nível E_WARNING é registrado

<?php
$a = 4;
$b = 9;
$c = 3;
$arr = array(99, 34, 11);

// Você pode querer implementar sua própria checagem
// no caso de falha (uma variável pode não existir)
if (!$min_value = @min($a, $b, $c)) {
    echo "Não pude obter o menor valor, tente novamente.";
} else {
    echo "O menor valor é $min_value";
}

print min($arr);  // Exibe 11

?>

Veja também max().

mt_getrandmax

(PHP 3>= 3.0.6, PHP 4 )

mt_getrandmax -- Retorna o maior valor aletório possível

Descrição

int mt_getrandmax ( void)

Retorna o maior valor que pode ser obtido numa chamada a mt_rand().

Veja também mt_rand(), mt_srand() e getrandmax().

mt_rand

(PHP 3>= 3.0.6, PHP 4 )

mt_rand -- Gerador melhorado de números aleatórios

Descrição

int mt_rand ( [int min, int max])

Muitos geradores de números aleatórios das libcs antigas são duvidosos ou com características duvidosas e lentos. Por default, o PHP utiliza o gerador de números aleatórios da libc para a função rand(). A função mt_rand() é um bom substituto para a primeira. Ela utiliza um gerador de números aleatórios com características conhecidas, o Mersenne Twister, que produzirá números randômicos que podem ser utilizados como sementes em alguns tipos de criptografia e é em média quatro vezes mais rápido do que o fornecido pela libc.

Se chamada sem os argumentos opcionais min e max, mt_rand() retorna um pseudo número aletório enrte 0 e RAND_MAX. se você precisa de um número randômico entre 5 e 15 (inclusive), por exemplo, utilize mt_rand (5, 15).

Em versões anteriores do PHP, você tem que semear o gerador de números randômicos primerio com mt_srand(). Desde o PHP 4.2.0, isto não é mais necessário.

Nota: Em versões anteriores a 3.0.7, o significado do parâmetro max era range. Assim, para obter os mesmos resultados do exemplo acima, você precisaria utilizar rand (5, 11) para obter um número aleatório entre 5 e 15.

Veja também mt_srand(), mt_getrandmax() e rand().

mt_srand

(PHP 3>= 3.0.6, PHP 4 )

mt_srand -- Semeia o gerador melhorado de números aleatórios

Deszcrição

void mt_srand ( int seed)

Semeia o gerador de números aleatórios com seed.

// semente de microsegundos
function make_seed() {
    list($usec, $sec) = explode(' ', microtime());
    return (float) $sec + ((float) $usec * 100000);
}
mt_srand(make_seed());
$randval = mt_rand();

Nota: Desde o PHP 4.2.0 não é mais necessário semear o gerador de números aleatórios antes de usá-lo.

Veja também mt_rand(), mt_getrandmax() e srand().

octdec

(PHP 3, PHP 4 )

octdec -- Octal para decimal

Descrição

int octdec ( string octal_string)

Retornar o decimal equivalente do número octal representado pelo argumento octal_string. O maior número que pode ser convertido é 17777777777 ou 2147483647 em decimal.

Veja também decoct().

pi

(PHP 3, PHP 4 )

pi -- Obtêm o valor de pi

Descrição

float pi ( void)

Retorna o valor aproximado de Pi. O valor retornado float tem a precisão baseada na diretiva precision do php.ini, que tem por padrão 14. Também é possivel usar a constante M_PI que terá resultados idênticos a pi().

echo pi(); // 3.1415926535898
echo M_PI; // 3.1415926535898

pow

(PHP 3, PHP 4 )

pow -- Potência

Descrição

number pow ( number base, number exp)

Retorna a base elevada ao expoente exp. Se possível, esta função retornará um integer.

Se a potência não puder ser calculada, um alerta será lançado, e pow() retornará FALSE.

Exemplo 1. Alguns exemplos de pow()

<?php

var_dump( pow(2,8) ); // int(256)
echo pow(-1,20); // 1
echo pow(0, 0); // 1

echo pow(-1, 5.5); // erro

?>

Atenção

No PHP 4.0.6 e posteriores, pow() sempre retornará um float, e não gerará avisos de erros.

Veja também exp() e sqrt().

rad2deg

(PHP 3>= 3.0.4, PHP 4 )

rad2deg --  Converte o número em radianos para o equivalente em graus

Descrição

float rad2deg ( float number)

Esta função converte number de radianos para graus.

Veja também deg2rad().

rand

(PHP 3, PHP 4 )

rand -- Gera um número aleatório

Descrição

int rand ( [int min, int max])

Se chamado sem os parâmetros opcionais min e max, rand() retornará um pseudo valor randômico entre 0 e RAND_MAX. Se você precisa de um número aleatório entre 5 e 15 (inclusive), por exemplo, utilize rand (5, 15).

Em versões anteriores do PHP, você precisa semear o gerador de números aletórios primeiro com srand(). Desde o PHP 4.2.0, isto não é mais necesário.

Nota: Em versões anteriores a 3.0.7, o significado do parâmetro max era range. Assim, para obter os mesmos resultados do exemplo acima, você precisaria utilizar rand (5, 11) para obter um número aleatório entre 5 e 15.

Veja também srand(), getrandmax() e mt_rand().

round

(PHP 3, PHP 4 )

round -- Arredonda um número

Descrição

float round ( float val [, int precision])

Retornar um valor arredondado de val em precision casas decimais. precision pode ser negativo ou zero (default).

Cuidado

O PHP não manipula strings como "12,300.2" corretamente por padrão. Veja convertendo de strings.

echo round(3.4);         // 3
echo round(3.5);         // 4
echo round(3.6);         // 4
echo round(3.6, 0);      // 4
echo round(1.95583, 2);  // 1.96
echo round(1241757, -3); // 1242000

Nota: O parâmetro precision foi acrescentado no PHP 4.

Veja também ceil() e floor().

sin

(PHP 3, PHP 4 )

sin -- Seno

Descrição

float sin ( float arg)

sin() retorna o seno do parâmetro arg. O argumento arg deve estar em radianos.

<?php

// Precisão depende da diretiva precision
print sin(deg2rad(60));  //  0.866025403 ...
print sin(60);           // -0.304810621 ...

?>

Veja também asin(), cos(), tan() e deg2rad().

sinh

(PHP 4 >= 4.1.0)

sinh -- Seno hiperbólico

Descrição

float sinh ( float arg)

Retorna o seno hiperbólico de arg, definido como (exp(arg) - exp(-arg))/2.

Veja também sin(), asinh(), cos() e tan().

sqrt

(PHP 3, PHP 4 )

sqrt -- Raiz quadrada

Descrição

float sqrt ( float arg)

Retorna a raiz quadrada de arg.

<?php
// Precisão depende de sua diretiva precision
echo sqrt(9); // 3
echo sqrt(10); // 3.16227766 ...
?>

Veja também pow().

srand

(PHP 3, PHP 4 )

srand -- Semeia o gerador de números aletórios

Descrição

void srand ( int seed)

Semeia o gerador de números aleatórios com seed.

// semeira com microsegundos
function make_seed() {
    list($usec, $sec) = explode(' ', microtime());
    return (float) $sec + ((float) $usec * 100000);
}
srand(make_seed());
$randval = rand();

Nota: Desde o PHP 4.2.0 não é mais necessário semear o gerador de números aleatórios antes de utilizá-lo.

Veja também rand(), getrandmax() e mt_srand().

tan

(PHP 3, PHP 4 )

tan -- Tangente

Descrição

float tan ( float arg)

tan() retorna a tangente do parâmetro arg. O argumento arg deve estar em radianos.

Veja também atan(), sin(), cos() e deg2rad().

tanh

(PHP 4 >= 4.1.0)

tanh -- Tangente hiperbólica

Descrição

float tanh ( float arg)

Retorna a tangente hiperbólica de arg, definida como sinh(arg)/cosh(arg).

Veja também tan(), atanh(), sin() e cos().

LII. Multi-Byte String Functions

Introdução

There are many languages in which all characters can be expressed by single byte. Multi-byte character codes are used to express many characters for many languages. mbstring is developed to handle Japanese characters. However, many mbstring functions are able to handle character encoding other than Japanese.

A multi-byte character encoding represents single character with consecutive bytes. Some character encoding has shift(escape) sequences to start/end multi-byte character strings. Therefore, a multi-byte character string may be destroyed when it is divided and/or counted unless multi-byte character encoding safe method is used. This module provides multi-byte character safe string functions and other utility functions such as conversion functions.

Since PHP is basically designed for ISO-8859-1, some multi-byte character encoding does not work well with PHP. Therefore, it is important to set mbstring.internal_encoding to a character encoding that works with PHP.

PHP4 Character Encoding Requirements

  • Per byte encoding

  • Single byte characters in range of 00h-7fh which is compatible with ASCII

  • Multi-byte characters without 00h-7fh

These are examples of internal character encoding that works with PHP and does NOT work with PHP.

Character encodings work with PHP: 
ISO-8859-*, EUC-JP, UTF-8

Character encodings do NOT work with PHP:
JIS, SJIS

Character encoding, that does not work with PHP, may be converted with mbstring's HTTP input/output conversion feature/function.

Nota: SJIS should not be used for internal encoding unless the reader is familiar with parser/compiler, character encoding and character encoding issues.

Nota: If you use databases with PHP, it is recommended that you use the same character encoding for both database and internal encoding for ease of use and better performance.

If you are using PostgreSQL, it supports character encoding that is different from backend character encoding. See the PostgreSQL manual for details.


Instalação

mbstring is an extended module. You must enable the module with the configure script. Refer to the Install section for details.

The following configure options are related to the mbstring module.

  • --enable-mbstring: Enable mbstring functions. This option is required to use mbstring functions.

    Nota: As of PHP 4.3.0, the option --enable-mbstring will be enabled by default and replaced with --with-mbstring[=LANG] to support Chinese, Korean and Russian language support. Japanese character encoding is supported by default. If --with-mbstring=cn is used, simplified chinese encoding will be supported. If --with-mbstring=tw is used, traditional chinese encoding will be supported. If --with-mbstring=kr is used, korean encoding will be supported. If --with-mbstring=ru is used, russian encoding will be supported. If --with-mbstring=all is added, all supported character encoding in mbstring will be enabled, but the binary size of PHP will be maximized because of huge Unicode character maps. Note that Chinese, Korean and Russian encoding is experimentally supported in PHP 4.3.0.

  • --enable-mbstr-enc-trans : Enable HTTP input character encoding conversion using mbstring conversion engine. If this feature is enabled, HTTP input character encoding may be converted to mbstring.internal_encoding automatically.

    Nota: As of PHP 4.3.0, the option --enable-mbstr-enc-trans will be eliminated and replaced with mbstring.encoding_translation. HTTP input character encoding conversion is enabled when this is set to On (the default is Off).

  • --enable-mbregex: Enable regular expression functions with multibyte character support.


Configuração durante execução

O comportamento dessas funções podem ser modificado pelas configurações do php.ini.

Tabela 1. Multi-Byte String configuration options

Name Default Changeable
mbstring.language NULL PHP_INI_ALL
mbstring.detect_order NULL PHP_INI_ALL
mbstring.http_input NULL PHP_INI_ALL
mbstring.http_output NULL PHP_INI_ALL
mbstring.internal_encoding NULL PHP_INI_ALL
mbstring.script_encoding NULL PHP_INI_ALL
mbstring.substitute_character NULL PHP_INI_ALL
mbstring.func_overload "0" PHP_INI_SYSTEM
mbstring.encoding_translation "0" PHP_INI_ALL
For further details and definition of the PHP_INI_* constants see ini_set().

Here is a short explanation of the configuration directives.

  • mbstring.language defines default language used in mbstring. Note that this option defines mbstring.interanl_encoding and mbstring.interanl_encoding should be placed after mbstring.language in php.ini

  • mbstring.encoding_translation enables HTTP input character encoding detection and translation into internal chatacter encoding.

  • mbstring.internal_encoding defines default internal character encoding.

  • mbstring.http_input defines default HTTP input character encoding.

  • mbstring.http_output defines default HTTP output character encoding.

  • mbstring.detect_order defines default character code detection order. See also mb_detect_order().

  • mbstring.substitute_character defines character to substitute for invalid character encoding.

  • mbstring.func_overloadoverload(replace) single byte functions by mbstring functions. mail(), ereg(), etc. are overloaded by mb_send_mail(), mb_ereg(), etc. Possible values are 0, 1, 2, 4 or a combination of them. For example, 7 for overload everything. 0: No overload, 1: Overload mail() function, 2: Overload str*() functions, 4: Overload ereg*() functions.

Web Browsers are supposed to use the same character encoding when submitting form. However, browsers may not use the same character encoding. See mb_http_input() to detect character encoding used by browsers.

If enctype is set to multipart/form-data in HTML forms, mbstring does not convert character encoding in POST data. The user must convert them in the script, if conversion is needed.

Although, browsers are smart enough to detect character encoding in HTML. charset is better to be set in HTTP header. Change default_charset according to character encoding.

Exemplo 1. php.ini setting example

; Set default language
mbstring.language        = English; Set default language to English (default)
mbstring.language        = Japanese; Set default language to Japanese

;; Set default internal encoding
;; Note: Make sure to use character encoding works with PHP
mbstring.internal_encoding    = UTF-8  ; Set internal encoding to UTF-8

;; HTTP input encoding translation is enabled.
mbstring.encoding_translation = On

;; Set default HTTP input character encoding
;; Note: Script cannot change http_input setting.
mbstring.http_input           = pass    ; No conversion. 
mbstring.http_input           = auto    ; Set HTTP input to auto
                                ; "auto" is expanded to "ASCII,JIS,UTF-8,EUC-JP,SJIS"
mbstring.http_input           = SJIS    ; Set HTTP2 input to  SJIS
mbstring.http_input           = UTF-8,SJIS,EUC-JP ; Specify order

;; Set default HTTP output character encoding 
mbstring.http_output          = pass    ; No conversion
mbstring.http_output          = UTF-8   ; Set HTTP output encoding to UTF-8

;; Set default character encoding detection order
mbstring.detect_order         = auto    ; Set detect order to auto
mbstring.detect_order         = ASCII,JIS,UTF-8,SJIS,EUC-JP ; Specify order

;; Set default substitute character
mbstring.substitute_character = 12307   ; Specify Unicode value
mbstring.substitute_character = none    ; Do not print character
mbstring.substitute_character = long    ; Long Example: U+3000,JIS+7E7E

Exemplo 2. php.ini setting for EUC-JP users

;; Disable Output Buffering
output_buffering      = Off

;; Set HTTP header charset
default_charset       = EUC-JP    

;; Set default language to Japanese
mbstring.language = Japanese

;; HTTP input encoding translation is enabled.
mbstring.encoding_translation = On

;; Set HTTP input encoding conversion to auto
mbstring.http_input   = auto 

;; Convert HTTP output to EUC-JP
mbstring.http_output  = EUC-JP    

;; Set internal encoding to EUC-JP
mbstring.internal_encoding = EUC-JP    

;; Do not print invalid characters
mbstring.substitute_character = none

Exemplo 3. php.ini setting for SJIS users

;; Enable Output Buffering
output_buffering     = On

;; Set mb_output_handler to enable output conversion
output_handler       = mb_output_handler

;; Set HTTP header charset
default_charset      = Shift_JIS

;; Set default language to Japanese
mbstring.language = Japanese

;; Set http input encoding conversion to auto
mbstring.http_input  = auto 

;; Convert to SJIS
mbstring.http_output = SJIS    

;; Set internal encoding to EUC-JP
mbstring.internal_encoding = EUC-JP    

;; Do not print invalid characters
mbstring.substitute_character = none


Tipos Resource

Esta extensão não possui nenhum tipo resource.


Constantes Predefinidas

As contantes abaixo são definidas por esta extensão e somente estarão disponíveis quando a extensão foi compilada com o PHP ou carregada dinamicamente durante a execução.

MB_OVERLOAD_MAIL (integer)

MB_OVERLOAD_STRING (integer)

MB_OVERLOAD_REGEX (integer)


HTTP Input and Output

HTTP input/output character encoding conversion may convert binary data also. Users are supposed to control character encoding conversion if binary data is used for HTTP input/output.

If enctype for HTML form is set to multipart/form-data, mbstring does not convert character encoding in POST data. If it is the case, strings are needed to be converted to internal character encoding.

  • HTTP Input

    There is no way to control HTTP input character conversion from PHP script. To disable HTTP input character conversion, it has to be done in php.ini.

    Exemplo 4. Disable HTTP input conversion in php.ini

    ;; Disable HTTP Input conversion
    mbstring.http_input = pass
    ;; Disable HTTP Input conversion (PHP 4.3.0 or higher)
    mbstring.encoding_translation = Off

    When using PHP as an Apache module, it is possible to override PHP ini setting per Virtual Host in httpd.conf or per directory with .htaccess. Refer to the Configuration section and Apache Manual for details.

  • HTTP Output

    There are several ways to enable output character encoding conversion. One is using php.ini, another is using ob_start() with mb_output_handler() as ob_start callback function.

    Nota: For PHP3-i18n users, mbstring's output conversion differs from PHP3-i18n. Character encoding is converted using output buffer.

Exemplo 5. php.ini setting example

;; Enable output character encoding conversion for all PHP pages

;; Enable Output Buffering
output_buffering    = On

;; Set mb_output_handler to enable output conversion
output_handler      = mb_output_handler

Exemplo 6. Script example

<?php

// Enable output character encoding conversion only for this page

// Set HTTP output character encoding to SJIS
mb_http_output('SJIS');

// Start buffering and specify "mb_output_handler" as
// callback function
ob_start('mb_output_handler');

?>


Supported Character Encodings

Currently, the following character encoding is supported by the mbstring module. Character encoding may be specified for mbstring functions' encoding parameter.

The following character encoding is supported in this PHP extension:

UCS-4, UCS-4BE, UCS-4LE, UCS-2, UCS-2BE, UCS-2LE, UTF-32, UTF-32BE, UTF-32LE, UCS-2LE, UTF-16, UTF-16BE, UTF-16LE, UTF-8, UTF-7, ASCII, EUC-JP, SJIS, eucJP-win, SJIS-win, ISO-2022-JP, JIS, ISO-8859-1, ISO-8859-2, ISO-8859-3, ISO-8859-4, ISO-8859-5, ISO-8859-6, ISO-8859-7, ISO-8859-8, ISO-8859-9, ISO-8859-10, ISO-8859-13, ISO-8859-14, ISO-8859-15, byte2be, byte2le, byte4be, byte4le, BASE64, 7bit, 8bit and UTF7-IMAP.

As of PHP 4.3.0, the following character encoding support will be added experimentaly : EUC-CN, CP936, HZ, EUC-TW, CP950, BIG-5, EUC-KR, UHC (CP949), ISO-2022-KR, Windows-1251 (CP1251), Windows-1252 (CP1252), CP866, KOI8-R.

php.ini entry, which accepts encoding name, accepts "auto" and "pass" also. mbstring functions, which accepts encoding name, and accepts "auto".

If "pass" is set, no character encoding conversion is performed.

If "auto" is set, it is expanded to "ASCII,JIS,UTF-8,EUC-JP,SJIS".

See also mb_detect_order()

Nota: "Supported character encoding" does not mean that it works as internal character code.


Overloading PHP string functions with multi byte string functions

Because almost PHP application written for language using single-byte character encoding, there are some difficulties for multibyte string handling including japanese. Almost PHP string functions such as substr() do not support multibyte string.

Multibyte extension (mbstring) has some PHP string functions with multibyte support (ex. substr() supports mb_substr()).

Multibyte extension (mbstring) also supports 'function overloading' to add multibyte string functionality without code modification. Using function overloading, some PHP string functions will be oveloaded multibyte string functions. For example, mb_substr() is called instead of substr() if function overloading is enabled. Function overload makes easy to port application supporting only single-byte encoding for multibyte application.

mbstring.func_overload in php.ini should be set some positive value to use function overloading. The value should specify the category of overloading functions, sbould be set 1 to enable mail function overloading. 2 to enable string functions, 4 to regular expression functions. For example, if is set for 7, mail, strings, regex functions should be overloaded. The list of overloaded functions are shown in below.


Basics of Japanese multi-byte characters

Most Japanese characters need more than 1 byte per character. In addition, several character encoding schemas are used under a Japanese environment. There are EUC-JP, Shift_JIS(SJIS) and ISO-2022-JP(JIS) character encoding. As Unicode becomes popular, UTF-8 is used also. To develop Web applications for a Japanese environment, it is important to use the character set for the task in hand, whether HTTP input/output, RDBMS and E-mail.

  • Storage for a character can be up to six bytes

  • A multi-byte character is usually twice of the width compared to single-byte characters. Wider characters are called "zen-kaku" - meaning full width, narrower characters are called "han-kaku" - meaning half width. "zen-kaku" characters are usually fixed width.

  • Some character encoding defines shift(escape) sequence for entering/exiting multi-byte character strings.

  • ISO-2022-JP must be used for SMTP/NNTP.

  • "i-mode" web site is supposed to use SJIS.


References

Multi-byte character encoding and its related issues are very complex. It is impossible to cover in sufficient detail here. Please refer to the following URLs and other resources for further readings.

  • Unicode/UTF/UCS/etc

    http://www.unicode.org/

  • Japanese/Korean/Chinese character information

    ftp://ftp.ora.com/pub/examples/nutshell/ujip/doc/cjk.inf

Índice
mb_convert_case -- Perform case folding on a string
mb_convert_encoding -- Convert character encoding
mb_convert_kana --  Convert "kana" one from another ("zen-kaku" ,"han-kaku" and more)
mb_convert_variables -- Convert character code in variable(s)
mb_decode_mimeheader -- Decode string in MIME header field
mb_decode_numericentity --  Decode HTML numeric string reference to character
mb_detect_encoding -- Detect character encoding
mb_detect_order --  Set/Get character encoding detection order
mb_encode_mimeheader -- Encode string for MIME header
mb_encode_numericentity --  Encode character to HTML numeric string reference
mb_ereg_match --  Regular expression match for multibyte string
mb_ereg_replace -- Replace regular expression with multibyte support
mb_ereg_search_getpos --  Returns start point for next regular expression match
mb_ereg_search_getregs --  Retrive the result from the last multibyte regular expression match
mb_ereg_search_init --  Setup string and regular expression for multibyte regular expression match
mb_ereg_search_pos --  Return position and length of matched part of multibyte regular expression for predefined multibyte string
mb_ereg_search_regs --  Returns the matched part of multibyte regular expression
mb_ereg_search_setpos --  Set start point of next regular expression match
mb_ereg_search --  Multibyte regular expression match for predefined multibyte string
mb_ereg -- Regular expression match with multibyte support
mb_eregi_replace --  Replace regular expression with multibyte support ignoring case
mb_eregi --  Regular expression match ignoring case with multibyte support
mb_get_info -- Get internal settings of mbstring
mb_http_input -- Detect HTTP input character encoding
mb_http_output -- Set/Get HTTP output character encoding
mb_internal_encoding --  Set/Get internal character encoding
mb_language --  Set/Get current language
mb_output_handler --  Callback function converts character encoding in output buffer
mb_parse_str --  Parse GET/POST/COOKIE data and set global variable
mb_preferred_mime_name -- Get MIME charset string
mb_regex_encoding --  Returns current encoding for multibyte regex as string
mb_regex_set_options --  Set/Get the default options for mbregex functions
mb_send_mail --  Send encoded mail.
mb_split -- Split multibyte string using regular expression
mb_strcut -- Get part of string
mb_strimwidth -- Get truncated string with specified width
mb_strlen -- Get string length
mb_strpos --  Find position of first occurrence of string in a string
mb_strrpos --  Find position of last occurrence of a string in a string
mb_strtolower -- Make a string lowercase
mb_strtoupper -- Make a string uppercase
mb_strwidth -- Return width of string
mb_substitute_character -- Set/Get substitution character
mb_substr_count -- Count the number of substring occurrences
mb_substr -- Get part of string

mb_convert_case

(PHP 4 >= 4.3.0)

mb_convert_case -- Perform case folding on a string

Description

string mb_convert_case ( string str, int mode [, string encoding])

mb_convert_case() returns case folded version of string converted in the way specified by mode.

mode can be one of MB_CASE_UPPER, MB_CASE_LOWER or MB_CASE_TITLE.

encoding specifies the encoding of str; if omitted, the internal character encoding value will be used.

The return value is str with the appropriate case folding applied.

By contrast to the standard case folding functions such as strtolower() and strtoupper(), case folding is performed on the basis of the Unicode character properties. Thus the behaviour of this function is not affected by locale settings and it can convert any characters that have 'alphabetic' property, such as A-umlaut (Ä).

For more information about the Unicode properties, please see http://www.unicode.org/unicode/reports/tr21/.

Exemplo 1. mb_convert_case() example

$str = "mary had a Little lamb and she loved it so";
$str = mb_convert_case($str, MB_CASE_UPPER, "UTF-8");
print $str; # Prints MARY HAD A LITTLE LAMB AND SHE LOVED IT SO
$str = mb_convert_case($str, MB_CASE_TITLE, "UTF-8");
print $str; # Prints Mary Had A Little Lamb And She Loved It So

See also mb_strtolower(), mb_strtoupper(), strtolower(), strtoupper().

mb_convert_encoding

(PHP 4 >= 4.0.6)

mb_convert_encoding -- Convert character encoding

Description

string mb_convert_encoding ( string str, string to-encoding [, mixed from-encoding])

mb_convert_encoding() converts character encoding of string str from from-encoding to to-encoding.

str : String to be converted.

from-encoding is specified by character code name before conversion. it can be array or string - comma separated enumerated list. If it is not specified, the internal encoding will be used.

Exemplo 1. mb_convert_encoding() example

/* Convert internal character encoding to SJIS */
$str = mb_convert_encoding($str, "SJIS");

/* Convert EUC-JP to UTF-7 */
$str = mb_convert_encoding($str, "UTF-7", "EUC-JP");

/* Auto detect encoding from JIS, eucjp-win, sjis-win, then convert str to UCS-2LE */
$str = mb_convert_encoding($str, "UCS-2LE", "JIS, eucjp-win, sjis-win");

/* "auto" is expanded to "ASCII,JIS,UTF-8,EUC-JP,SJIS" */
$str = mb_convert_encoding($str, "EUC-JP", "auto");

See also: mb_detect_order().

mb_convert_kana

(PHP 4 >= 4.0.6)

mb_convert_kana --  Convert "kana" one from another ("zen-kaku" ,"han-kaku" and more)

Description

string mb_convert_kana ( string str, string option [, mixed encoding])

mb_convert_kana() performs "han-kaku" - "zen-kaku" conversion for string str. It returns converted string. This function is only useful for Japanese.

option is conversion option. Default value is "KV".

encoding is character encoding. If it is omitted, internal character encoding is used.

Applicable Conversion Options 

       option : Specify with conversion of following options. Default "KV"
       "r" :  Convert "zen-kaku" alphabets to "han-kaku"
       "R" :  Convert "han-kaku" alphabets to "zen-kaku"
       "n" :  Convert "zen-kaku" numbers to "han-kaku"
       "N" :  Convert "han-kaku" numbers to "zen-kaku"
       "a" :  Convert "zen-kaku" alphabets and numbers to "han-kaku"
       "A" :  Convert "han-kaku" alphabets and numbers to "zen-kaku"
       (Characters included in "a", "A" options are
       U+0021 - U+007E excluding U+0022, U+0027, U+005C, U+007E)
       "s" :  Convert "zen-kaku" space to "han-kaku" (U+3000 -> U+0020)
       "S" :  Convert "han-kaku" space to "zen-kaku" (U+0020 -> U+3000)
       "k" :  Convert "zen-kaku kata-kana" to "han-kaku kata-kana"
       "K" :  Convert "han-kaku kata-kana" to "zen-kaku kata-kana"
       "h" :  Convert "zen-kaku hira-gana" to "han-kaku kata-kana"
       "H" :  Convert "han-kaku kata-kana" to "zen-kaku hira-gana"
       "c" :  Convert "zen-kaku kata-kana" to "zen-kaku hira-gana"
       "C" :  Convert "zen-kaku hira-gana" to "zen-kaku kata-kana"
       "V" :  Collapse voiced sound notation and convert them into a character. Use with "K","H"

Exemplo 1. mb_convert_kana() example

/* Convert all "kana" to "zen-kaku" "kata-kana" */
$str = mb_convert_kana($str, "KVC");

/* Convert "han-kaku" "kata-kana" to "zen-kaku" "kata-kana" 
   and "zen-kaku" alpha-numeric to "han-kaku" */
$str = mb_convert_kana($str, "KVa");

mb_convert_variables

(PHP 4 >= 4.0.6)

mb_convert_variables -- Convert character code in variable(s)

Description

string mb_convert_variables ( string to-encoding, mixed from-encoding, mixed vars)

mb_convert_variables() convert character encoding of variables vars in encoding from-encoding to encoding to-encoding. It returns character encoding before conversion for success, FALSE for failure.

mb_convert_variables() join strings in Array or Object to detect encoding, since encoding detection tends to fail for short strings. Therefore, it is impossible to mix encoding in single array or object.

It from-encoding is specified by array or comma separated string, it tries to detect encoding from from-coding. When encoding is omitted, detect_order is used.

vars (3rd and larger) is reference to variable to be converted. String, Array and Object are accepted. mb_convert_variables() assumes all parameters have the same encoding.

Exemplo 1. mb_convert_variables() example

/* Convert variables $post1, $post2 to internal encoding */
$interenc = mb_internal_encoding();
$inputenc = mb_convert_variables($interenc, "ASCII,UTF-8,SJIS-win", $post1, $post2);

mb_decode_mimeheader

(PHP 4 >= 4.0.6)

mb_decode_mimeheader -- Decode string in MIME header field

Description

string mb_decode_mimeheader ( string str)

mb_decode_mimeheader() decodes encoded-word string str in MIME header.

It returns decoded string in internal character encoding.

See also mb_encode_mimeheader().

mb_decode_numericentity

(PHP 4 >= 4.0.6)

mb_decode_numericentity --  Decode HTML numeric string reference to character

Description

string mb_decode_numericentity ( string str, array convmap [, string encoding])

Convert numeric string reference of string str in specified block to character. It returns converted string.

array is array to specifies code area to convert.

encoding is character encoding. If it is omitted, internal character encoding is used.

Exemplo 1. convmap example

$convmap = array (
   int start_code1, int end_code1, int offset1, int mask1,
   int start_code2, int end_code2, int offset2, int mask2,
   ........
   int start_codeN, int end_codeN, int offsetN, int maskN );
// Specify Unicode value for start_codeN and end_codeN
// Add offsetN to value and take bit-wise 'AND' with maskN, 
// then convert value to numeric string reference.

See also: mb_encode_numericentity().

mb_detect_encoding

(PHP 4 >= 4.0.6)

mb_detect_encoding -- Detect character encoding

Description

string mb_detect_encoding ( string str [, mixed encoding-list])

mb_detect_encoding() detects character encoding in string str. It returns detected character encoding.

encoding-list is list of character encoding. Encoding order may be specified by array or comma separated list string.

If encoding_list is omitted, detect_order is used.

Exemplo 1. mb_detect_encoding() example

/* Detect character encoding with current detect_order */
echo mb_detect_encoding($str);

/* "auto" is expanded to "ASCII,JIS,UTF-8,EUC-JP,SJIS" */
echo mb_detect_encoding($str, "auto");

/* Specify encoding_list character encoding by comma separated list */
echo mb_detect_encoding($str, "JIS, eucjp-win, sjis-win");

/* Use array to specify encoding_list  */
$ary[] = "ASCII";
$ary[] = "JIS";
$ary[] = "EUC-JP";
echo mb_detect_encoding($str, $ary);

See also: mb_detect_order().

mb_detect_order

(PHP 4 >= 4.0.6)

mb_detect_order --  Set/Get character encoding detection order

Description

array mb_detect_order ( [mixed encoding-list])

mb_detect_order() sets automatic character encoding detection order to encoding-list. It returns TRUE for success, FALSE for failure.

encoding-list is array or comma separated list of character encoding. ("auto" is expanded to "ASCII, JIS, UTF-8, EUC-JP, SJIS")

If encoding-list is omitted, it returns current character encoding detection order as array.

This setting affects mb_detect_encoding() and mb_send_mail().

Nota: mbstring currently implements following encoding detection filters. If there is a invalid byte sequence for following encoding, encoding detection will fail.

Nota: UTF-8, UTF-7, ASCII, EUC-JP,SJIS, eucJP-win, SJIS-win, JIS, ISO-2022-JP

For ISO-8859-*, mbstring always detects as ISO-8859-*.

For UTF-16, UTF-32, UCS2 and UCS4, encoding detection will fail always.

Exemplo 1. Useless detect order example

; Always detect as ISO-8859-1
detect_order = ISO-8859-1, UTF-8

; Always detect as UTF-8, since ASCII/UTF-7 values are 
; valid for UTF-8
detect_order = UTF-8, ASCII, UTF-7

Exemplo 2. mb_detect_order() examples

/* Set detection order by enumerated list */
mb_detect_order("eucjp-win,sjis-win,UTF-8");

/* Set detection order by array */
$ary[] = "ASCII";
$ary[] = "JIS";
$ary[] = "EUC-JP";
mb_detect_order($ary);

/* Display current detection order */
echo implode(", ", mb_detect_order());

See also mb_internal_encoding(), mb_http_input(), mb_http_output() mb_send_mail().

mb_encode_mimeheader

(PHP 4 >= 4.0.6)

mb_encode_mimeheader -- Encode string for MIME header

Description

string mb_encode_mimeheader ( string str [, string charset [, string transfer-encoding [, string linefeed]]])

mb_encode_mimeheader() converts string str to encoded-word for header field. It returns converted string in ASCII encoding.

charset is character encoding name. Default is ISO-2022-JP.

transfer-encoding is transfer encoding. It should be one of "B" (Base64) or "Q" (Quoted-Printable). Default is "B".

linefeed is end of line marker. Default is "\r\n" (CRLF).

Exemplo 1. mb_convert_kana() example

$name = ""; // kanji
$mbox = "kru";
$doma = "gtinn.mon";
$addr = mb_encode_mimeheader($name, "UTF-7", "Q") . " <" . $mbox . "@" . $doma . ">";
echo $addr;

See also mb_decode_mimeheader().

mb_encode_numericentity

(PHP 4 >= 4.0.6)

mb_encode_numericentity --  Encode character to HTML numeric string reference

Description

string mb_encode_numericentity ( string str, array convmap [, string encoding])

mb_encode_numericentity() converts specified character codes in string str from HTML numeric character reference to character code. It returns converted string.

array is array specifies code area to convert.

encoding is character encoding.

Exemplo 1. convmap example

$convmap = array (
 int start_code1, int end_code1, int offset1, int mask1,
 int start_code2, int end_code2, int offset2, int mask2,
 ........
 int start_codeN, int end_codeN, int offsetN, int maskN );
// Specify Unicode value for start_codeN and end_codeN
// Add offsetN to value and take bit-wise 'AND' with maskN, then
// it converts value to numeric string reference.

Exemplo 2. mb_encode_numericentity() example

/* Convert Left side of ISO-8859-1 to HTML numeric character reference */
$convmap = array(0x80, 0xff, 0, 0xff);
$str = mb_encode_numericentity($str, $convmap, "ISO-8859-1");

/* Convert user defined SJIS-win code in block 95-104 to numeric
   string reference */
$convmap = array(
       0xe000, 0xe03e, 0x1040, 0xffff,
       0xe03f, 0xe0bb, 0x1041, 0xffff,
       0xe0bc, 0xe0fa, 0x1084, 0xffff,
       0xe0fb, 0xe177, 0x1085, 0xffff,
       0xe178, 0xe1b6, 0x10c8, 0xffff,
       0xe1b7, 0xe233, 0x10c9, 0xffff,
       0xe234, 0xe272, 0x110c, 0xffff,
       0xe273, 0xe2ef, 0x110d, 0xffff,
       0xe2f0, 0xe32e, 0x1150, 0xffff,
       0xe32f, 0xe3ab, 0x1151, 0xffff );
$str = mb_encode_numericentity($str, $convmap, "sjis-win");

See also: mb_decode_numericentity().

mb_ereg_match

(4.2.0 - 4.3.0 only)

mb_ereg_match --  Regular expression match for multibyte string

Description

bool mb_ereg_match ( string pattern, string string [, string option])

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

mb_ereg_match() returns TRUE if string matches regular expression pattern, FALSE if not.

The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.

Nota: This function is supported in PHP 4.2.0 or higher.

See also: mb_regex_encoding(), mb_ereg().

mb_ereg_replace

(4.2.0 - 4.3.0 only)

mb_ereg_replace -- Replace regular expression with multibyte support

Description

string mb_ereg_replace ( string pattern, string replacement, string string [, array option])

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

mb_ereg_replace() scans string for matches to pattern, then replaces the matched text with replacement and returns the result string or FALSE on error. Multibyte character can be used in pattern.

Matching condition can be set by option parameter. If i is specified for this parameter, the case will be ignored. If x is specified, white space will be ignored. If m is specified, match will be executed in multiline mode and line break will be included in '.'. If p is specified, match will be executed in POSIX mode, line break will be considered as normal character. If e is specified, replacement string will be evaluated as PHP expression.

The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.

Nota: This function is supported in PHP 4.2.0 or higher.

See also: mb_regex_encoding(), mb_eregi_replace().

mb_ereg_search_getpos

(4.2.0 - 4.3.0 only)

mb_ereg_search_getpos --  Returns start point for next regular expression match

Description

array mb_ereg_search_getpos ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

mb_ereg_search_getpos() returns the point to start regular expression match for mb_ereg_search(), mb_ereg_search_pos(), mb_ereg_search_regs(). The position is represented by bytes from the head of string.

The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.

Nota: This function is supported in PHP 4.2.0 or higher.

See also: mb_regex_encoding(), mb_ereg_search_setpos().

mb_ereg_search_getregs

(4.2.0 - 4.3.0 only)

mb_ereg_search_getregs --  Retrive the result from the last multibyte regular expression match

Description

array mb_ereg_search_getregs ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

mb_ereg_search_getregs() returns an array including the sub-string of matched part by last mb_ereg_search(), mb_ereg_search_pos(), mb_ereg_search_regs(). If there are some maches, the first element will have the matched sub-string, the second element will have the first part grouped with brackets, the third element will have the second part grouped with brackets, and so on. It returns FALSE on error;

The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.

Nota: This function is supported in PHP 4.2.0 or higher.

See also: mb_regex_encoding(), mb_ereg_search_init().

mb_ereg_search_init

(4.2.0 - 4.3.0 only)

mb_ereg_search_init --  Setup string and regular expression for multibyte regular expression match

Description

array mb_ereg_search_init ( string string [, string pattern [, string option]])

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

mb_ereg_search_init() sets string and pattern for multibyte regular expression. These values are used for mb_ereg_search(), mb_ereg_search_pos(), mb_ereg_search_regs(). It returns TRUE for success, FALSE for error.

The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.

Nota: This function is supported in PHP 4.2.0 or higher.

See also: mb_regex_encoding(), mb_ereg_search_regs().

mb_ereg_search_pos

(4.2.0 - 4.3.0 only)

mb_ereg_search_pos --  Return position and length of matched part of multibyte regular expression for predefined multibyte string

Description

array mb_ereg_search_pos ( [string pattern [, string option]])

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

mb_ereg_search_pos() returns an array including position of matched part for multibyte regular expression. The first element of the array will be the beggining of matched part, the second element will be length (bytes) of matched part. It returns FALSE on error.

The string for match is specified by mb_ereg_search_init(). It it is not specified, the previous one will be used.

The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.

Nota: This function is supported in PHP 4.2.0 or higher.

See also: mb_regex_encoding(), mb_ereg_search_init().

mb_ereg_search_regs

(4.2.0 - 4.3.0 only)

mb_ereg_search_regs --  Returns the matched part of multibyte regular expression

Description

array mb_ereg_search_regs ( [string pattern [, string option]])

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

mb_ereg_search_regs() executes the multibyte regular expression match, and if there are some matched part, it returns an array including substring of matched part as first element, the first grouped part with brackets as second element, the second grouped part as third element, and so on. It returns FALSE on error.

The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.

Nota: This function is supported in PHP 4.2.0 or higher.

See also: mb_regex_encoding(), mb_ereg_search_init().

mb_ereg_search_setpos

(4.2.0 - 4.3.0 only)

mb_ereg_search_setpos --  Set start point of next regular expression match

Description

array mb_ereg_search_setpos ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

mb_ereg_search_setpos() sets the starting point of match for mb_ereg_search().

The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.

Nota: This function is supported in PHP 4.2.0 or higher.

See also: mb_regex_encoding(), mb_ereg_search_init().

mb_ereg_search

(4.2.0 - 4.3.0 only)

mb_ereg_search --  Multibyte regular expression match for predefined multibyte string

Description

bool mb_ereg_search ( [string pattern [, string option]])

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

mb_ereg_search() returns TRUE if the multibyte string matches with the regular expression, FALSE for otherwise. The string for matching is set by mb_ereg_search_init(). If pattern is not specified, the previous one is used.

The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.

Nota: This function is supported in PHP 4.2.0 or higher.

See also: mb_regex_encoding(), mb_ereg_search_init().

mb_ereg

(4.2.0 - 4.3.0 only)

mb_ereg -- Regular expression match with multibyte support

Description

int mb_ereg ( string pattern, string string [, array regs])

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

mb_ereg() executes the regular expression match with multibyte support, and returns 1 if matches are found. If the optional third parameter was specified, the function returns the byte length of matched part, and therarray regs will contain the substring of matched string. The functions returns 1 if it matches with the empty string. It no matche found or error happend, FALSE will be returned.

The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.

Nota: This function is supported in PHP 4.2.0 or higher.

See also: mb_regex_encoding(), mb_eregi()

mb_eregi_replace

(4.2.0 - 4.3.0 only)

mb_eregi_replace --  Replace regular expression with multibyte support ignoring case

Description

string mb_eregi_replace ( string pattern, string replace, string string)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

mb_ereg_replace() scans string for matches to pattern, then replaces the matched text with replacement and returns the result string or FALSE on error. Multibyte character can be used in pattern. The case will be ignored.

The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.

Nota: This function is supported in PHP 4.2.0 or higher.

See also: mb_regex_encoding(), mb_ereg_replace().

mb_eregi

(4.2.0 - 4.3.0 only)

mb_eregi --  Regular expression match ignoring case with multibyte support

Description

int mb_eregi ( string pattern, string string [, array regs])

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

mb_eregi() executes the regular expression match with multibyte support, and returns 1 if matches are found. This function ignore case. If the optional third parameter was specified, the function returns the byte length of matched part, and therarray regs will contain the substring of matched string. The functions returns 1 if it matches with the empty string. It no matche found or error happend, FALSE will be returned.

The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.

Nota: This function is supported in PHP 4.2.0 or higher.

See also: mb_regex_encoding(), mb_ereg().

mb_get_info

(PHP 4 >= 4.2.0)

mb_get_info -- Get internal settings of mbstring

Description

string mb_get_info ( [string type])

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

mb_get_info() returns internal setting parameter of mbstring.

If type isn't specified or is specified to "all", an array having the elements "internal_encoding", "http_output", "http_input", "func_overload" will be returned.

If type is specified for "http_output", "http_input", "internal_encoding", "func_overload", the specified setting parameter will be returned.

See also mb_internal_encoding(), mb_http_output().

mb_http_input

(PHP 4 >= 4.0.6)

mb_http_input -- Detect HTTP input character encoding

Description

string mb_http_input ( [string type])

mb_http_input() returns result of HTTP input character encoding detection.

type: Input string specifies input type. "G" for GET, "P" for POST, "C" for COOKIE. If type is omitted, it returns last input type processed.

Return Value: Character encoding name. If mb_http_input() does not process specified HTTP input, it returns FALSE.

See also mb_internal_encoding(), mb_http_output(), mb_detect_order().

mb_http_output

(PHP 4 >= 4.0.6)

mb_http_output -- Set/Get HTTP output character encoding

Description

string mb_http_output ( [string encoding])

If encoding is set, mb_http_output() sets HTTP output character encoding to encoding. Output after this function is converted to encoding. mb_http_output() returns TRUE for success and FALSE for failure.

If encoding is omitted, mb_http_output() returns current HTTP output character encoding.

See also mb_internal_encoding(), mb_http_input(), mb_detect_order().

mb_internal_encoding

(PHP 4 >= 4.0.6)

mb_internal_encoding --  Set/Get internal character encoding

Description

string mb_internal_encoding ( [string encoding])

mb_internal_encoding() sets internal character encoding to encoding If parameter is omitted, it returns current internal encoding.

encoding is used for HTTP input character encoding conversion, HTTP output character encoding conversion and default character encoding for string functions defined by mbstring module.

encoding: Character encoding name

Return Value: If encoding is set,mb_internal_encoding() returns TRUE for success, otherwise returns FALSE. If encoding is omitted, it returns current character encoding name.

Exemplo 1. mb_internal_encoding() example

/* Set internal character encoding to UTF-8 */
mb_internal_encoding("UTF-8");

/* Display current internal character encoding */
echo mb_internal_encoding();

See also mb_http_input(), mb_http_output(), mb_detect_order().

mb_language

(PHP 4 >= 4.0.6)

mb_language --  Set/Get current language

Description

string mb_language ( [string language])

mb_language() sets language. If language is omitted, it returns current language as string.

language setting is used for encoding e-mail messages. Valid languages are "Japanese", "ja","English","en" and "uni" (UTF-8). mb_send_mail() uses this setting to encode e-mail.

Language and its setting is ISO-2022-JP/Base64 for Japanese, UTF-8/Base64 for uni, ISO-8859-1/quoted printable for English.

Return Value: If language is set and language is valid, it returns TRUE. Otherwise, it returns FALSE. When language is omitted, it returns language name as string. If no language is set previously, it returns FALSE.

See also mb_send_mail().

mb_output_handler

(PHP 4 >= 4.0.6)

mb_output_handler --  Callback function converts character encoding in output buffer

Description

string mb_output_handler ( string contents, int status)

mb_output_handler() is ob_start() callback function. mb_output_handler() converts characters in output buffer from internal character encoding to HTTP output character encoding.

4.1.0 or later version, this hanlder adds charset HTTP header when following conditions are met:

  • Does not set Content-Type by header()

  • Default MIME type begins with text/

  • http_output setting is other than pass

contents : Output buffer contents

status : Output buffer status

Return Value: String converted

Exemplo 1. mb_output_handler() example

mb_http_output("UTF-8");
ob_start("mb_output_handler");

Nota: If you want to output some binary data such as image from PHP script with PHP 4.3.0 or later, Content-Type: header must be send using header() before any binary data was send to client (e.g. header("Content-Type: image/png")). If Content-Type: header was send, output character encoding conversion will not be performed.

Note that if 'Content-Type: text/*' was send using header(), the sending data is regarded as text, encoding conversion will be performed using character encoding settings.

If you want to output some binary data such as image from PHP script with PHP 4.2.x or earlier, you must set output encoding to "pass" using mb_http_output().

See also ob_start().

mb_parse_str

(PHP 4 >= 4.0.6)

mb_parse_str --  Parse GET/POST/COOKIE data and set global variable

Description

bool mb_parse_str ( string encoded_string [, array result])

mb_parse_str() parses GET/POST/COOKIE data and sets global variables. Since PHP does not provide raw POST/COOKIE data, it can only used for GET data for now. It preses URL encoded data, detects encoding, converts coding to internal encoding and set values to result array or global variables.

encoded_string: URL encoded data.

result: Array contains decoded and character encoding converted values.

Return Value: It returns TRUE for success or FALSE for failure.

See also mb_detect_order(), mb_internal_encoding().

mb_preferred_mime_name

(PHP 4 >= 4.0.6)

mb_preferred_mime_name -- Get MIME charset string

Description

string mb_preferred_mime_name ( string encoding)

mb_preferred_mime_name() returns MIME charset string for character encoding encoding. It returns charset string.

Exemplo 1. mb_preferred_mime_string() example

$outputenc = "sjis-win";
mb_http_output($outputenc);
ob_start("mb_output_handler");
header("Content-Type: text/html; charset=" . mb_preferred_mime_name($outputenc));

mb_regex_encoding

(4.2.0 - 4.3.0 only)

mb_regex_encoding --  Returns current encoding for multibyte regex as string

Description

string mb_regex_encoding ( [string encoding])

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

mb_regex_encoding() returns the character encoding used by multibyte regex functions.

If the optional parameter encoding is specified, it is set to the character encoding for multibyte regex. The default value is the internal character encoding.

Nota: This function is supported in PHP 4.2.0 or higher.

See also: mb_internal_encoding(), mb_ereg()

mb_regex_set_options

(PHP 4 4.3.0 only)

mb_regex_set_options --  Set/Get the default options for mbregex functions

Description

string mb_regex_set_options ( [string options])

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

mb_regex_set_options() sets the default options described by options for multibyte regex functions.

Returns the previous options. If options is omitted, it returns the string that describes the current options.

Nota: This function is supported in PHP 4.3.0 or higher.

See also: mb_split(), mb_ereg() mb_eregi()

mb_send_mail

(PHP 4 >= 4.0.6)

mb_send_mail --  Send encoded mail.

Description

bool mb_send_mail ( string to, string subject, string message [, string additional_headers [, string additional_parameter]])

mb_send_mail() sends email. Headers and message are converted and encoded according to mb_language() setting. mb_send_mail() is wrapper function of mail(). See mail() for details.

to is mail addresses send to. Multiple recipients can be specified by putting a comma between each address in to. This parameter is not automatically encoded.

subject is subject of mail.

message is mail message.

additional_headers is inserted at the end of the header. This is typically used to add extra headers. Multiple extra headers are separated with a newline ("\n").

additional_parameter is a MTA command line parameter. It is useful when setting the correct Return-Path header when using sendmail.

Retorna TRUE em caso de sucesso ou FALSE em falhas.

See also mail(), mb_encode_mimeheader(), and mb_language().

mb_split

(4.2.0 - 4.3.0 only)

mb_split -- Split multibyte string using regular expression

Description

array mb_split ( string pattern, string string [, int limit])

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

mb_split() split multibyte string using regular expression pattern and returns the result as an array.

If optional parameter limit is specified, it will be split in limit elements as maximum.

The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.

Nota: This function is supported in PHP 4.2.0 or higher.

See also: mb_regex_encoding(), mb_ereg().

mb_strcut

(PHP 4 >= 4.0.6)

mb_strcut -- Get part of string

Description

string mb_strcut ( string str, int start [, int length [, string encoding]])

mb_strcut() returns the portion of str specified by the start and length parameters.

mb_strcut() performs equivalent operation as mb_substr() with different method. If start position is multi-byte character's second byte or larger, it starts from first byte of multi-byte character.

It subtracts string from str that is shorter than length AND character that is not part of multi-byte string or not being middle of shift sequence.

encoding is character encoding. If it is not set, internal character encoding is used.

See also mb_substr(), mb_internal_encoding().

mb_strimwidth

(PHP 4 >= 4.0.6)

mb_strimwidth -- Get truncated string with specified width

Description

string mb_strimwidth ( string str, int start, int width, string trimmarker [, string encoding])

mb_strimwidth() truncates string str to specified width. It returns truncated string.

If trimmarker is set, trimmarker is appended to return value.

start is start position offset. Number of characters from the beginning of string. (First character is 0)

trimmarker is string that is added to the end of string when string is truncated.

encoding is character encoding. If it is omitted, internal encoding is used.

Exemplo 1. mb_strimwidth() example

$str = mb_strimwidth($str, 0, 40, "..>");

See also: mb_strwidth(), mb_internal_encoding().

mb_strlen

(PHP 4 >= 4.0.6)

mb_strlen -- Get string length

Description

string mb_strlen ( string str [, string encoding])

mb_strlen() returns number of characters in string str having character encoding encoding. A multi-byte character is counted as 1.

encoding is character encoding for str. If encoding is omitted, internal character encoding is used.

See also mb_internal_encoding(), strlen().

mb_strpos

(PHP 4 >= 4.0.6)

mb_strpos --  Find position of first occurrence of string in a string

Description

int mb_strpos ( string haystack, string needle [, int offset [, string encoding]])

mb_strpos() returns the numeric position of the first occurrence of needle in the haystack string. If needle is not found, it returns FALSE.

mb_strpos() performs multi-byte safe strpos() operation based on number of characters. needle position is counted from the beginning of the haystack. First character's position is 0. Second character position is 1, and so on.

If encoding is omitted, internal character encoding is used. mb_strrpos() accepts string for needle where strrpos() accepts only character.

offset is search offset. If it is not specified, 0 is used.

encoding is character encoding name. If it is omitted, internal character encoding is used.

See also mb_strpos(), mb_internal_encoding(), strpos()

mb_strrpos

(PHP 4 >= 4.0.6)

mb_strrpos --  Find position of last occurrence of a string in a string

Description

int mb_strrpos ( string haystack, string needle [, string encoding])

mb_strrpos() returns the numeric position of the last occurrence of needle in the haystack string. If needle is not found, it returns FALSE.

mb_strrpos() performs multi-byte safe strrpos() operation based on number of characters. needle position is counted from the beginning of haystack. First character's position is 0. Second character position is 1.

If encoding is omitted, internal encoding is assumed. mb_strrpos() accepts string for needle where strrpos() accepts only character.

encoding is character encoding. If it is not specified, internal character encoding is used.

See also mb_strpos(), mb_internal_encoding(), strrpos().

mb_strtolower

(PHP 4 >= 4.3.0)

mb_strtolower -- Make a string lowercase

Description

string mb_strtolower ( string str [, string encoding])

mb_strtolower() returns str with all alphabetic characters converted to lowercase.

encoding specifies the encoding of str; if omitted, the internal character encoding value will be used.

For more information about the Unicode properties, please see http://www.unicode.org/unicode/reports/tr21/.

By contrast to strtolower(), 'alphabetic' is determined by the Unicode character properties. Thus the behaviour of this function is not affected by locale settings and it can convert any characters that have 'alphabetic' property, such as A-umlaut (Ä).

Exemplo 1. mb_strtolower() example

$str = "Mary Had A Little Lamb and She LOVED It So";
$str = mb_strtolower($str);
print $str; # Prints mary had a little lamb and she loved it so

See also strtolower(), mb_strtoupper(), mb_convert_case().

mb_strtoupper

(PHP 4 >= 4.3.0)

mb_strtoupper -- Make a string uppercase

Description

string mb_strtoupper ( string str [, string encoding])

mb_strtoupper() returns str with all alphabetic characters converted to uppercase.

encoding specifies the encoding of str; if omitted, the internal character encoding value will be used.

By contrast to strtoupper(), 'alphabetic' is determined by the Unicode character properties. Thus the behaviour of this function is not affected by locale settings and it can convert any characters that have 'alphabetic' property, such as a-umlaut (ä).

For more information about the Unicode properties, please see http://www.unicode.org/unicode/reports/tr21/.

Exemplo 1. mb_strtoupper() example

$str = "Mary Had A Little Lamb and She LOVED It So";
$str = mb_strtoupper($str);
print $str; # Prints MARY HAD A LITTLE LAMB AND SHE LOVED IT SO

See also strtoupper(), mb_strtolower(), mb_convert_case().

mb_strwidth

(PHP 4 >= 4.0.6)

mb_strwidth -- Return width of string

Description

int mb_strwidth ( string str [, string encoding])

mb_strwidth() returns width of string str.

Multi-byte character usually twice of width compare to single byte character.

Character width

       U+0000 - U+0019   0
       U+0020 - U+1FFF   1
       U+2000 - U+FF60   2
       U+FF61 - U+FF9F   1
       U+FFA0 -          2

encoding is character encoding. If it is omitted, internal encoding is used.

See also: mb_strimwidth(), mb_internal_encoding().

mb_substitute_character

(PHP 4 >= 4.0.6)

mb_substitute_character -- Set/Get substitution character

Description

mixed mb_substitute_character ( [mixed substrchar])

mb_substitute_character() specifies substitution character when input character encoding is invalid or character code is not exist in output character encoding. Invalid characters may be substituted NULL(no output), string or integer value (Unicode character code value).

This setting affects mb_detect_encoding() and mb_send_mail().

substchar : Specify Unicode value as integer or specify as string as follows

  • "none" : no output

  • "long" : Output character code value (Example: U+3000,JIS+7E7E)

Return Value: If substchar is set, it returns TRUE for success, otherwise returns FALSE. If substchar is not set, it returns Unicode value or "none"/"long".

Exemplo 1. mb_substitute_character() example

/* Set with Unicode U+3013 (GETA MARK) */
mb_substitute_character(0x3013);

/* Set hex format */
mb_substitute_character("long");

/* Display current setting */
echo mb_substitute_character();

mb_substr_count

(PHP 4 >= 4.3.0)

mb_substr_count -- Count the number of substring occurrences

Description

int mb_substr_count ( string haystack, string needle [, string encoding])

mb_substr_count() returns the number of times the needle substring occurs in the haystack string.

encoding specifies the encoding for needle and haystack. If omitted, internal character encoding is used.

Exemplo 1. mb_substr_count() example

<?php
print mb_substr_count("This is a test", "is"); // prints out 2
?>

See also substr_count(), mb_strpos(), mb_substr().

mb_substr

(PHP 4 >= 4.0.6)

mb_substr -- Get part of string

Description

string mb_substr ( string str, int start [, int length [, string encoding]])

mb_substr() returns the portion of str specified by the start and length parameters.

mb_substr() performs multi-byte safe substr() operation based on number of characters. Position is counted from the beginning of str. First character's position is 0. Second character position is 1, and so on.

If encoding is omitted, internal encoding is assumed.

encoding is character encoding. If it is omitted, internal character encoding is used.

See also mb_strcut(), mb_internal_encoding().

LIII. MCAL functions

Introdução

MCAL stands for Modular Calendar Access Library.

Libmcal is a C library for accessing calendars. It's written to be very modular, with pluggable drivers. MCAL is the calendar equivalent of the IMAP module for mailboxes.

With mcal support, a calendar stream can be opened much like the mailbox stream with the IMAP support. Calendars can be local file stores, remote ICAP servers, or other formats that are supported by the mcal library.

Calendar events can be pulled up, queried, and stored. There is also support for calendar triggers (alarms) and recurring events.

With libmcal, central calendar servers can be accessed, removing the need for any specific database or local file programming.

Most of the functions use an internal event structure that is unique for each stream. This alleviates the need to pass around large objects between functions. There are convenience functions for setting, initializing, and retrieving the event structure values.

Nota: PHP had an ICAP extension previously, but the original library and the PHP extension is not supported anymore. The suggested replacement is MCAL.

Nota: This extension is not available on Windows platforms.


Requisitos

This extension requires the mcal library to be installed. Grab the latest version from http://mcal.chek.com/ and compile and install it.


Instalação

After you installed the mcal library, to get these functions to work, you have to compile PHP -with-mcal[=DIR].


Configuração durante execução

Esta extenção não define nenhum parâmetro de configuração no php.ini.


Tipos Resource

Esta extensão não possui nenhum tipo resource.


Constantes Predefinidas

As contantes abaixo são definidas por esta extensão e somente estarão disponíveis quando a extensão foi compilada com o PHP ou carregada dinamicamente durante a execução.

MCAL_SUNDAY (integer)

MCAL_MONDAY (integer)

MCAL_TUESDAY (integer)

MCAL_WEDNESDAY (integer)

MCAL_THURSDAY (integer)

MCAL_FRIDAY (integer)

MCAL_SATURDAY (integer)

MCAL_JANUARY (integer)

MCAL_FEBRUARY (integer)

MCAL_MARCH (integer)

MCAL_APRIL (integer)

MCAL_MAY (integer)

MCAL_JUNE (integer)

MCAL_JULY (integer)

MCAL_AUGUST (integer)

MCAL_SEPTEMBER (integer)

MCAL_OCTOBER (integer)

MCAL_NOVEMBER (integer)

MCAL_DECEMBER (integer)

MCAL_RECUR_NONE (integer)

MCAL_RECUR_DAILY (integer)

MCAL_RECUR_WEEKLY (integer)

MCAL_RECUR_MONTHLY_MDAY (integer)

MCAL_RECUR_MONTHLY_WDAY (integer)

MCAL_RECUR_YEARLY (integer)

MCAL_M_SUNDAY (integer)

MCAL_M_MONDAY (integer)

MCAL_M_TUESDAY (integer)

MCAL_M_WEDNESDAY (integer)

MCAL_M_THURSDAY (integer)

MCAL_M_FRIDAY (integer)

MCAL_M_SATURDAY (integer)

MCAL_M_WEEKDAYS (integer)

MCAL_M_WEEKEND (integer)

MCAL_M_ALLDAYS (integer)

Índice
mcal_append_event -- Store a new event into an MCAL calendar
mcal_close -- Close an MCAL stream
mcal_create_calendar -- Create a new MCAL calendar
mcal_date_compare -- Compares two dates
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 given date
mcal_day_of_year --  Returns the day of the year of the given date
mcal_days_in_month --  Returns the number of days in the given month
mcal_delete_calendar -- Delete an MCAL calendar
mcal_delete_event -- Delete an event from an MCAL calendar
mcal_event_add_attribute --  Adds an attribute and a value to the streams global event structure
mcal_event_init --  Initializes a streams global event structure
mcal_event_set_alarm --  Sets the alarm of the streams global event structure
mcal_event_set_category --  Sets the category of the streams global event structure
mcal_event_set_class --  Sets the class of the streams global event structure
mcal_event_set_description --  Sets the description of the streams global event structure
mcal_event_set_end --  Sets the end date and time of the streams global event structure
mcal_event_set_recur_daily --  Sets the recurrence of the streams global event structure
mcal_event_set_recur_monthly_mday --  Sets the recurrence of the streams global event structure
mcal_event_set_recur_monthly_wday --  Sets the recurrence of the streams global event structure
mcal_event_set_recur_none --  Sets the recurrence of the streams global event structure
mcal_event_set_recur_weekly --  Sets the recurrence of the streams global event structure
mcal_event_set_recur_yearly --  Sets the recurrence of the streams global event structure
mcal_event_set_start --  Sets the start date and time of the streams global event structure
mcal_event_set_title --  Sets the title of the streams global event structure
mcal_expunge --  Deletes all events marked for being expunged.
mcal_fetch_current_stream_event --  Returns an object containing the current streams event structure
mcal_fetch_event --  Fetches an event from the calendar stream
mcal_is_leap_year --  Returns if the given year is a leap year or not
mcal_list_alarms --  Return a list of events that has an alarm triggered at the given datetime
mcal_list_events --  Return a list of IDs for a date or a range of dates.
mcal_next_recurrence -- Returns the next recurrence of the event
mcal_open -- Opens up an MCAL connection
mcal_popen -- Opens up a persistent MCAL connection
mcal_rename_calendar -- Rename an MCAL calendar
mcal_reopen -- Reopens an MCAL connection
mcal_snooze -- Turn off an alarm for an event
mcal_store_event -- Modify an existing event in an MCAL calendar
mcal_time_valid --  Returns TRUE if the given year, month, day is a valid time
mcal_week_of_year --  Returns the week number of the given date

mcal_append_event

(PHP 4 )

mcal_append_event -- Store a new event into an MCAL calendar

Description

int mcal_append_event ( int mcal_stream)

mcal_append_event() Stores the global event into an MCAL calendar for the given stream.

Returns the id of the newly inserted event.

mcal_close

(PHP 3>= 3.0.13, PHP 4 )

mcal_close -- Close an MCAL stream

Description

int mcal_close ( int mcal_stream, int flags)

Closes the given mcal stream.

mcal_create_calendar

(PHP 3>= 3.0.13, PHP 4 )

mcal_create_calendar -- Create a new MCAL calendar

Description

string mcal_create_calendar ( int stream, string calendar)

Creates a new calendar named calendar.

mcal_date_compare

(PHP 3>= 3.0.13, PHP 4 )

mcal_date_compare -- Compares two dates

Description

int mcal_date_compare ( int a_year, int a_month, int a_day, int b_year, int b_month, int b_day)

mcal_date_compare() Compares the two given dates, returns <0, 0, >0 if a<b, a==b, a>b respectively.

mcal_date_valid

(PHP 3>= 3.0.13, PHP 4 )

mcal_date_valid --  Returns TRUE if the given year, month, day is a valid date

Description

int mcal_date_valid ( int year, int month, int day)

mcal_date_valid() Returns TRUE if the given year, month and day is a valid date, FALSE if not.

mcal_day_of_week

(PHP 3>= 3.0.13, PHP 4 )

mcal_day_of_week --  Returns the day of the week of the given date

Description

int mcal_day_of_week ( int year, int month, int day)

mcal_day_of_week() returns the day of the week of the given date. Possible return values range from 0 for Sunday through 6 for Saturday.

mcal_day_of_year

(PHP 3>= 3.0.13, PHP 4 )

mcal_day_of_year --  Returns the day of the year of the given date

Description

int mcal_ ( int year, int month, int day)

mcal_day_of_year() returns the day of the year of the given date.

mcal_days_in_month

(PHP 3>= 3.0.13, PHP 4 )

mcal_days_in_month --  Returns the number of days in the given month

Description

int mcal_days_in_month ( int month, int leap year)

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_delete_calendar

(PHP 3>= 3.0.13, PHP 4 )

mcal_delete_calendar -- Delete an MCAL calendar

Description

string mcal_delete_calendar ( int stream, string calendar)

Deletes the calendar named calendar.

mcal_delete_event

(PHP 3>= 3.0.13, PHP 4 )

mcal_delete_event -- Delete an event from an MCAL calendar

Description

int mcal_delete_event ( int mcal_stream [, int event_id])

mcal_delete_event() deletes the calendar event specified by the event_id.

Returns TRUE.

mcal_event_add_attribute

(PHP 3>= 3.0.15, PHP 4 )

mcal_event_add_attribute --  Adds an attribute and a value to the streams global event structure

Description

void mcal_event_add_attribute ( int stream, string attribute, string value)

mcal_event_add_attribute() adds an attribute to the stream's global event structure with the value given by "value".

mcal_event_init

(PHP 3>= 3.0.13, PHP 4 )

mcal_event_init --  Initializes a streams global event structure

Description

int mcal_event_init ( int stream)

mcal_event_init() initializes a streams global event structure. this effectively sets all elements of the structure to 0, or the default settings.

Returns TRUE.

mcal_event_set_alarm

(PHP 3>= 3.0.13, PHP 4 )

mcal_event_set_alarm --  Sets the alarm of the streams global event structure

Description

int mcal_event_set_alarm ( int stream, int alarm)

mcal_event_set_alarm() sets the streams global event structure's alarm to the given minutes before the event.

Returns TRUE.

mcal_event_set_category

(PHP 3>= 3.0.13, PHP 4 )

mcal_event_set_category --  Sets the category of the streams global event structure

Description

int mcal_event_set_category ( int stream, string category)

mcal_event_set_category() sets the streams global event structure's category to the given string.

Returns TRUE.

mcal_event_set_class

(PHP 3>= 3.0.13, PHP 4 )

mcal_event_set_class --  Sets the class of the streams global event structure

Description

int mcal_event_set_class ( int stream, int class)

mcal_event_set_class() sets the streams global event structure's class to the given value. The class is either 1 for public, or 0 for private.

Returns TRUE.

mcal_event_set_description

(PHP 3>= 3.0.13, PHP 4 )

mcal_event_set_description --  Sets the description of the streams global event structure

Description

int mcal_event_set_description ( int stream, string description)

mcal_event_set_description() sets the streams global event structure's description to the given string.

Returns TRUE.

mcal_event_set_end

(PHP 3>= 3.0.13, PHP 4 )

mcal_event_set_end --  Sets the end date and time of the streams global event structure

Description

int mcal_event_set_end ( int stream, int year, int month [, int day [, int hour [, int min [, int sec]]]])

mcal_event_set_end() sets the streams global event structure's end date and time to the given values.

Returns TRUE.

mcal_event_set_recur_daily

(PHP 3>= 3.0.13, PHP 4 )

mcal_event_set_recur_daily --  Sets the recurrence of the streams global event structure

Description

int mcal_event_set_recur_daily ( int stream, int year, int month, int day, int interval)

mcal_event_set_recur_daily() sets the streams global event structure's recurrence to the given value to be reoccuring on a daily basis, ending at the given date.

mcal_event_set_recur_monthly_mday

(PHP 3>= 3.0.13, PHP 4 )

mcal_event_set_recur_monthly_mday --  Sets the recurrence of the streams global event structure

Description

int mcal_event_set_recur_monthly_mday ( int stream, int year, int month, int day, int interval)

mcal_event_set_recur_monthly_mday() sets the streams global event structure's recurrence to the given value to be reoccuring on a monthly by month day basis, ending at the given date.

mcal_event_set_recur_monthly_wday

(PHP 3>= 3.0.13, PHP 4 )

mcal_event_set_recur_monthly_wday --  Sets the recurrence of the streams global event structure

Description

int mcal_event_set_recur_monthly_wday ( int stream, int year, int month, int day, int interval)

mcal_event_set_recur_monthly_wday() sets the streams global event structure's recurrence to the given value to be reoccuring on a monthly by week basis, ending at the given date.

mcal_event_set_recur_none

(PHP 3>= 3.0.15, PHP 4 )

mcal_event_set_recur_none --  Sets the recurrence of the streams global event structure

Description

int mcal_event_set_recur_none ( int stream)

mcal_event_set_recur_none() sets the streams global event structure to not recur (event->recur_type is set to MCAL_RECUR_NONE).

mcal_event_set_recur_weekly

(PHP 3>= 3.0.13, PHP 4 )

mcal_event_set_recur_weekly --  Sets the recurrence of the streams global event structure

Description

int mcal_event_set_recur_weekly ( int stream, int year, int month, int day, int interval, int weekdays)

mcal_event_set_recur_weekly() sets the streams global event structure's recurrence to the given value to be reoccuring on a weekly basis, ending at the given date.

mcal_event_set_recur_yearly

(PHP 3>= 3.0.13, PHP 4 )

mcal_event_set_recur_yearly --  Sets the recurrence of the streams global event structure

Description

int mcal_event_set_recur_yearly ( int stream, int year, int month, int day, int interval)

mcal_event_set_recur_yearly() sets the streams global event structure's recurrence to the given value to be reoccuring on a yearly basis,ending at the given date.

mcal_event_set_start

(PHP 3>= 3.0.13, PHP 4 )

mcal_event_set_start --  Sets the start date and time of the streams global event structure

Description

int mcal_event_set_start ( int stream, int year, int month [, int day [, int hour [, int min [, int sec]]]])

mcal_event_set_start() sets the streams global event structure's start date and time to the given values.

Returns TRUE.

mcal_event_set_title

(PHP 3>= 3.0.13, PHP 4 )

mcal_event_set_title --  Sets the title of the streams global event structure

Description

int mcal_event_set_title ( int stream, string title)

mcal_event_set_title() sets the streams global event structure's title to the given string.

Returns TRUE.

mcal_expunge

(no version information, might be only in CVS)

mcal_expunge --  Deletes all events marked for being expunged.

Description

int mcal_expunge ( int stream)

mcal_expunge() Deletes all events which have been previously marked for deletion.

mcal_fetch_current_stream_event

(PHP 3>= 3.0.13, PHP 4 )

mcal_fetch_current_stream_event --  Returns an object containing the current streams event structure

Description

object mcal_fetch_current_stream_event ( int stream)

mcal_fetch_current_stream_event() returns the current stream's event structure as an object containing:

  • int id - ID of that event.

  • int public - TRUE if the event if public, FALSE if it is private.

  • string category - Category string of the event.

  • string title - Title string of the event.

  • string description - Description string of the event.

  • int alarm - number of minutes before the event to send an alarm/reminder.

  • object start - Object containing a datetime entry.

  • object end - Object containing a datetime entry.

  • int recur_type - recurrence type

  • int recur_interval - recurrence interval

  • datetime recur_enddate - recurrence end date

  • int recur_data - recurrence data

All datetime entries consist of an object that contains:

  • int year - year

  • int month - month

  • int mday - day of month

  • int hour - hour

  • int min - minutes

  • int sec - seconds

  • int alarm - minutes before event to send an alarm

mcal_fetch_event

(PHP 3>= 3.0.13, PHP 4 )

mcal_fetch_event --  Fetches an event from the calendar stream

Description

object mcal_fetch_event ( int mcal_stream, int event_id [, int options])

mcal_fetch_event() fetches an event from the calendar stream specified by id.

Returns an event object consisting of:

  • int id - ID of that event.

  • int public - TRUE if the event if public, FALSE if it is private.

  • string category - Category string of the event.

  • string title - Title string of the event.

  • string description - Description string of the event.

  • int alarm - number of minutes before the event to send an alarm/reminder.

  • object start - Object containing a datetime entry.

  • object end - Object containing a datetime entry.

  • int recur_type - recurrence type

  • int recur_interval - recurrence interval

  • datetime recur_enddate - recurrence end date

  • int recur_data - recurrence data

All datetime entries consist of an object that contains:

  • int year - year

  • int month - month

  • int mday - day of month

  • int hour - hour

  • int min - minutes

  • int sec - seconds

  • int alarm - minutes before event to send an alarm

The possible values for recur_type are:

  • 0 - Indicates that this event does not recur

  • 1 - This event recurs daily

  • 2 - This event recurs on a weekly basis

  • 3 - This event recurs monthly on a specific day of the month (e.g. the 10th of the month)

  • 4 - This event recurs monthly on a sequenced day of the week (e.g. the 3rd Saturday)

  • 5 - This event recurs on an annual basis

mcal_is_leap_year

(PHP 3>= 3.0.13, PHP 4 )

mcal_is_leap_year --  Returns if the given year is a leap year or not

Description

int mcal_is_leap_year ( int year)

mcal_is_leap_year() returns 1 if the given year is a leap year, 0 if not.

mcal_list_alarms

(PHP 3>= 3.0.13, PHP 4 )

mcal_list_alarms --  Return a list of events that has an alarm triggered at the given datetime

Description

array mcal_list_alarms ( int mcal_stream [, int begin_year [, int begin_month [, int begin_day [, int end_year [, int end_month [, int end_day]]]]]])

Returns an array of event ID's that has an alarm going off between the start and end dates, or if just a stream is given, uses the start and end dates in the global event structure.

mcal_list_events() function takes in an optional beginning date and an end date for a calendar stream. An array of event id's that are between the given dates or the internal event dates are returned.

mcal_list_events

(PHP 3>= 3.0.13, PHP 4 )

mcal_list_events --  Return a list of IDs for a date or a range of dates.

Description

array mcal_list_events ( int mcal_stream, object begin_date [, object end_date])

Returns an array of ID's that are between the start and end dates, or if just a stream is given, uses the start and end dates in the global event structure.

mcal_list_events() function takes in an beginning date and an optional end date for a calendar stream. An array of event id's that are between the given dates or the internal event dates are returned.

mcal_next_recurrence

(PHP 3>= 3.0.13, PHP 4 )

mcal_next_recurrence -- Returns the next recurrence of the event

Description

int mcal_next_recurrence ( int stream, int weekstart, array next)

mcal_next_recurrence() returns an object filled with the next date the event occurs, on or after the supplied date. Returns empty date field if event does not occur or something is invalid. Uses weekstart to determine what day is considered the beginning of the week.

mcal_open

(PHP 3>= 3.0.13, PHP 4 )

mcal_open -- Opens up an MCAL connection

Description

int mcal_open ( string calendar, string username, string password [, int options])

Returns an MCAL stream on success, FALSE on error.

mcal_open() opens up an MCAL connection to the specified calendar store. If the optional options is specified, passes the options to that mailbox also. The streams internal event structure is also initialized upon connection.

mcal_popen

(PHP 3>= 3.0.13, PHP 4 )

mcal_popen -- Opens up a persistent MCAL connection

Description

int mcal_popen ( string calendar, string username, string password [, int options])

Returns an MCAL stream on success, FALSE on error.

mcal_popen() opens up an MCAL connection to the specified calendar store. If the optional options is specified, passes the options to that mailbox also. The streams internal event structure is also initialized upon connection.

mcal_rename_calendar

(PHP 3>= 3.0.13, PHP 4 )

mcal_rename_calendar -- Rename an MCAL calendar

Description

string mcal_rename_calendar ( int stream, string old_name, string new_name)

Renames the calendar old_name to new_name.

mcal_reopen

(PHP 3>= 3.0.13, PHP 4 )

mcal_reopen -- Reopens an MCAL connection

Description

int mcal_reopen ( string calendar [, int options])

Reopens an MCAL stream to a new calendar.

mcal_reopen() reopens an MCAL connection to the specified calendar store. If the optional options is specified, passes the options to that mailbox also.

mcal_snooze

(PHP 3>= 3.0.13, PHP 4 )

mcal_snooze -- Turn off an alarm for an event

Description

int mcal_snooze ( int id)

mcal_snooze() turns off an alarm for a calendar event specified by the id.

Returns TRUE.

mcal_store_event

(PHP 3>= 3.0.13, PHP 4 )

mcal_store_event -- Modify an existing event in an MCAL calendar

Description

int mcal_store_event ( int mcal_stream)

mcal_store_event() Stores the modifications to the current global event for the given stream.

Returns the event id of the modified event on success and FALSE on error.

mcal_time_valid

(PHP 3>= 3.0.13, PHP 4 )

mcal_time_valid --  Returns TRUE if the given year, month, day is a valid time

Description

int mcal_time_valid ( int hour, int minutes, int seconds)

mcal_time_valid() Returns TRUE if the given hour, minutes and seconds is a valid time, FALSE if not.

mcal_week_of_year

(PHP 4 )

mcal_week_of_year --  Returns the week number of the given date

Description

int mcal_week_of_year ( int day, int month, int year)

LIV. Mcrypt Encryption Functions

Introdução

This is an interface to the mcrypt library, which supports a wide variety of block algorithms such as DES, TripleDES, Blowfish (default), 3-WAY, SAFER-SK64, SAFER-SK128, TWOFISH, TEA, RC2 and GOST in CBC, OFB, CFB and ECB cipher modes. Additionally, it supports RC6 and IDEA which are considered "non-free".


Requisitos

These functions work using mcrypt. To use it, download libmcrypt-x.x.tar.gz from here and follow the included installation instructions. Windows users will find all the needed compiled mcrypt binaries here.

If you linked against libmcrypt 2.4.x or higher, the following additional block algorithms are supported: CAST, LOKI97, RIJNDAEL, SAFERPLUS, SERPENT and the following stream ciphers: ENIGMA (crypt), PANAMA, RC4 and WAKE. With libmcrypt 2.4.x or higher another cipher mode is also available; nOFB.


Instalação

You need to compile PHP with the --with-mcrypt[=DIR] parameter to enable this extension. DIR is the mcrypt install directory. Make sure you compile libmcrypt with the option --disable-posix-threads.


Configuração durante execução

O comportamento dessas funções podem ser modificado pelas configurações do php.ini.

Tabela 1. Mcrypt configuration options

Name Default Changeable
mcrypt.algorithms_dir NULL PHP_INI_ALL
mcrypt.modes_dir NULL PHP_INI_ALL
For further details and definition of the PHP_INI_* constants see ini_set().


Tipos Resource

Esta extensão não possui nenhum tipo resource.


Constantes Predefinidas

As contantes abaixo são definidas por esta extensão e somente estarão disponíveis quando a extensão foi compilada com o PHP ou carregada dinamicamente durante a execução.

Mcrypt can operate in four block cipher modes (CBC, OFB, CFB, and ECB). If linked against libmcrypt-2.4.x or higher the functions can also operate in the block cipher mode nOFB and in STREAM mode. Below you find a list with all supported encryption modes together with the constants that are defines for the encryption mode. For a more complete reference and discussion see Applied Cryptography by Schneier (ISBN 0-471-11709-9).

  • MCRYPT_MODE_ECB (electronic codebook) is suitable for random data, such as encrypting other keys. Since data there is short and random, the disadvantages of ECB have a favorable negative effect.

  • MCRYPT_MODE_CBC (cipher block chaining) is especially suitable for encrypting files where the security is increased over ECB significantly.

  • MCRYPT_MODE_CFB (cipher feedback) is the best mode for encrypting byte streams where single bytes must be encrypted.

  • MCRYPT_MODE_OFB (output feedback, in 8bit) is comparable to CFB, but can be used in applications where error propagation cannot be tolerated. It's insecure (because it operates in 8bit mode) so it is not recommended to use it.

  • MCRYPT_MODE_NOFB (output feedback, in nbit) is comparable to OFB, but more secure because it operates on the block size of the algorithm.

  • MCRYPT_MODE_STREAM is an extra mode to include some stream algorithms like WAKE or RC4.

Some other mode and random device constants:

MCRYPT_ENCRYPT (integer)

MCRYPT_DECRYPT (integer)

MCRYPT_DEV_RANDOM (integer)

MCRYPT_DEV_URANDOM (integer)

MCRYPT_RAND (integer)


Mcrypt ciphers

Here is a list of ciphers which are currently supported by the mcrypt extension. For a complete list of supported ciphers, see the defines at the end of mcrypt.h. The general rule with the mcrypt-2.2.x API is that you can access the cipher from PHP with MCRYPT_ciphername. With the libmcrypt-2.4.x and libmcrypt-2.5.x API these constants also work, but it is possible to specify the name of the cipher as a string with a call to mcrypt_module_open().

  • MCRYPT_3DES

  • MCRYPT_ARCFOUR_IV (libmcrypt > 2.4.x only)

  • MCRYPT_ARCFOUR (libmcrypt > 2.4.x only)

  • MCRYPT_BLOWFISH

  • MCRYPT_CAST_128

  • MCRYPT_CAST_256

  • MCRYPT_CRYPT

  • MCRYPT_DES

  • MCRYPT_DES_COMPAT (libmcrypt 2.2.x only)

  • MCRYPT_ENIGMA (libmcrypt > 2.4.x only, alias for MCRYPT_CRYPT)

  • MCRYPT_GOST

  • MCRYPT_IDEA (non-free)

  • MCRYPT_LOKI97 (libmcrypt > 2.4.x only)

  • MCRYPT_MARS (libmcrypt > 2.4.x only, non-free)

  • MCRYPT_PANAMA (libmcrypt > 2.4.x only)

  • MCRYPT_RIJNDAEL_128 (libmcrypt > 2.4.x only)

  • MCRYPT_RIJNDAEL_192 (libmcrypt > 2.4.x only)

  • MCRYPT_RIJNDAEL_256 (libmcrypt > 2.4.x only)

  • MCRYPT_RC2

  • MCRYPT_RC4 (libmcrypt 2.2.x only)

  • MCRYPT_RC6 (libmcrypt > 2.4.x only)

  • MCRYPT_RC6_128 (libmcrypt 2.2.x only)

  • MCRYPT_RC6_192 (libmcrypt 2.2.x only)

  • MCRYPT_RC6_256 (libmcrypt 2.2.x only)

  • MCRYPT_SAFER64

  • MCRYPT_SAFER128

  • MCRYPT_SAFERPLUS (libmcrypt > 2.4.x only)

  • MCRYPT_SERPENT(libmcrypt > 2.4.x only)

  • MCRYPT_SERPENT_128 (libmcrypt 2.2.x only)

  • MCRYPT_SERPENT_192 (libmcrypt 2.2.x only)

  • MCRYPT_SERPENT_256 (libmcrypt 2.2.x only)

  • MCRYPT_SKIPJACK (libmcrypt > 2.4.x only)

  • MCRYPT_TEAN (libmcrypt 2.2.x only)

  • MCRYPT_THREEWAY

  • MCRYPT_TRIPLEDES (libmcrypt > 2.4.x only)

  • MCRYPT_TWOFISH (for older mcrypt 2.x versions, or mcrypt > 2.4.x )

  • MCRYPT_TWOFISH128 (TWOFISHxxx are available in newer 2.x versions, but not in the 2.4.x versions)

  • MCRYPT_TWOFISH192

  • MCRYPT_TWOFISH256

  • MCRYPT_WAKE (libmcrypt > 2.4.x only)

  • MCRYPT_XTEA (libmcrypt > 2.4.x only)

You must (in CFB and OFB mode) or can (in CBC mode) supply an initialization vector (IV) to the respective cipher function. The IV must be unique and must be the same when decrypting/encrypting. With data which is stored encrypted, you can take the output of a function of the index under which the data is stored (e.g. the MD5 key of the filename). Alternatively, you can transmit the IV together with the encrypted data (see chapter 9.3 of Applied Cryptography by Schneier (ISBN 0-471-11709-9) for a discussion of this topic).


Exemplos

Mcrypt can be used to encrypt and decrypt using the above mentioned ciphers. If you linked against libmcrypt-2.2.x, the four important mcrypt commands (mcrypt_cfb(), mcrypt_cbc(), mcrypt_ecb(), and mcrypt_ofb()) can operate in both modes which are named MCRYPT_ENCRYPT and MCRYPT_DECRYPT, respectively.

Exemplo 1. Encrypt an input value with TripleDES under 2.2.x in ECB mode

<?php
$key = "this is a secret key";
$input = "Let us meet at 9 o'clock at the secret place.";

$encrypted_data = mcrypt_ecb (MCRYPT_3DES, $key, $input, MCRYPT_ENCRYPT);
?>
This example will give you the encrypted data as a string in $encrypted_data.

If you linked against libmcrypt 2.4.x or 2.5.x, these functions are still available, but it is recommended that you use the advanced functions.

Exemplo 2. Encrypt an input value with TripleDES under 2.4.x and higher in ECB mode

<?php
    $key = "this is a secret key";
    $input = "Let us meet at 9 o'clock at the secret place.";

    $td = mcrypt_module_open ('tripledes', '', 'ecb', '');
    $iv = mcrypt_create_iv (mcrypt_enc_get_iv_size ($td), MCRYPT_RAND);
    mcrypt_generic_init ($td, $key, $iv);
    $encrypted_data = mcrypt_generic ($td, $input);
    mcrypt_generic_deinit ($td);
    mcrypt_module_close ($td);
?>
This example will give you the encrypted data as a string in $encrypted_data. For a full example see mcrypt_module_open().

Índice
mcrypt_cbc -- Encrypt/decrypt data in CBC mode
mcrypt_cfb -- Encrypt/decrypt data in CFB mode
mcrypt_create_iv --  Create an initialization vector (IV) from a random source
mcrypt_decrypt -- Decrypts crypttext with given parameters
mcrypt_ecb -- Encrypt/decrypt data in ECB mode
mcrypt_enc_get_algorithms_name -- Returns the name of the opened algorithm
mcrypt_enc_get_block_size -- Returns the blocksize of the opened algorithm
mcrypt_enc_get_iv_size -- Returns the size of the IV of the opened algorithm
mcrypt_enc_get_key_size -- Returns the maximum supported keysize of the opened mode
mcrypt_enc_get_modes_name -- Returns the name of the opened mode
mcrypt_enc_get_supported_key_sizes -- Returns an array with the supported keysizes of the opened algorithm
mcrypt_enc_is_block_algorithm_mode -- Checks whether the encryption of the opened mode works on blocks
mcrypt_enc_is_block_algorithm -- Checks whether the algorithm of the opened mode is a block algorithm
mcrypt_enc_is_block_mode -- Checks whether the opened mode outputs blocks
mcrypt_enc_self_test -- This function runs a self test on the opened module
mcrypt_encrypt -- Encrypts plaintext with given parameters
mcrypt_generic_deinit --  This function deinitializes an encryption module
mcrypt_generic_end -- This function terminates encryption
mcrypt_generic_init -- This function initializes all buffers needed for encryption
mcrypt_generic -- This function encrypts data
mcrypt_get_block_size -- Get the block size of the specified cipher
mcrypt_get_cipher_name -- Get the name of the specified cipher
mcrypt_get_iv_size -- Returns the size of the IV belonging to a specific cipher/mode combination
mcrypt_get_key_size -- Get the key size of the specified cipher
mcrypt_list_algorithms -- Get an array of all supported ciphers
mcrypt_list_modes -- Get an array of all supported modes
mcrypt_module_close --  Close the mcrypt module
mcrypt_module_get_algo_block_size -- Returns the blocksize of the specified algorithm
mcrypt_module_get_algo_key_size -- Returns the maximum supported keysize of the opened mode
mcrypt_module_get_supported_key_sizes -- Returns an array with the supported keysizes of the opened algorithm
mcrypt_module_is_block_algorithm_mode -- This function returns if the the specified module is a block algorithm or not
mcrypt_module_is_block_algorithm -- This function checks whether the specified algorithm is a block algorithm
mcrypt_module_is_block_mode -- This function returns if the the specified mode outputs blocks or not
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 on the specified module
mcrypt_ofb -- Encrypt/decrypt data in OFB mode
mdecrypt_generic -- This function decrypts data

mcrypt_cbc

(PHP 3>= 3.0.8, PHP 4 )

mcrypt_cbc -- Encrypt/decrypt data in CBC mode

Description

string mcrypt_cbc ( int cipher, string key, string data, int mode [, string iv])

string mcrypt_cbc ( string cipher, string key, string data, int mode [, string iv])

The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x or higher.

This function should not be used anymore, see mcrypt_generic() and mdecrypt_generic() for replacements.

mcrypt_cfb

(PHP 3>= 3.0.8, PHP 4 )

mcrypt_cfb -- Encrypt/decrypt data in CFB mode

Description

string mcrypt_cfb ( int cipher, string key, string data, int mode, string iv)

string mcrypt_cfb ( string cipher, string key, string data, int mode [, string iv])

The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x or higher.

This function should not be used anymore, see mcrypt_generic() and mdecrypt_generic() for replacements.

mcrypt_create_iv

(PHP 3>= 3.0.8, PHP 4 )

mcrypt_create_iv --  Create an initialization vector (IV) from a random source

Description

string mcrypt_create_iv ( int size, int source)

mcrypt_create_iv() is used to create an IV.

mcrypt_create_iv() takes two arguments, size determines the size of the IV, source specifies the source of the IV.

The source can be MCRYPT_RAND (system random number generator), MCRYPT_DEV_RANDOM (read data from /dev/random) and MCRYPT_DEV_URANDOM (read data from /dev/urandom). If you use MCRYPT_RAND, make sure to call srand() before to initialize the random number generator.

Exemplo 1. mcrypt_create_iv() example

<?php
    $size = mcrypt_get_iv_size (MCRYPT_CAST_256, MCRYPT_MODE_CFB);
    $iv = mcrypt_create_iv ($size, MCRYPT_DEV_RANDOM);
?>

The IV is only meant to give an alternative seed to the encryption routines. This IV does not need to be secret at all, though it can be desirable. You even can send it along with your ciphertext without loosing security.

More information can be found at http://www.ciphersbyritter.com/GLOSSARY.HTM#IV, http://fn2.freenet.edmonton.ab.ca/~jsavard/crypto/co0409.htm and in chapter 9.3 of Applied Cryptography by Schneier (ISBN 0-471-11709-9) for a discussion of this topic.

mcrypt_decrypt

(PHP 4 >= 4.0.2)

mcrypt_decrypt -- Decrypts crypttext with given parameters

Description

string mcrypt_decrypt ( string cipher, string key, string data, string mode [, string iv])

mcrypt_decrypt() decrypts the data and returns the unencrypted data.

Cipher is one of the MCRYPT_ciphername constants of the name of the algorithm as string.

Key is the key with which the data is encrypted. If it's smaller that the required keysize, it is padded with '\0'.

Data is the data that will be decrypted with the given cipher and mode. If the size of the data is not n * blocksize, the data will be padded with '\0'.

Mode is one of the MCRYPT_MODE_modename constants of one of "ecb", "cbc", "cfb", "ofb", "nofb" or "stream".

The IV parameter is used for the initialisation in CBC, CFB, OFB modes, and in some algorithms in STREAM mode. If you do not supply an IV, while it is needed for an algorithm, the function issues a warning and uses an IV with all bytes set to '\0'.

mcrypt_ecb

(PHP 3>= 3.0.8, PHP 4 )

mcrypt_ecb -- Encrypt/decrypt data in ECB mode

Description

string mcrypt_ecb ( int cipher, string key, string data, int mode)

string mcrypt_ecb ( string cipher, string key, string data, int mode [, string iv])

The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x or higher.

This function should not be used anymore, see mcrypt_generic() and mdecrypt_generic() for replacements.

mcrypt_enc_get_algorithms_name

(PHP 4 >= 4.0.2)

mcrypt_enc_get_algorithms_name -- Returns the name of the opened algorithm

Description

string mcrypt_enc_get_algorithms_name ( resource td)

This function returns the name of the algorithm.

Exemplo 1. mcrypt_enc_get_algorithms_name() example

<?php
    $td = mcrypt_module_open (MCRYPT_CAST_256, '', MCRYPT_MODE_CFB, '');
    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";
?>

Prints:
CAST-256
CAST-256

mcrypt_enc_get_block_size

(PHP 4 >= 4.0.2)

mcrypt_enc_get_block_size -- Returns the blocksize of the opened algorithm

Description

int mcrypt_enc_get_block_size ( resource td)

This function returns the block size of the algorithm specified by the encryption descriptor td in bytes.

mcrypt_enc_get_iv_size

(PHP 4 >= 4.0.2)

mcrypt_enc_get_iv_size -- Returns the size of the IV of the opened algorithm

Description

int mcrypt_enc_get_iv_size ( resource td)

This function returns the size of the iv of the algorithm specified by the encryption descriptor in bytes. If it returns '0' then the IV is ignored in the algorithm. An IV is used in cbc, cfb and ofb modes, and in some algorithms in stream mode.

mcrypt_enc_get_key_size

(PHP 4 >= 4.0.2)

mcrypt_enc_get_key_size -- Returns the maximum supported keysize of the opened mode

Description

int mcrypt_enc_get_key_size ( resource td)

This function returns the maximum supported key size of the algorithm specified by the encryption descriptor td in bytes.

mcrypt_enc_get_modes_name

(PHP 4 >= 4.0.2)

mcrypt_enc_get_modes_name -- Returns the name of the opened mode

Description

string mcrypt_enc_get_modes_name ( resource td)

This function returns the name of the mode.

Exemplo 1. mcrypt_enc_get_modes_name() example

<?php
    $td = mcrypt_module_open (MCRYPT_CAST_256, '', MCRYPT_MODE_CFB, '');
    echo mcrypt_enc_get_modes_name($td). "\n";
  
    $td = mcrypt_module_open ('cast-256', '', 'ecb', '');
    echo mcrypt_enc_get_modes_name($td). "\n";
?>

Prints:
CFB
ECB

mcrypt_enc_get_supported_key_sizes

(PHP 4 >= 4.0.2)

mcrypt_enc_get_supported_key_sizes -- Returns an array with the supported keysizes of the opened algorithm

Description

array mcrypt_enc_get_supported_key_sizes ( resource td)

Returns an array with the key sizes supported by the algorithm specified by the encryption descriptor. If it returns an empty array then all key sizes between 1 and mcrypt_enc_get_key_size() are supported by the algorithm.

Exemplo 1. mcrypt_enc_get_supported_key_sizes() example

<?php
    $td = mcrypt_module_open ('rijndael-256', '', 'ecb', '');
    var_dump (mcrypt_enc_get_supported_key_sizes($td));
?>

This will print:

array(3) {
  [0]=>
  int(16)
  [1]=>
  int(24)
  [2]=>
  int(32)
}
?>

mcrypt_enc_is_block_algorithm_mode

(PHP 4 >= 4.0.2)

mcrypt_enc_is_block_algorithm_mode -- Checks whether the encryption of the opened mode works on blocks

Description

bool mcrypt_enc_is_block_algorithm_mode ( resource td)

This function returns TRUE if the mode is for use with block algorithms, otherwise it returns FALSE. (eg. FALSE for stream, and TRUE for cbc, cfb, ofb).

mcrypt_enc_is_block_algorithm

(PHP 4 >= 4.0.2)

mcrypt_enc_is_block_algorithm -- Checks whether the algorithm of the opened mode is a block algorithm

Description

bool mcrypt_enc_is_block_algorithm ( resource td)

This function returns TRUE if the algorithm is a block algorithm, or FALSE if it is a stream algorithm.

mcrypt_enc_is_block_mode

(PHP 4 >= 4.0.2)

mcrypt_enc_is_block_mode -- Checks whether the opened mode outputs blocks

Description

bool mcrypt_enc_is_block_mode ( resource td)

This function returns TRUE if the mode outputs blocks of bytes or FALSE if it outputs bytes. (eg. TRUE for cbc and ecb, and FALSE for cfb and stream).

mcrypt_enc_self_test

(PHP 4 >= 4.0.2)

mcrypt_enc_self_test -- This function runs a self test on the opened module

Description

bool mcrypt_enc_self_test ( resource td)

This function runs the self test on the algorithm specified by the descriptor td. If the self test succeeds it returns FALSE. In case of an error, it returns TRUE.

mcrypt_encrypt

(PHP 4 >= 4.0.2)

mcrypt_encrypt -- Encrypts plaintext with given parameters

Description

string mcrypt_encrypt ( string cipher, string key, string data, string mode [, string iv])

mcrypt_encrypt() encrypts the data and returns the encrypted data.

Cipher is one of the MCRYPT_ciphername constants of the name of the algorithm as string.

Key is the key with which the data will be encrypted. If it's smaller that the required keysize, it is padded with '\0'. It is better not to use ASCII strings for keys. It is recommended to use the mhash functions to create a key from a string.

Data is the data that will be encrypted with the given cipher and mode. If the size of the data is not n * blocksize, the data will be padded with '\0'. The returned crypttext can be larger that the size of the data that is given by data.

Mode is one of the MCRYPT_MODE_modename constants of one of "ecb", "cbc", "cfb", "ofb", "nofb" or "stream".

The IV parameter is used for the initialisation in CBC, CFB, OFB modes, and in some algorithms in STREAM mode. If you do not supply an IV, while it is needed for an algorithm, the function issues a warning and uses an IV with all bytes set to '\0'.

Exemplo 1. mcrypt_encrypt() Example

<?php
    $iv = mcrypt_create_iv (mcrypt_get_iv_size (MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND);
    $key = "This is a very secret key";
    $text = "Meet me at 11 o'clock behind the monument.";
    echo strlen ($text)."\n";

    $crypttext = mcrypt_encrypt (MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_ECB, $iv);
    echo strlen ($crypttext)."\n";
?>

The above example will print out:
42
64

See also mcrypt_module_open() for a more advanced API and an example.

mcrypt_generic_deinit

(PHP 4 >= 4.1.1)

mcrypt_generic_deinit --  This function deinitializes an encryption module

Description

bool mcrypt_generic_deinit ( resource td)

This function terminates encryption specified by the encryption descriptor (td). It clears all buffers, but does not close the module. You need to call mcrypt_module_close() yourself. (But PHP does this for you at the end of the script. Returns FALSE on error, or TRUE on success.

See for an example mcrypt_module_open() and the entry on mcrypt_generic_init().

mcrypt_generic_end

(PHP 4 >= 4.0.2)

mcrypt_generic_end -- This function terminates encryption

Description

bool mcrypt_generic_end ( resource td)

This function is deprecated, use mcrypt_generic_deinit() instead. It can cause crashes when used with mcrypt_module_close() due to multiple buffer frees.

This function terminates encryption specified by the encryption descriptor (td). Actually it clears all buffers, and closes all the modules used. Returns FALSE on error, or TRUE on success.

mcrypt_generic_init

(PHP 4 >= 4.0.2)

mcrypt_generic_init -- This function initializes all buffers needed for encryption

Description

int mcrypt_generic_init ( resource td, string key, string iv)

The maximum length of the key should be the one obtained by calling mcrypt_enc_get_key_size() and every value smaller than this is legal. The IV should normally have the size of the algorithms block size, but you must obtain the size by calling mcrypt_enc_get_iv_size(). IV is ignored in ECB. IV MUST exist in CFB, CBC, STREAM, nOFB and OFB modes. It needs to be random and unique (but not secret). The same IV must be used for encryption/decryption. If you do not want to use it you should set it to zeros, but this is not recommended. The function returns a negative value on error.

You need to call this function before every call to mcrypt_generic() or mdecrypt_generic().

See for an example mcrypt_module_open() and the entry on mcrypt_generic_deinit().

mcrypt_generic

(PHP 4 >= 4.0.2)

mcrypt_generic -- This function encrypts data

Description

string mcrypt_generic ( resource td, string data)

This function encrypts data. The data is padded with "\0" to make sure the length of the data is n * blocksize. This function returns the encrypted data. Note that the length of the returned string can in fact be longer then the input, due to the padding of the data.

The encryption handle should alwayws be initialized with mcrypt_generic_init() with a key and an IV before calling this function. Where the encryption is done, you should free the encryption buffers by calling mcrypt_generic_deinit(). See mcrypt_module_open() for an example.

See also mdecrypt_generic(), mcrypt_generic_init() and mcrypt_generic_deinit().

mcrypt_get_block_size

(PHP 3>= 3.0.8, PHP 4 )

mcrypt_get_block_size -- Get the block size of the specified cipher

Description

int mcrypt_get_block_size ( int cipher)

int mcrypt_get_block_size ( string cipher, string module)

The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x or 2.5.x.

mcrypt_get_block_size() is used to get the size of a block of the specified cipher (in combination with an encryption mode).

This example shows how to use this function when linked against libmcrypt 2.4.x and 2.5.x.

Exemplo 1. mcrypt_get_block_size() example

<?php
    echo mcrypt_get_block_size ('tripledes', 'ecb');
?>

Prints:
8

See also: mcrypt_get_key_size() and mcrypt_encrypt().

mcrypt_get_cipher_name

(PHP 3>= 3.0.8, PHP 4 )

mcrypt_get_cipher_name -- Get the name of the specified cipher

Description

string mcrypt_get_cipher_name ( int cipher)

string mcrypt_get_cipher_name ( string cipher)

mcrypt_get_cipher_name() is used to get the name of the specified cipher.

mcrypt_get_cipher_name() takes the cipher number as an argument (libmcrypt 2.2.x) or takes the cipher name as an argument (libmcrypt 2.4.x or higher) and returns the name of the cipher or FALSE, if the cipher does not exist.

Exemplo 1. mcrypt_get_cipher_name() Example

<?php
   $cipher = MCRYPT_TripleDES;

   echo mcrypt_get_cipher_name ($cipher);
?>

The above example will produce:
3DES

mcrypt_get_iv_size

(PHP 4 >= 4.0.2)

mcrypt_get_iv_size -- Returns the size of the IV belonging to a specific cipher/mode combination

Description

int mcrypt_get_iv_size ( resource td)

int mcrypt_get_iv_size ( string cipher, string mode)

The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x or higher.

mcrypt_get_iv_size() returns the size of the Initialisation Vector (IV) in bytes. On error the function returns FALSE. If the IV is ignored in the specified cipher/mode combination zero is returned.

cipher is one of the MCRYPT_ciphername constants of the name of the algorithm as string.

mode is one of the MCRYPT_MODE_modename constants of one of "ecb", "cbc", "cfb", "ofb", "nofb" or "stream".

td is the resource that is returned by mcrypt_module_open().

Exemplo 1. mcrypt_create_iv() example

<?php
    $size = mcrypt_get_iv_size (MCRYPT_CAST_256, MCRYPT_MODE_CFB);

    $size = mcrypt_get_iv_size ('des', 'ecb');
?>

See also: mcrypt_create_iv()

mcrypt_get_key_size

(PHP 3>= 3.0.8, PHP 4 )

mcrypt_get_key_size -- Get the key size of the specified cipher

Description

int mcrypt_get_key_size ( int cipher)

int mcrypt_get_key_size ( string cipher, string module)

The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x or 2.5.x.

mcrypt_get_key_size() is used to get the size of a key of the specified cipher (in combination with an encryption mode).

This example shows how to use this function when linked against libmcrypt 2.4.x and 2.5.x.

Exemplo 1. mcrypt_get_block_size() example

<?php
    echo mcrypt_get_key_size ('tripledes', 'ecb');
?>

Prints:
24

See also: mcrypt_get_block_size() and mcrypt_encrypt().

mcrypt_list_algorithms

(PHP 4 >= 4.0.2)

mcrypt_list_algorithms -- Get an array of all supported ciphers

Description

array mcrypt_list_algorithms ( [string lib_dir])

mcrypt_list_algorithms() is used to get an array of all supported algorithms in the lib_dir parameter.

mcrypt_list_algorithms() takes an optional lib_dir parameter which specifies the directory where all algorithms are located. If not specifies, the value of the mcrypt.algorithms_dir php.ini directive is used.

Exemplo 1. mcrypt_list_algorithms() Example

<?php
    $algorithms = mcrypt_list_algorithms ("/usr/local/lib/libmcrypt");

    foreach ($algorithms as $cipher) {
        echo "$cipher<br />\n";
    }
?>

The above example will produce a list with all supported algorithms in the "/usr/local/lib/libmcrypt" directory.

mcrypt_list_modes

(PHP 4 >= 4.0.2)

mcrypt_list_modes -- Get an array of all supported modes

Description

array mcrypt_list_modes ( [string lib_dir])

mcrypt_list_modes() is used to get an array of all supported modes in the lib_dir.

mcrypt_list_modes() takes as optional parameter a directory which specifies the directory where all modes are located. If not specifies, the value of the mcrypt.modes_dir php.ini directive is used.

Exemplo 1. mcrypt_list_modes() Example

<?php
    $modes = mcrypt_list_modes ();

    foreach ($modes as $mode) {
        echo "$mode <br />\n";
    }
?>

The above example will produce a list with all supported algorithms in the default mode directory. If it is not set with the ini directive mcrypt.modes_dir, the default directory of mcrypt is used (which is /usr/local/lib/libmcrypt).

mcrypt_module_close

(PHP 4 >= 4.0.2)

mcrypt_module_close --  Close the mcrypt module

Description

bool mcrypt_module_close ( resource td)

This function closes the specified encryption handle.

See mcrypt_module_open() for an example.

mcrypt_module_get_algo_block_size

(PHP 4 >= 4.0.2)

mcrypt_module_get_algo_block_size -- Returns the blocksize of the specified algorithm

Description

int mcrypt_module_get_algo_block_size ( string algorithm [, string lib_dir])

This function returns the block size of the algorithm specified in bytes. The optional lib_dir parameter can contain the location where the mode module is on the system.

mcrypt_module_get_algo_key_size

(PHP 4 >= 4.0.2)

mcrypt_module_get_algo_key_size -- Returns the maximum supported keysize of the opened mode

Description

int mcrypt_module_get_algo_key_size ( string algorithm [, string lib_dir])

This function returns the maximum supported key size of the algorithm specified in bytes. The optional lib_dir parameter can contain the location where the mode module is on the system.

mcrypt_module_get_supported_key_sizes

(PHP 4 >= 4.0.2)

mcrypt_module_get_supported_key_sizes -- Returns an array with the supported keysizes of the opened algorithm

Description

array mcrypt_module_get_supported_key_sizes ( string algorithm [, string lib_dir])

Returns an array with the key sizes supported by the specified algorithm. If it returns an empty array then all key sizes between 1 and mcrypt_module_get_algo_key_size() are supported by the algorithm. The optional lib_dir parameter can contain the location where the mode module is on the system.

See also mcrypt_enc_get_supported_key_sizes() which is used on open encryption modules.

mcrypt_module_is_block_algorithm_mode

(PHP 4 >= 4.0.2)

mcrypt_module_is_block_algorithm_mode -- This function returns if the the specified module is a block algorithm or not

Description

bool mcrypt_module_is_block_algorithm_mode ( string mode [, string lib_dir])

This function returns TRUE if the mode is for use with block algorithms, otherwise it returns FALSE. (eg. FALSE for stream, and TRUE for cbc, cfb, ofb). The optional lib_dir parameter can contain the location where the mode module is on the system.

mcrypt_module_is_block_algorithm

(PHP 4 >= 4.0.2)

mcrypt_module_is_block_algorithm -- This function checks whether the specified algorithm is a block algorithm

Description

bool mcrypt_module_is_block_algorithm ( string algorithm [, string lib_dir])

This function returns TRUE if the specified algorithm is a block algorithm, or FALSE is it is a stream algorithm. The optional lib_dir parameter can contain the location where the algorithm module is on the system.

mcrypt_module_is_block_mode

(PHP 4 >= 4.0.2)

mcrypt_module_is_block_mode -- This function returns if the the specified mode outputs blocks or not

Description

bool mcrypt_module_is_block_mode ( string mode [, string lib_dir])

This function returns TRUE if the mode outputs blocks of bytes or FALSE if it outputs just bytes. (eg. TRUE for cbc and ecb, and FALSE for cfb and stream). The optional lib_dir parameter can contain the location where the mode module is on the system.

mcrypt_module_open

(PHP 4 >= 4.0.2)

mcrypt_module_open -- This function opens the module of the algorithm and the mode to be used

Description

resource mcrypt_module_open ( string algorithm, string algorithm_directory, string mode, string mode_directory)

This function opens the module of the algorithm and the mode to be used. The name of the algorithm is specified in algorithm, eg. "twofish" or is one of the MCRYPT_ciphername constants. The module is closed by calling mcrypt_module_close(). Normally it returns an encryption descriptor, or FALSE on error.

The algorithm_directory and mode_directory are used to locate the encryption modules. When you supply a directory name, it is used. When you set one of these to the empty string (""), the value set by the mcrypt.algorithms_dir or mcrypt.modes_dir ini-directive is used. When these are not set, the default directories that are used are the ones that were compiled in into libmcrypt (usally /usr/local/lib/libmcrypt).

Exemplo 1. mcrypt_module_open() Example

<?php
    $td = mcrypt_module_open (MCRYPT_DES, '', MCRYPT_MODE_ECB, '/usr/lib/mcrypt-modes');
    $td = mcrypt_module_open ('rijndael-256', '', 'ofb', '');
?>

The first line in the example above will try to open the DES cipher from the default directory and the EBC mode from the directory /usr/lib/mcrypt-modes. The second example uses strings as name for the cipher an dmode, this only works when the extension is linked against libmcrypt 2.4.x or 2.5.x.

Exemplo 2. Using mcrypt_module_open() in encryption

<?php
    /* Open the cipher */
    $td = mcrypt_module_open ('rijndael-256', '', 'ofb', '');

    /* Create the IV and determine the keysize length */
    $iv = mcrypt_create_iv (mcrypt_enc_get_iv_size($td), MCRYPT_DEV_RANDOM);
    $ks = mcrypt_enc_get_key_size ($td);

    /* Create key */
    $key = substr (md5 ('very secret key'), 0, $ks);

    /* Intialize encryption */
    mcrypt_generic_init ($td, $key, $iv);

    /* Encrypt data */
    $encrypted = mcrypt_generic ($td, 'This is very important data');

    /* Terminate encryption handler */
    mcrypt_generic_deinit ($td);

    /* Initialize encryption module for decryption */
    mcrypt_generic_init ($td, $key, $iv);

    /* Decrypt encrypted string */
    $decrypted = mdecrypt_generic ($td, $encrypted);

    /* Terminate decryption handle and close module */
    mcrypt_generic_deinit ($td);
    mcrypt_module_close ($td);

    /* Show string */
    echo trim ($decrypted)."\n";
?>

The first line in the example above will try to open the DES cipher from the default directory and the EBC mode from the directory /usr/lib/mcrypt-modes. The second example uses strings as name for the cipher an dmode, this only works when the extension is linked against libmcrypt 2.4.x or 2.5.x.

See also mcrypt_module_close(), mcrypt_generic(), mdecrypt_generic(), mcrypt_generic_init() and mcrypt_generic_deinit().

mcrypt_module_self_test

(PHP 4 >= 4.0.2)

mcrypt_module_self_test -- This function runs a self test on the specified module

Description

bool mcrypt_module_self_test ( string algorithm [, string lib_dir])

This function runs the self test on the algorithm specified. The optional lib_dir parameter can contain the location of where the algorithm module is on the system.

The function returns TRUE if the self test succeeds, or FALSE when if fails.

mcrypt_ofb

(PHP 3>= 3.0.8, PHP 4 )

mcrypt_ofb -- Encrypt/decrypt data in OFB mode

Description

string mcrypt_ofb ( int cipher, string key, string data, int mode, string iv)

string mcrypt_ofb ( string cipher, string key, string data, int mode [, string iv])

The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x or higher.

This function should not be used anymore, see mcrypt_generic() and mdecrypt_generic() for replacements.

mdecrypt_generic

(PHP 4 >= 4.0.2)

mdecrypt_generic -- This function decrypts data

Description

string mdecrypt_generic ( resource td, string data)

This function decrypts data. Note that the length of the returned string can in fact be longer then the unencrypted string, due to the padding of the data.

Exemplo 1. mdecrypt_generic() Example

<?php
    /* Data */
    $key = 'this is a very long key, even too long for the cipher';
    $plain_text = 'very important data';
   
    /* Open module, and create IV */ 
    $td = mcrypt_module_open ('des', '', 'ecb', '');
    $key = substr ($key, 0, mcrypt_enc_get_key_size ($td));
    $iv_size = mcrypt_enc_get_iv_size ($td);
    $iv = mcrypt_create_iv ($iv_size, MCRYPT_RAND);

    /* Initialize encryption handle */
    if (mcrypt_generic_init ($td, $key, $iv) != -1) {

        /* Encrypt data */
        $c_t = mcrypt_generic ($td, $plain_text);
        mcrypt_generic_deinit ($td);

        /* Reinitialize buffers for decryption */
        mcrypt_generic_init ($td, $key, $iv);
        $p_t = mdecrypt_generic ($td, $c_t);

        /* Clean up */
        mcrypt_generic_deinit ($td);
        mcrypt_module_close ($td);
    }

    if (strncmp ($p_t, $plain_text, strlen($plain_text)) == 0) {
        echo "ok\n";
    } else {
        echo "error\n";
    }
?>

The above example shows how to check if the data before the encryption is the same as the data after the decryption. It is very important to reinitialize the encryption buffer with mcrypt_generic_init() before you try to decrypt the data.

The decryption handle should alwayws be initialized with mcrypt_generic_init() with a key and an IV before calling this function. Where the encryption is done, you should free the encryption buffers by calling mcrypt_generic_deinit(). See mcrypt_module_open() for an example.

See also mcrypt_generic(), mcrypt_generic_init() and mcrypt_generic_deinit().

LV. MCVE Payment Functions

Introdução

These functions interface the MCVE API (libmcve), allowing you to work directly with MCVE from your PHP scripts. MCVE is Main Street Softworks' solution to direct credit card processing. It lets you directly address the credit card clearing houses via your *nix box, modem and/or internet connection (bypassing the need for an additional service such as Authorize.Net or Pay Flow Pro). Using the MCVE module for PHP, you can process credit cards directly through MCVE via your PHP scripts. The following references will outline the process.

Nota: MCVE is the replacement for RedHat's CCVS. They contracted with RedHat in late 2001 to migrate all existing clientelle to the MCVE platform.

Nota: This extension is not available on Windows platforms.


Instalação

To enable MCVE Support in PHP, first verify your LibMCVE installation directory. You will then need to configure PHP with the --with-mcve option. If you use this option without specifying the path to your MCVE installation, PHP will attempt to look in the default LibMCVE Install location (/usr/local). If MCVE is in a non-standard location, run configure with: --with-mcve=$mcve_path, where $mcve_path is the path to your MCVE installation. Please note that MCVE support requires that $mcve_path/lib and $mcve_path/include exist, and include mcve.h under the include directory and libmcve.so and/or libmcve.a under the lib directory.

Since MCVE has true server/client separation, there are no additional requirements for running PHP with MCVE support. To test your MCVE extension in PHP, you may connect to testbox.mcve.com on port 8333 for IP, or port 8444 for SSL using the MCVE PHP API. Use 'vitale' for your username, and 'test' for your password. Additional information about test facilities are available at http://www.mcve.com/.


Veja Também

Additional documentation about MCVE's PHP API can be found at http://www.mcve.com/docs/phpapi.pdf. Main Street's documentation is complete and should be the primary reference for functions.

Índice
mcve_adduser --  Add an MCVE user using usersetup structure
mcve_adduserarg --  Add a value to user configuration structure
mcve_bt --  Get unsettled batch totals
mcve_checkstatus --  Check to see if a transaction has completed
mcve_chkpwd --  Verify Password
mcve_chngpwd --  Change the system administrator's password
mcve_completeauthorizations --  Number of complete authorizations in queue, returning an array of their identifiers
mcve_connect --  Establish the connection to MCVE
mcve_connectionerror --  Get a textual representation of why a connection failed
mcve_deleteresponse --  Delete specified transaction from MCVE_CONN structure
mcve_deletetrans --  Delete specified transaction from MCVE_CONN structure
mcve_deleteusersetup --  Deallocate data associated with usersetup structure
mcve_deluser --  Delete an MCVE user account
mcve_destroyconn --  Destroy the connection and MCVE_CONN structure
mcve_destroyengine --  Free memory associated with IP/SSL connectivity
mcve_disableuser --  Disable an active MCVE user account
mcve_edituser --  Edit MCVE user using usersetup structure
mcve_enableuser --  Enable an inactive MCVE user account
mcve_force --  Send a FORCE to MCVE. (typically, a phone-authorization)
mcve_getcell --  Get a specific cell from a comma delimited response by column name
mcve_getcellbynum --  Get a specific cell from a comma delimited response by column number
mcve_getcommadelimited --  Get the RAW comma delimited data returned from MCVE
mcve_getheader --  Get the name of the column in a comma-delimited response
mcve_getuserarg --  Grab a value from usersetup structure
mcve_getuserparam --  Get a user response parameter
mcve_gft --  Audit MCVE for Failed transactions
mcve_gl --  Audit MCVE for settled transactions
mcve_gut --  Audit MCVE for Unsettled Transactions
mcve_initconn --  Create and initialize an MCVE_CONN structure
mcve_initengine --  Ready the client for IP/SSL Communication
mcve_initusersetup --  Initialize structure to store user data
mcve_iscommadelimited --  Checks to see if response is comma delimited
mcve_liststats --  List statistics for all users on MCVE system
mcve_listusers --  List all users on MCVE system
mcve_maxconntimeout --  The maximum amount of time the API will attempt a connection to MCVE
mcve_monitor --  Perform communication with MCVE (send/receive data) Non-blocking
mcve_numcolumns --  Number of columns returned in a comma delimited response
mcve_numrows --  Number of rows returned in a comma delimited response
mcve_override --  Send an OVERRIDE to MCVE
mcve_parsecommadelimited --  Parse the comma delimited response so mcve_getcell, etc will work
mcve_ping --  Send a ping request to MCVE
mcve_preauth --  Send a PREAUTHORIZATION to MCVE
mcve_preauthcompletion --  Complete a PREAUTHORIZATION... Ready it for settlement
mcve_qc --  Audit MCVE for a list of transactions in the outgoing queue
mcve_responseparam --  Get a custom response parameter
mcve_return --  Issue a RETURN or CREDIT to MCVE
mcve_returncode --  Grab the exact return code from the transaction
mcve_returnstatus --  Check to see if the transaction was successful
mcve_sale --  Send a SALE to MCVE
mcve_setblocking --  Set blocking/non-blocking mode for connection
mcve_setdropfile --  Set the connection method to Drop-File
mcve_setip --  Set the connection method to IP
mcve_setssl --  Set the connection method to SSL
mcve_settimeout --  Set maximum transaction time (per trans)
mcve_settle --  Issue a settlement command to do a batch deposit
mcve_text_avs --  Get a textual representation of the return_avs
mcve_text_code --  Get a textual representation of the return_code
mcve_text_cv --  Get a textual representation of the return_cv
mcve_transactionauth --  Get the authorization number returned for the transaction (alpha-numeric)
mcve_transactionavs --  Get the Address Verification return status
mcve_transactionbatch --  Get the batch number associated with the transaction
mcve_transactioncv --  Get the CVC2/CVV2/CID return status
mcve_transactionid --  Get the unique system id for the transaction
mcve_transactionitem --  Get the ITEM number in the associated batch for this transaction
mcve_transactionssent --  Check to see if outgoing buffer is clear
mcve_transactiontext --  Get verbiage (text) return from MCVE or processing institution
mcve_transinqueue --  Number of transactions in client-queue
mcve_transnew --  Start a new transaction
mcve_transparam --  Add a parameter to a transaction
mcve_transsend --  Finalize and send the transaction
mcve_ub --  Get a list of all Unsettled batches
mcve_uwait --  Wait x microsecs
mcve_verifyconnection --  Set whether or not to PING upon connect to verify connection
mcve_verifysslcert --  Set whether or not to verify the server ssl certificate
mcve_void --  VOID a transaction in the settlement queue

mcve_adduser

(PHP 4 >= 4.2.0)

mcve_adduser --  Add an MCVE user using usersetup structure

Description

int mcve_adduser ( resource conn, string admin_password, int usersetup)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mcve_adduserarg

(PHP 4 >= 4.2.0)

mcve_adduserarg --  Add a value to user configuration structure

Description

int mcve_adduserarg ( resource usersetup, int argtype, string argval)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mcve_bt

(PHP 4 >= 4.2.0)

mcve_bt --  Get unsettled batch totals

Description

int mcve_bt ( resource conn, string username, string password)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mcve_checkstatus

(PHP 4 >= 4.2.0)

mcve_checkstatus --  Check to see if a transaction has completed

Description

int mcve_checkstatus ( resource conn, int identifier)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mcve_chkpwd

(PHP 4 >= 4.2.0)

mcve_chkpwd --  Verify Password

Description

int mcve_chkpwd ( resource conn, string username, string password)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mcve_chngpwd

(PHP 4 >= 4.2.0)

mcve_chngpwd --  Change the system administrator's password

Description

int mcve_chngpwd ( resource conn, string admin_password, string new_password)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mcve_completeauthorizations

(PHP 4 >= 4.2.0)

mcve_completeauthorizations --  Number of complete authorizations in queue, returning an array of their identifiers

Description

int mcve_completeauthorizations ( resource conn, int &array)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mcve_connect

(PHP 4 >= 4.2.0)

mcve_connect --  Establish the connection to MCVE

Description

int mcve_connect ( resource conn)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mcve_connectionerror

(PHP 4 >= 4.3.0)

mcve_connectionerror --  Get a textual representation of why a connection failed

Description

string mcve_connectionerror ( resource conn)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mcve_deleteresponse

(PHP 4 >= 4.2.0)

mcve_deleteresponse --  Delete specified transaction from MCVE_CONN structure

Description

bool mcve_deleteresponse ( resource conn, int identifier)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mcve_deletetrans

(PHP 4 >= 4.3.0)

mcve_deletetrans --  Delete specified transaction from MCVE_CONN structure

Description

bool mcve_deletetrans ( resource conn, int identifier)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mcve_deleteusersetup

(PHP 4 >= 4.2.0)

mcve_deleteusersetup --  Deallocate data associated with usersetup structure

Description

void mcve_deleteusersetup ( resource usersetup)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mcve_deluser

(PHP 4 >= 4.2.0)

mcve_deluser --  Delete an MCVE user account

Description

int mcve_deluser ( resource conn, string admin_password, string username)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mcve_destroyconn

(PHP 4 >= 4.2.0)

mcve_destroyconn --  Destroy the connection and MCVE_CONN structure

Description

void mcve_destroyconn ( resource conn)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mcve_destroyengine

(PHP 4 >= 4.2.0)

mcve_destroyengine --  Free memory associated with IP/SSL connectivity

Description

void mcve_destroyengine ( void)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mcve_disableuser

(PHP 4 >= 4.2.0)

mcve_disableuser --  Disable an active MCVE user account

Description

int mcve_disableuser ( resource conn, string admin_password, string username)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mcve_edituser

(PHP 4 >= 4.2.0)

mcve_edituser --  Edit MCVE user using usersetup structure

Description

int mcve_edituser ( resource conn, string admin_password, int usersetup)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mcve_enableuser

(PHP 4 >= 4.2.0)

mcve_enableuser --  Enable an inactive MCVE user account

Description

int mcve_enableuser ( resource conn, string admin_password, string username)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mcve_force

(PHP 4 >= 4.2.0)

mcve_force --  Send a FORCE to MCVE. (typically, a phone-authorization)

Description

int mcve_force ( resiurce conn, string username, string password, string trackdata, string account, string expdate, float amount, string authcode, string comments, string clerkid, string stationid, int ptrannum)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mcve_getcell

(PHP 4 >= 4.2.0)

mcve_getcell --  Get a specific cell from a comma delimited response by column name

Description

string mcve_getcell ( resource conn, int identifier, string column, int row)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mcve_getcellbynum

(PHP 4 >= 4.2.0)

mcve_getcellbynum --  Get a specific cell from a comma delimited response by column number

Description

string mcve_getcellbynum ( resource conn, int identifier, int column, int row)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mcve_getcommadelimited

(PHP 4 >= 4.2.0)

mcve_getcommadelimited --  Get the RAW comma delimited data returned from MCVE

Description

string mcve_getcommadelimited ( resource conn, int identifier)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mcve_getheader

(PHP 4 >= 4.2.0)

mcve_getheader --  Get the name of the column in a comma-delimited response

Description

string mcve_getheader ( resource conn, int identifier, int column_num)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mcve_getuserarg

(PHP 4 >= 4.2.0)

mcve_getuserarg --  Grab a value from usersetup structure

Description

string mcve_getuserarg ( resource usersetup, int argtype)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mcve_getuserparam

(PHP 4 >= 4.3.0)

mcve_getuserparam --  Get a user response parameter

Description

string mcve_getuserparam ( resource conn, long identifier, int key)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mcve_gft

(PHP 4 >= 4.2.0)

mcve_gft --  Audit MCVE for Failed transactions

Description

int mcve_gft ( resource conn, string username, string password, int type, string account, string clerkid, string stationid, string comments, int ptrannum, string startdate, string enddate)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mcve_gl

(PHP 4 >= 4.2.0)

mcve_gl --  Audit MCVE for settled transactions

Description

int mcve_gl ( int conn, string username, string password, int type, string account, string batch, string clerkid, string stationid, string comments, int ptrannum, string startdate, string enddate)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mcve_gut

(PHP 4 >= 4.2.0)

mcve_gut --  Audit MCVE for Unsettled Transactions

Description

int mcve_gut ( resource conn, string username, string password, int type, string account, string clerkid, string stationid, string comments, int ptrannum, string startdate, string enddate)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mcve_initconn

(PHP 4 >= 4.2.0)

mcve_initconn --  Create and initialize an MCVE_CONN structure

Description

resource mcve_initconn ( void)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mcve_initengine

(PHP 4 >= 4.2.0)

mcve_initengine --  Ready the client for IP/SSL Communication

Description

int mcve_initengine ( string location)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mcve_initusersetup

(PHP 4 >= 4.2.0)

mcve_initusersetup --  Initialize structure to store user data

Description

resource mcve_initusersetup ( void)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mcve_iscommadelimited

(PHP 4 >= 4.2.0)

mcve_iscommadelimited --  Checks to see if response is comma delimited

Description

int mcve_iscommadelimited ( resource conn, int identifier)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mcve_liststats

(PHP 4 >= 4.2.0)

mcve_liststats --  List statistics for all users on MCVE system

Description

int mcve_liststats ( resource conn, string admin_password)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mcve_listusers

(PHP 4 >= 4.2.0)

mcve_listusers --  List all users on MCVE system

Description

int mcve_listusers ( resource conn, string admin_password)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mcve_maxconntimeout

(PHP 4 >= 4.3.0)

mcve_maxconntimeout --  The maximum amount of time the API will attempt a connection to MCVE

Description

bool mcve_maxconntimeout ( resource conn, int secs)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mcve_monitor

(PHP 4 >= 4.2.0)

mcve_monitor --  Perform communication with MCVE (send/receive data) Non-blocking

Description

int mcve_monitor ( resource conn)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mcve_numcolumns

(PHP 4 >= 4.2.0)

mcve_numcolumns --  Number of columns returned in a comma delimited response

Description

int mcve_numcolumns ( resource conn, int identifier)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mcve_numrows

(PHP 4 >= 4.2.0)

mcve_numrows --  Number of rows returned in a comma delimited response

Description

int mcve_numrows ( resource conn, int identifier)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mcve_override

(PHP 4 >= 4.2.0)

mcve_override --  Send an OVERRIDE to MCVE

Description

int mcve_override ( resource conn, string username, string password, string trackdata, string account, string expdate, float amount, string street, string zip, string cv, string comments, string clerkid, string stationid, int ptrannum)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mcve_parsecommadelimited

(PHP 4 >= 4.2.0)

mcve_parsecommadelimited --  Parse the comma delimited response so mcve_getcell, etc will work

Description

int mcve_parsecommadelimited ( resource conn, int identifier)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mcve_ping

(PHP 4 >= 4.3.0)

mcve_ping --  Send a ping request to MCVE

Description

int mcve_ping ( resource conn)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mcve_preauth

(PHP 4 >= 4.2.0)

mcve_preauth --  Send a PREAUTHORIZATION to MCVE

Description

int mcve_preauth ( resource conn, string username, string password, string trackdata, string account, string expdate, float amount, string street, string zip, string cv, string comments, string clerkid, string stationid, int ptrannum)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mcve_preauthcompletion

(PHP 4 >= 4.2.0)

mcve_preauthcompletion --  Complete a PREAUTHORIZATION... Ready it for settlement

Description

int mcve_preauthcompletion ( resource conn, string username, string password, float finalamount, int sid, int ptrannum)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mcve_qc

(PHP 4 >= 4.2.0)

mcve_qc --  Audit MCVE for a list of transactions in the outgoing queue

Description

int mcve_qc ( resource conn, string username, string password, string clerkid, string stationid, string comments, int ptrannum)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mcve_responseparam

(PHP 4 >= 4.3.0)

mcve_responseparam --  Get a custom response parameter

Description

string mcve_responseparam ( resource conn, long identifier, string key)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mcve_return

(PHP 4 >= 4.2.0)

mcve_return --  Issue a RETURN or CREDIT to MCVE

Description

int mcve_return ( int conn, string username, string password, string trackdata, string account, string expdate, float amount, string comments, string clerkid, string stationid, int ptrannum)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mcve_returncode

(PHP 4 >= 4.2.0)

mcve_returncode --  Grab the exact return code from the transaction

Description

int mcve_returncode ( resource conn, int identifier)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mcve_returnstatus

(PHP 4 >= 4.2.0)

mcve_returnstatus --  Check to see if the transaction was successful

Description

int mcve_returnstatus ( resource conn, int identifier)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mcve_sale

(PHP 4 >= 4.2.0)

mcve_sale --  Send a SALE to MCVE

Description

int mcve_sale ( resource conn, string username, string password, string trackdata, string account, string expdate, float amount, string street, string zip, string cv, string comments, string clerkid, string stationid, int ptrannum)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mcve_setblocking

(PHP 4 >= 4.3.0)

mcve_setblocking --  Set blocking/non-blocking mode for connection

Description

int mcve_setblocking ( resource conn, int tf)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mcve_setdropfile

(PHP 4 >= 4.2.0)

mcve_setdropfile --  Set the connection method to Drop-File

Description

int mcve_setdropfile ( resource conn, string directory)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mcve_setip

(PHP 4 >= 4.2.0)

mcve_setip --  Set the connection method to IP

Description

int mcve_setip ( resource conn, string host, int port)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mcve_setssl

(PHP 4 >= 4.2.0)

mcve_setssl --  Set the connection method to SSL

Description

int mcve_setssl ( resource conn, string host, int port)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mcve_settimeout

(PHP 4 >= 4.2.0)

mcve_settimeout --  Set maximum transaction time (per trans)

Description

int mcve_settimeout ( resource conn, int seconds)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mcve_settle

(PHP 4 >= 4.2.0)

mcve_settle --  Issue a settlement command to do a batch deposit

Description

int mcve_settle ( resource conn, string username, string password, string batch)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mcve_text_avs

(PHP 4 >= 4.3.0)

mcve_text_avs --  Get a textual representation of the return_avs

Description

string mcve_text_avs ( string code)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mcve_text_code

(PHP 4 >= 4.3.0)

mcve_text_code --  Get a textual representation of the return_code

Description

string mcve_text_code ( string code)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mcve_text_cv

(PHP 4 >= 4.3.0)

mcve_text_cv --  Get a textual representation of the return_cv

Description

string mcve_text_cv ( int code)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mcve_transactionauth

(PHP 4 >= 4.2.0)

mcve_transactionauth --  Get the authorization number returned for the transaction (alpha-numeric)

Description

string mcve_transactionauth ( resource conn, int identifier)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mcve_transactionavs

(PHP 4 >= 4.2.0)

mcve_transactionavs --  Get the Address Verification return status

Description

int mcve_transactionavs ( resource conn, int identifier)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mcve_transactionbatch

(PHP 4 >= 4.2.0)

mcve_transactionbatch --  Get the batch number associated with the transaction

Description

int mcve_transactionbatch ( resource conn, int identifier)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mcve_transactioncv

(PHP 4 >= 4.2.0)

mcve_transactioncv --  Get the CVC2/CVV2/CID return status

Description

int mcve_transactioncv ( resource conn, int identifier)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mcve_transactionid

(PHP 4 >= 4.2.0)

mcve_transactionid --  Get the unique system id for the transaction

Description

int mcve_transactionid ( resource conn, int identifier)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mcve_transactionitem

(PHP 4 >= 4.2.0)

mcve_transactionitem --  Get the ITEM number in the associated batch for this transaction

Description

int mcve_transactionitem ( resource conn, int identifier)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mcve_transactionssent

(PHP 4 >= 4.2.0)

mcve_transactionssent --  Check to see if outgoing buffer is clear

Description

int mcve_transactionssent ( resource conn)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mcve_transactiontext

(PHP 4 >= 4.2.0)

mcve_transactiontext --  Get verbiage (text) return from MCVE or processing institution

Description

string mcve_transactiontext ( resource conn, int identifier)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mcve_transinqueue

(PHP 4 >= 4.2.0)

mcve_transinqueue --  Number of transactions in client-queue

Description

int mcve_transinqueue ( resource conn)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mcve_transnew

(PHP 4 >= 4.3.0)

mcve_transnew --  Start a new transaction

Description

int mcve_transnew ( resource conn)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mcve_transparam

(PHP 4 >= 4.3.0)

mcve_transparam --  Add a parameter to a transaction

Description

int mcve_transparam ( resource conn, long identifier, int key)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mcve_transsend

(PHP 4 >= 4.3.0)

mcve_transsend --  Finalize and send the transaction

Description

int mcve_transsend ( resource conn, long identifier)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mcve_ub

(PHP 4 >= 4.2.0)

mcve_ub --  Get a list of all Unsettled batches

Description

int mcve_ub ( resource conn, string username, string password)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mcve_uwait

(PHP 4 >= 4.3.0)

mcve_uwait --  Wait x microsecs

Description

int mcve_uwait ( long microsecs)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mcve_verifyconnection

(PHP 4 >= 4.3.0)

mcve_verifyconnection --  Set whether or not to PING upon connect to verify connection

Description

bool mcve_verifyconnection ( resource conn, int tf)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mcve_verifysslcert

(PHP 4 >= 4.3.0)

mcve_verifysslcert --  Set whether or not to verify the server ssl certificate

Description

bool mcve_verifysslcert ( resource conn, int tf)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mcve_void

(PHP 4 >= 4.2.0)

mcve_void --  VOID a transaction in the settlement queue

Description

int mcve_void ( resource conn, string username, string password, int sid, int ptrannum)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

LVI. Mhash - Funções de hash

Introdução

Essas funções são planejadas para trabalhar com mhash. Com o Mhash você pode criar checksums, digests de mensagens, códigos de autenticação de mensagens e mais.

Esta é uma interface para a biblioteca mhash. O mhash suporta uma grande variedade de algoritmos de hash como MD5, SHA1, GOST e muitos outros. Para uma lista completa das hashs suportadas, verifique a documentação do mhash. A regra geral é: você pode acessar o algoritmo de hash a partir do PHP com MHASH_NOMEdoHASH, Por exemplo, para acessar o algoritmo TIGER, você utiliza a constante MHASH_TIGER.


Requisitos

Para usá-las, faça o download da distribuição do mhash em http://mhash.sourceforge.net/ e siga as instruções de instalação inclusas.


Instalação

Você precisará compilar o PHP com o parametro --with-mhash[=DIR] para habilitar esta extensão. DIR é o diretório de instalação do mhash.


Configuração durante execução

Esta extenção não define nenhum parâmetro de configuração no php.ini.


Tipos Resource

Esta extensão não possui nenhum tipo resource.


Constantes Predefinidas

As contantes abaixo são definidas por esta extensão e somente estarão disponíveis quando a extensão foi compilada com o PHP ou carregada dinamicamente durante a execução.

Aqui está a lista de hashes que são atualmente suportadas por mhash. Se uma hash não está listada aqui, mas é listada pelo mhash como suportada, você pode assumir seguramente que esta documentação está desatualizada.

  • MHASH_MD5

  • MHASH_SHA1

  • MHASH_HAVAL256

  • MHASH_HAVAL192

  • MHASH_HAVAL160

  • MHASH_HAVAL128

  • MHASH_RIPEMD160

  • MHASH_GOST

  • MHASH_TIGER

  • MHASH_CRC32

  • MHASH_CRC32B


Exemplos

Exemplo 1. Calcular o MD5 digest e hmac e imprimir como hex

<?php
$input = "what do ya want for nothing?";
$hash = mhash (MHASH_MD5, $input);
print "A hash é ".bin2hex ($hash)."<br />\n";
$hash = mhash (MHASH_MD5, $input, "Jefe");
print "A hmac é ".bin2hex ($hash)."<br />\n";
?>

Este código irá produzir:
A hash é d03cb659cbf9192dcd066272249f8412
A hmac é 750c783e6ab0b503eaa86e310a5db738

Índice
mhash_count -- Ler o mais alto hash id disponível
mhash_get_block_size -- Ler o tamanho do bloco da hash específicada
mhash_get_hash_name -- Ler o nome da hash especificada
mhash_keygen_s2k -- Gerar uma chave
mhash -- Computar a hash

mhash_count

(PHP 3>= 3.0.9, PHP 4 )

mhash_count -- Ler o mais alto hash id disponível

Descrição

int mhash_count ( void)

mhash_count() retorna a mais alta hash id disponível. As hashes são numeradas de 0 até esta hash id.

Exemplo 1. Listando todas as hashes

<?php

$nr = mhash_count();

for ($i = 0; $i <= $nr; $i++) {
    echo sprintf ("O tamanho do bloco de %s é %d\n", 
        mhash_get_hash_name ($i),
        mhash_get_block_size ($i));
}
?>

mhash_get_block_size

(PHP 3>= 3.0.9, PHP 4 )

mhash_get_block_size -- Ler o tamanho do bloco da hash específicada

Descrição

int mhash_get_block_size ( int hash)

mhash_get_block_size() é usada para obter o tamanho de um blobo da hash específicada.

mhash_get_block_size() recebe um argumento, a hash e retorna o tamanho em bytes ou FALSE, se o parametro hash não existe.

mhash_get_hash_name

(PHP 3>= 3.0.9, PHP 4 )

mhash_get_hash_name -- Ler o nome da hash especificada

Descrição

string mhash_get_hash_name ( int hash)

mhash_get_hash_name() é usada para obter o nome da hash especificada.

mhash_get_hash_name() recebe a id da hash como um argumento e retorna o nome da hash ou FALSE, se a hash não existe.

Exemplo 1. Exemplo do mhash_get_hash_name()

<?php
$hash = MHASH_MD5;

print mhash_get_hash_name ($hash);
?>

O exemplo acima irá imprimir:
MD5

mhash_keygen_s2k

(PHP 4 >= 4.0.4)

mhash_keygen_s2k -- Gerar uma chave

Descrição

string mhash_keygen_s2k ( int hash, string password, string salt, int bytes)

mhash_keygen_s2k() gera um chave que tem bytes de comprimento, apartir de uma senha (password) do usuário. Este é o algoritmo Salted S2K como especificado no documento OpenPGP (RFC 2440). Este algoritmo usará o algoritmo hash para criar a chave. O salt deve ser diferente e aleatório o suficiente para que cada chave que você gere seja diferente. Este salt tem que ser sabido quando você checar as suas chaves (keys), logo é uma boa ideia que a chave siga o salt. O salt tem o comprimento fixo de 8 bytes e será completado com zeros se voce fornecer menos bytes. Tenha em mente que as senhas fornecidas pelos usuários não são boas para serem usadas como chaves em algoritmos criptográficos, pois usuários normalmente escolhem chaves que eles podem escrever no teclado. Estas senhas usam somente 6 a 7 bits por caracter (ou menos). É altamente recomendado usar algum tipo de transformação (como esta função) na chave dada pelo usuário.

mhash

(PHP 3>= 3.0.9, PHP 4 )

mhash -- Computar a hash

Descrição

string mhash ( int hash, string data, string [ key ])

mhash() applica a função hash especificada por hash para o parametro data e retorna a hash resultante (também chamada de digest). Se a key for especificada a função irá retornar o HMAC resultante. HMAC é o hashing com chave (keyed) para autenticações de mensagens, ou simplesmente um digest de mensagens que depende na chave (key) específicada. Nem todos os algorítmos suportados em mhash podem ser usados em modo HMAC. Em caso de erro retorna FALSE.

LVII. Mimetype Functions

Introdução

The functions in this module try to guess the content type and encoding of a file by looking for certain magic byte sequences at specific positions within the file. While this is not a bullet proof approach the heuristics used do a very good job.

This extension is derivated from Apache mod_mime_magic, which is itself based on the file command maintaind by Ian F. Darwin. See the source code for further historic and copyright information.


Requisitos

Nenhuma biblioteca externa é necessária para compilar esta extensão.


Instalação

You must compile PHP with the configure switch --enable-mime-magic to get support for mime-type functions. The 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 /usr/share/misc directory.


Configuração durante execução

O comportamento dessas funções podem ser modificado pelas configurações do php.ini.

Tabela 1. Mimetype configuration options

Name Default Changeable
mime_magic.magicfile "/usr/share/misc/magic.mime" PHP_INI_SYSTEM
For further details and definition of the PHP_INI_* constants see ini_set().


Tipos Resource

Esta extensão não possui nenhum tipo resource.


Constantes Predefinidas

Esta extensão não possui nenhuma constante.

Índice
mime_content_type -- Detect MIME Content-type for a file

mime_content_type

(PHP 4 >= 4.3.0)

mime_content_type -- Detect MIME Content-type for a file

Description

string mime_content_type ( string filename)

Returns the MIME content type for a file as determined by using information from the magic.mime file. Content types are returned in MIME format, like text/plain or application/octet-stream.

LVIII. Funções Microsoft SQL Server

Introdução

Estas funções permitem a você acessar um banco de dados do MS SQL Server.

Nota: A extensão MSSQL esta disponível somente em sistemas Win32. Você pode usar a extensão Sybase para conectar com banco de dados MSSQL de outras plataformas.


Requisitos

A extensão requer que as ferramentas de cliente do MS SQL sejam instaladas no sistema onde o PHP esta instalado. As ferramentas de cliene podem ser instaladas apartir do CD do MS SQL Server ou copiando ntwdblib.dll de \winnt\system32 da maquina do servidor \winnt\system32 na maquina do PHP. Copiar ntwdblib.dll irá somente prover acesso. Configuração do cliente irá requerer a instalação de todas as ferramentas.


Instalação

A extensão MSSQL é ativada se adicionando extension=php_mssql.dll no php.ini.


Configuração durante execução

O comportamento dessas funções podem ser modificado pelas configurações do php.ini.

Tabela 1. Opções de configuração do MS SQL Server

Nome Padrão Modificável
mssql.allow_persistent "1" PHP_INI_SYSTEM
mssql.max_persistent "-1" PHP_INI_SYSTEM
mssql.max_links "-1" PHP_INI_SYSTEM
mssql.min_error_severity "10" PHP_INI_ALL
mssql.min_message_severity "10" PHP_INI_ALL
mssql.compatability_mode "0" PHP_INI_ALL
mssql.connect_timeout "5" PHP_INI_ALL
mssql.timeout "60" PHP_INI_ALL
mssql.textsize "-1" PHP_INI_ALL
mssql.textlimit "-1" PHP_INI_ALL
mssql.batchsize "0" PHP_INI_ALL
mssql.datetimeconvert "1" PHP_INI_ALL
mssql.secure_connection "0" PHP_INI_SYSTEM
mssql.max_procs "25" PHP_INI_ALL
Para maiores detalhes e definição das constantes PHP_INI_* veja ini_set().


Tipos Resource


Constantes Predefinidas

As contantes abaixo são definidas por esta extensão e somente estarão disponíveis quando a extensão foi compilada com o PHP ou carregada dinamicamente durante a execução.

MSSQL_ASSOC (integer)

MSSQL_NUM (integer)

MSSQL_BOTH (integer)

SQLTEXT (integer)

SQLVARCHAR (integer)

SQLCHAR (integer)

SQLINT1 (integer)

SQLINT2 (integer)

SQLINT4 (integer)

SQLBIT (integer)

SQLFLT8 (integer)

Índice
mssql_bind --  Adiciona um parâmetro a um stored procedure ou a um remote stored procedure
mssql_close -- Fecha a conexão com o servidor MS SQL
mssql_connect -- Abre uma conexão com o servidor MS SQL
mssql_data_seek -- move o ponteiro interno da linha
mssql_execute --  Executa uma stored procedure num banco de dados de um servidor MS SQL
mssql_fetch_array -- Retorna uma linha como uma array
mssql_fetch_assoc --  Retorna uma matriz associativa da linha atual do conjunto de resultados especificado por result_id
mssql_fetch_batch --  Retorna o próximo lote de registros
mssql_fetch_field -- Retorna informação sobre o campo
mssql_fetch_object -- Devolve a linha como um objeto
mssql_fetch_row -- Retorna uma matriz enumerada
mssql_field_length -- Retorna o tamanho de um campo
mssql_field_name -- Retorna o nome de um campo
mssql_field_seek -- Estabelece o índice do campo
mssql_field_type -- Retorna o tipo de um campo
mssql_free_result -- Limpa o resultado da memória
mssql_free_statement -- Free statement memory
mssql_get_last_message --  Retorna a ultima mensagem do servidor (sobre min_message_severity?)
mssql_guid_string --  Converte um 16 byte binary GUID para uma string
mssql_init --  Inicializa um stored procedure ou um remote stored procedure
mssql_min_error_severity -- Estabelece a menor severidade a erros
mssql_min_message_severity -- Estabelece a menor severidade a mensagens
mssql_next_result -- Move o ponteiro interno do resultado para o próximo resultado
mssql_num_fields -- Retorna o número de campos em um resultado
mssql_num_rows -- Retorna o número de linhas em um resultado
mssql_pconnect -- Abre uma conexão persistente com MS SQL
mssql_query -- Envia uma query ao MS SQL
mssql_result -- Retorna dados do resultado
mssql_rows_affected --  Retorna o número de registros afetados pela query
mssql_select_db -- Seleciona um banco de dados do MS SQL

mssql_bind

(PHP 4 >= 4.1.0)

mssql_bind --  Adiciona um parâmetro a um stored procedure ou a um remote stored procedure

Descrição

int mssql_bind ( int stmt, string param_name, mixed var, int type [, int is_output [, int is_null [, int maxlen]]])

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mssql_close

(PHP 3, PHP 4 )

mssql_close -- Fecha a conexão com o servidor MS SQL

Descrição

int mssql_close ( [int link_identifier])

Retorna: TRUE se funcionar, FALSE se ocorrer erro.

mssql_close() fecha a conexão com o MS SQL Server que esta associado ao identificador de conexão(link_identifier) indicado. Se o identificador de conexão não é especificado, a ultima conexão aberta é usada.

Note que isto não é usualmente necessário, já que conexões não persistentes são automaticamente fechadas ao final da execução do script.

mssql_close() não irá fechar conexões persistentes geradas por mssql_pconnect().

Veja também: mssql_connect(), mssql_pconnect().

mssql_connect

(PHP 3, PHP 4 )

mssql_connect -- Abre uma conexão com o servidor MS SQL

Descrição

int mssql_connect ( [string nomedoservidor [, string username [, string password]]])

Retorna: um identificador de link positivo com o servidor MS SQL se funcionar, ou FALSE se houver erro.

mssql_connect() estabelece uma conexão com um servidor MS SQL . O argumento nomedoservidor tem que ser um nome de servidor que esteja definido no arquivo 'interfaces'.

No caso de uma segunda chamada for feita para mssql_connect() com os mesmos argumentos, não será criada uma nova conexão, mas ao invés, o identificador de conexão da conexão que já esta aberta será retornado.

A conexão com o servidor será fechada assim que a execução do script terminar, a menos que seja fechada antes explicitamente por mssql_close().

Veja também mssql_pconnect(), mssql_close().

mssql_data_seek

(PHP 3, PHP 4 )

mssql_data_seek -- move o ponteiro interno da linha

Descrição

int mssql_data_seek ( int result_identifier, int row_number)

Retorna: TRUE se funcionar, FALSE se houver erro.

mssql_data_seek() move o ponteiro interno da linha do resultado indicado por result_identifier para o numero da linha especificado. A próxima chamada a mssql_fetch_row() irá retornar esta linha.

Veja também: mssql_data_seek().

mssql_execute

(PHP 4 >= 4.1.0)

mssql_execute --  Executa uma stored procedure num banco de dados de um servidor MS SQL

Descrição

int mssql_execute ( int stmt)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mssql_fetch_array

(PHP 3, PHP 4 )

mssql_fetch_array -- Retorna uma linha como uma array

Descrição

array mssql_fetch_array ( int result)

Retorna: uma array que corresponde a linha, ou FALSE se não houver mais linhas.

mssql_fetch_array() é uma versão estendida de mssql_fetch_row(). Alem de guardar os dados em uma matriz com índices numéricos, também guarda os dados em uma matriz associativa, usando os nomes dos campos como chave.

Uma coisa importante para notar é que usar mssql_fetch_array() NÃO é significativamente mais lento do que usar mssql_fetch_row(), enquanto que é mais fácil de usar.

Para maiores detalhes veja também mssql_fetch_row().

mssql_fetch_assoc

(PHP 4 >= 4.2.0)

mssql_fetch_assoc --  Retorna uma matriz associativa da linha atual do conjunto de resultados especificado por result_id

Descrição

array mssql_fetch_assoc ( int result_id [, int result_type])

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mssql_fetch_batch

(PHP 4 >= 4.0.4)

mssql_fetch_batch --  Retorna o próximo lote de registros

Descrição

int mssql_fetch_batch ( string result_index)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mssql_fetch_field

(PHP 3, PHP 4 )

mssql_fetch_field -- Retorna informação sobre o campo

Descrição

object mssql_fetch_field ( int result [, int field_offset])

Retorna um objeto contendo informação do campo.

mssql_fetch_field() pode ser usada para obter informações sobre os campos do resultado de uma query. Se o índice do campo não for especificado, o próximo campo que ainda não foi recuperado por mssql_fetch_field() é retornado.

As propriedades do objeto são:

  • name - nome da coluna. Se a coluna é resultado de alguma função, esta propriedade é estabelecida como computed#N, aonde #N é um número de série.

  • column_source - a tabela de onde a coluna veio

  • max_length - o limite de tamanho da coluna

  • numeric - 1 se a coluna é numérica

Veja também mssql_field_seek().

mssql_fetch_object

(PHP 3)

mssql_fetch_object -- Devolve a linha como um objeto

Descrição

int mssql_fetch_object ( int result)

Retorna: Um objeto com propriedades que correspondem a linha, ou FALSE se não houver mais linhas.

mssql_fetch_object() é similar a mssql_fetch_array(), com uma diferença - um objeto é retornado, ao invés de uma matriz. Indiretamente, isto indica que você só pode acessar os dados pelo nome dos campos, e não por seus índices (números são nomes de propriedades ilegais).

Em velocidade, esta função é idêntica a mssql_fetch_array(), e quase tão rápida quanto mssql_fetch_row() (a diferença é insignificante).

Veja também: mssql_fetch-array() e mssql_fetch-row().

mssql_fetch_row

(PHP 3, PHP 4 )

mssql_fetch_row -- Retorna uma matriz enumerada

Descrição

array mssql_fetch_row ( int result)

Retorna: uma matriz que corresponde a linha, ou FALSE se não houver mais linhas.

mssql_fetch_row() retorna uma linha do resultado identificado por result. A linha é retornada como uma matriz. Cada coluna do resultado é guardada com um índice numérico, começando no 0.

A próxima chamada para mssql_fetch_rows() deve retornar a próxima linha do conjunto de resultados, ou FALSE se não houver mais linhas.

Veja também: mssql_fetch_array(), mssql_fetch_object(), mssql_data_seek(), mssql_fetch_lengths(), e mssql_result().

mssql_field_length

(PHP 3>= 3.0.3, PHP 4 )

mssql_field_length -- Retorna o tamanho de um campo

Descrição

int mssql_field_length ( int result [, int offset])

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mssql_field_name

(PHP 3>= 3.0.3, PHP 4 )

mssql_field_name -- Retorna o nome de um campo

Descrição

int mssql_field_name ( int result [, int offset])

mssql_field_seek

(PHP 3, PHP 4 )

mssql_field_seek -- Estabelece o índice do campo

Descrição

int mssql_field_seek ( int result, int field_offset)

Move o ponteiro para o índice do campo especificado. Se a próxima chamada a mssql_fetch_field() não incluir um índice do campo, este campo será retornado.

Veja também: mssql_fetch_field().

mssql_field_type

(PHP 3>= 3.0.3, PHP 4 )

mssql_field_type -- Retorna o tipo de um campo

Descrição

string mssql_field_type ( int result [, int offset])

mssql_free_result

(PHP 3, PHP 4 )

mssql_free_result -- Limpa o resultado da memória

Descrição

int mssql_free_result ( int result)

mssql_free_result() somente precisa ser chamado se você esta preocupado com a quantidade de memória usada enquanto o seu script esta sendo executado. Toda a memória do resultado é liberada automaticamente quando o script acaba. Você deve chamar mssql_free_result() com o identificador do resultado que você quer liberar da memória.

mssql_free_statement

(PHP 5 CVS only)

mssql_free_statement -- Free statement memory

Description

int mssql_free_statement ( int statement)

mssql_free_statement() only needs to be called if you are worried about using too much memory while your script is running. All statement memory will automatically be freed when the script ends. You may call mssql_free_statement() with the statement identifier as an argument and the associated statement memory will be freed.

See also mssql_bind(), mssql_execute() and mssql_init()

mssql_get_last_message

(PHP 3, PHP 4 )

mssql_get_last_message --  Retorna a ultima mensagem do servidor (sobre min_message_severity?)

Descrição

string mssql_get_last_message ( void)

mssql_guid_string

(PHP 4 >= 4.1.0)

mssql_guid_string --  Converte um 16 byte binary GUID para uma string

Descrição

string mssql_guid_string ( string binary [, int short_format])

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mssql_init

(PHP 4 >= 4.1.0)

mssql_init --  Inicializa um stored procedure ou um remote stored procedure

Descrição

int mssql_init ( string sp_name [, int conn_id])

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mssql_min_error_severity

(PHP 3, PHP 4 )

mssql_min_error_severity -- Estabelece a menor severidade a erros

Descrição

void mssql_min_error_severity ( int severity)

mssql_min_message_severity

(PHP 3, PHP 4 )

mssql_min_message_severity -- Estabelece a menor severidade a mensagens

Descrição

void mssql_min_message_severity ( int severity)

mssql_next_result

(PHP 4 >= 4.0.5)

mssql_next_result -- Move o ponteiro interno do resultado para o próximo resultado

Descrição

bool mssql_next_result ( int result_id)

Quando se envia mais de uma sql para o servidor ou executando uma stored procedure com múltiplos resultados, irá causar que o servidor retorne múltiplos conjuntos de resultados. Esta função irá testar se há resultados adicionais do servidor. Se existir um conjunto adicional de resultados, irá liberar o conjunto atual de resultados e preparar para usar o novo conjunto de resultados. A função irá retornar TRUE se um conjunto adicional de resultados estiver disponível ou FALSE em outro caso.

Exemplo 1. Exemplo mssql_next_result()

<?php
    $link = mssql_connect ("localhost", "userid", "secret");
    mssql_select_db("MyDB", $link);
    $SQL = "Select * from table1 select * from table2";
    $rs = mssql_query($SQL, $link);
    do {
        while ($row = mssql_fetch_row($rs)) {
        }
    } while (mssql_next_result($rs));
    mssql_free_result($rs);
    mssql_close ($link);
?>

mssql_num_fields

(PHP 3, PHP 4 )

mssql_num_fields -- Retorna o número de campos em um resultado

Descrição

int mssql_num_fields ( int result)

mssql_num_fields() retorna o número de campos em um conjunto de resultados.

Veja também: mssql_db_query(), mssql_query(), mssql_fetch_field(), e mssql_num_rows().

mssql_num_rows

(PHP 3, PHP 4 )

mssql_num_rows -- Retorna o número de linhas em um resultado

Descrição

int mssql_num_rows ( string result)

mssql_num_rows() retorna o número de linhas em um conjunto de resultados.

Veja também: mssql_db_query(), mssql_query(), e mssql_fetch_row().

mssql_pconnect

(PHP 3, PHP 4 )

mssql_pconnect -- Abre uma conexão persistente com MS SQL

Descrição

int mssql_pconnect ( [string servername [, string username [, string password]]])

Retorna: um identificador de link persistente com MS SQL se funcionar, ou FALSE se houver erro.

mssql_pconnect() funciona muito parecido com mssql_connect() com duas diferenças maiores.

Primeiro, ao conectar, a função irá primeiro tentar achar uma conexão (persistente) que já esteja aberta com o mesmo host, username e password. Se uma é encontrada, um identificador para ela será retornada ao invés de abrir uma nova conexão.

Segundo, a conexão ao servidor SQL não será fechada quando a execução do script terminar. Ao invés, a conexão permanecerá aberta para uso futuro (mssql_close() não irá fechar conexões criadas com mssql_pconnect()).

Este tipo de conexão é chamado 'Persistente'.

mssql_query

(PHP 3, PHP 4 )

mssql_query -- Envia uma query ao MS SQL

Descrição

int mssql_query ( string query [, int link_identifier])

Retorna: um identificador de resultado do MS SQL se funcionar, ou FALSE se houver um erro.

mssql_query() envia uma query para o banco de dados atual no servidor que esta associado a conexão especificada em link_identifier. Se link_identifier não for especificado, a ultima conexão aberta é usada. Se nenhuma conexão estiver aberta, a função tenta criar um como se mssql_connect() fosse chamada, e irá usa-la.

Veja também: mssql_db_query(), mssql_select_db(),e mssql_connect().

mssql_result

(PHP 3, PHP 4 )

mssql_result -- Retorna dados do resultado

Descrição

int mssql_result ( int result, int i, mixed field)

mssql_result() retorna o conteúdo de uma célula de um conjunto de resultados do MS SQL. O argumento field pode ser o índice do campo, o nome do campo ou a tabela do campo ponto o nome do campo (tabela.campo). Se um nome da coluna tem apelido ('select foo as bar from...'), use o apelido ao invés do nome da coluna.

Quando estiver trabalhando com grandes conjuntos de resultados, você deve considerar o uso de funções que retornam toda a linha (especificadas abaixo). Como estas funções retornam múltiplas células em uma chamada de função, elas são MUITO mais rápidas do que mssql_result(). Também note que especificar um índice numérico para o argumento field é muito mais rápido do que especificar um nome de campo ou tabela.campo.

Alternativas mais rápidas recomendadas: mssql_fetch_row(), mssql_fetch_array(), e mssql_fetch_object().

mssql_rows_affected

(PHP 4 >= 4.0.4)

mssql_rows_affected --  Retorna o número de registros afetados pela query

Descrição

int mssql_rows_affected ( int conn_id)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

mssql_select_db

(PHP 3, PHP 4 )

mssql_select_db -- Seleciona um banco de dados do MS SQL

Descrição

int mssql_select_db ( string database_name [, int link_identifier])

Retorna: TRUE se funcionar, FALSE se houver erro

mssql_select_db() estabelece o banco de dados ativo para a conexão especificada por link_identifier. Se nenhum identificador de conexão for especificado, a ultima conexão aberta é usada. Se nenhuma conexão estiver aberta a função tentará estabelecer uma como se mssql_connect() fosse chamada, e irá usa-la.

Todas as próximas chamadas a mssql_query() serão feitas no banco de dados ativo.

Veja também: mssql_connect(), mssql_pconnect(), e mssql_query()

LIX. Ming functions for Flash

Atenção

Este módulo é EXPERIMENTAL. Isso quer dizer que o comportamento neste módulo --- incluindo suas funções e seus nomes, e TUDO mais que está documentado sobre esse módulo --- poderá mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use este módulo por sua própria conta e risco.


Introdução

First of all: Ming is not an acronym. Ming is an open-source (LGPL) library which allows you to create SWF ("Flash") format movies. Ming supports almost all of Flash 4's features, including: shapes, gradients, bitmaps (pngs and jpegs), morphs ("shape tweens"), text, buttons, actions, sprites ("movie clips"), streaming mp3, and color transforms --the only thing that's missing is sound events.

Note that all values specifying length, distance, size, etc. are in "twips", twenty units per pixel. That's pretty much arbitrary, though, since the player scales the movie to whatever pixel size is specified in the embed/object tag, or the entire frame if not embedded.

Ming offers a number of advantages over the existing PHP/libswf module. You can use Ming anywhere you can compile the code, whereas libswf is closed-source and only available for a few platforms, Windows not one of them. Ming provides some insulation from the mundane details of the SWF file format, wrapping the movie elements in PHP objects. Also, Ming is still being maintained; if there's a feature that you want to see, just let us know ming@opaque.net.

Ming was added in PHP 4.0.5.


Requisitos

To use Ming with PHP, you first need to build and install the Ming library. Source code and installation instructions are available at the Ming home page: http://ming.sourceforge.net/ along with examples, a small tutorial, and the latest news.

Download the ming archive. Unpack the archive. Go in the Ming directory. make. make install.

This will build libming.so and install it into /usr/lib/, and copy ming.h into /usr/include/. Edit the PREFIX= line in the Makefile to change the installation directory.


Instalação

Exemplo 1. built into php (unix)



    mkdir <phpdir>/ext/ming
    cp php_ext/* <phpdir>/ext/ming
    cd <phpdir>
    ./buildconf 
    ./configure --with-ming <other config options>

    

Build and install php as usual, restart web server if necessary.

Now either just add extension=php_ming.so to your php.ini file, or put dl('php_ming.so'); at the head of all of your Ming scripts.


Configuração durante execução

Esta extenção não define nenhum parâmetro de configuração no php.ini.


Tipos Resource


Constantes Predefinidas

As contantes abaixo são definidas por esta extensão e somente estarão disponíveis quando a extensão foi compilada com o PHP ou carregada dinamicamente durante a execução.

SWFBUTTON_HIT (integer)

SWFBUTTON_DOWN (integer)

SWFBUTTON_OVER (integer)

SWFBUTTON_UP (integer)

SWFBUTTON_MOUSEUPOUTSIDE (integer)

SWFBUTTON_DRAGOVER (integer)

SWFBUTTON_DRAGOUT (integer)

SWFBUTTON_MOUSEUP (integer)

SWFBUTTON_MOUSEDOWN (integer)

SWFBUTTON_MOUSEOUT (integer)

SWFBUTTON_MOUSEOVER (integer)

SWFFILL_RADIAL_GRADIENT (integer)

SWFFILL_LINEAR_GRADIENT (integer)

SWFFILL_TILED_BITMAP (integer)

SWFFILL_CLIPPED_BITMAP (integer)

SWFTEXTFIELD_HASLENGTH (integer)

SWFTEXTFIELD_NOEDIT (integer)

SWFTEXTFIELD_PASSWORD (integer)

SWFTEXTFIELD_MULTILINE (integer)

SWFTEXTFIELD_WORDWRAP (integer)

SWFTEXTFIELD_DRAWBOX (integer)

SWFTEXTFIELD_NOSELECT (integer)

SWFTEXTFIELD_HTML (integer)

SWFTEXTFIELD_ALIGN_LEFT (integer)

SWFTEXTFIELD_ALIGN_RIGHT (integer)

SWFTEXTFIELD_ALIGN_CENTER (integer)

SWFTEXTFIELD_ALIGN_JUSTIFY (integer)

SWFACTION_ONLOAD (integer)

SWFACTION_ENTERFRAME (integer)

SWFACTION_UNLOAD (integer)

SWFACTION_MOUSEMOVE (integer)

SWFACTION_MOUSEDOWN (integer)

SWFACTION_MOUSEUP (integer)

SWFACTION_KEYDOWN (integer)

SWFACTION_KEYUP (integer)

SWFACTION_DATA (integer)


Classes Predefinidas

As classes abaixo são definidas por esta extensão e somente estarão disponíveis quando a extensão for compilada junto com o PHP, ou carregada dinamicamente na execução.

Ming introduces 13 new objects in PHP, all with matching methods and attributes. To use them, you need to know about objects.

swfshape

swffill

swfgradient

swfbitmap

swftext

swftextfield

swffont

swfdisplayitem

swfmovie

swfbutton

swfaction

swfmorph

swfsprite

Índice
ming_setcubicthreshold --  Set cubic threshold (?)
ming_setscale --  Set scale (?)
ming_useswfversion --  Use SWF version (?)
SWFAction -- Creates a new Action.
SWFBitmap->getHeight -- Returns the bitmap's height.
SWFBitmap->getWidth -- Returns the bitmap's width.
SWFBitmap -- Loads Bitmap object
swfbutton_keypress --  Returns the action flag for keyPress(char)
SWFbutton->addAction -- Adds an action
SWFbutton->addShape -- Adds a shape to a button
SWFbutton->setAction -- Sets the action
SWFbutton->setdown -- Alias for addShape(shape, SWFBUTTON_DOWN))
SWFbutton->setHit -- Alias for addShape(shape, SWFBUTTON_HIT)
SWFbutton->setOver -- Alias for addShape(shape, SWFBUTTON_OVER)
SWFbutton->setUp -- Alias for addShape(shape, SWFBUTTON_UP)
SWFbutton -- Creates a new Button.
SWFDisplayItem->addColor -- Adds the given color to this item's color transform.
SWFDisplayItem->move -- Moves object in relative coordinates.
SWFDisplayItem->moveTo -- Moves object in global coordinates.
SWFDisplayItem->multColor -- Multiplies the item's color transform.
SWFDisplayItem->remove -- Removes the object from the movie
SWFDisplayItem->Rotate -- Rotates in relative coordinates.
SWFDisplayItem->rotateTo -- Rotates the object in global coordinates.
SWFDisplayItem->scale -- Scales the object in relative coordinates.
SWFDisplayItem->scaleTo -- Scales the object in global coordinates.
SWFDisplayItem->setDepth -- Sets z-order
SWFDisplayItem->setName -- Sets the object's name
SWFDisplayItem->setRatio -- Sets the object's ratio.
SWFDisplayItem->skewX -- Sets the X-skew.
SWFDisplayItem->skewXTo -- Sets the X-skew.
SWFDisplayItem->skewY -- Sets the Y-skew.
SWFDisplayItem->skewYTo -- Sets the Y-skew.
SWFDisplayItem -- Creates a new displayitem object.
SWFFill->moveTo -- Moves fill origin
SWFFill->rotateTo -- Sets fill's rotation
SWFFill->scaleTo -- Sets fill's scale
SWFFill->skewXTo -- Sets fill x-skew
SWFFill->skewYTo -- Sets fill y-skew
SWFFill -- Loads SWFFill object
swffont->getwidth -- Returns the string's width
SWFFont -- Loads a font definition
SWFGradient->addEntry -- Adds an entry to the gradient list.
SWFGradient -- Creates a gradient object
SWFMorph->getshape1 -- Gets a handle to the starting shape
SWFMorph->getshape2 -- Gets a handle to the ending shape
SWFMorph -- Creates a new SWFMorph object.
SWFMovie->add -- Adds any type of data to a movie.
SWFMovie->nextframe -- Moves to the next frame of the animation.
SWFMovie->output -- Dumps your lovingly prepared movie out.
SWFMovie->remove -- Removes the object instance from the display list.
SWFMovie->save -- Saves your movie in a file.
SWFMovie->setbackground -- Sets the background color.
SWFMovie->setdimension -- Sets the movie's width and height.
SWFMovie->setframes -- Sets the total number of frames in the animation.
SWFMovie->setrate -- Sets the animation's frame rate.
SWFMovie->streammp3 -- Streams a MP3 file.
SWFMovie -- Creates a new movie object, representing an SWF version 4 movie.
SWFShape->addFill -- Adds a solid fill to the shape.
SWFShape->drawCurve -- Draws a curve (relative).
SWFShape->drawCurveTo -- Draws a curve.
SWFShape->drawLine -- Draws a line (relative).
SWFShape->drawLineTo -- Draws a line.
SWFShape->movePen -- Moves the shape's pen (relative).
SWFShape->movePenTo -- Moves the shape's pen.
SWFShape->setLeftFill -- Sets left rasterizing color.
SWFShape->setLine -- Sets the shape's line style.
SWFShape->setRightFill -- Sets right rasterizing color.
SWFShape -- Creates a new shape object.
SWFSprite->add -- Adds an object to a sprite
SWFSprite->nextframe -- Moves to the next frame of the animation.
SWFSprite->remove -- Removes an object to a sprite
SWFSprite->setframes -- Sets the total number of frames in the animation.
SWFSprite -- Creates a movie clip (a sprite)
SWFText->addString -- Draws a string
SWFText->getWidth -- Computes string's width
SWFText->moveTo -- Moves the pen
SWFText->setColor -- Sets the current font color
SWFText->setFont -- Sets the current font
SWFText->setHeight -- Sets the current font height
SWFText->setSpacing -- Sets the current font spacing
SWFText -- Creates a new SWFText object.
SWFTextField->addstring -- Concatenates the given string to the text field
SWFTextField->align -- Sets the text field alignment
SWFTextField->setbounds -- Sets the text field width and height
SWFTextField->setcolor -- Sets the color of the text field.
SWFTextField->setFont -- Sets the text field font
SWFTextField->setHeight -- Sets the font height of this text field font.
SWFTextField->setindentation -- Sets the indentation of the first line.
SWFTextField->setLeftMargin -- Sets the left margin width of the text field.
SWFTextField->setLineSpacing -- Sets the line spacing of the text field.
SWFTextField->setMargins -- Sets the margins width of the text field.
SWFTextField->setname -- Sets the variable name
SWFTextField->setrightMargin -- Sets the right margin width of the text field.
SWFTextField -- Creates a text field object

ming_setcubicthreshold

(PHP 4 >= 4.0.5)

ming_setcubicthreshold --  Set cubic threshold (?)

Description

void ming_setcubicthreshold ( int threshold)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ming_setscale

(PHP 4 >= 4.0.5)

ming_setscale --  Set scale (?)

Description

void ming_setscale ( int scale)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ming_useswfversion

(PHP 4 >= 4.2.0)

ming_useswfversion --  Use SWF version (?)

Description

void ming_useswfversion ( int version)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

SWFAction

(PHP 4 >= 4.0.5)

SWFAction -- Creates a new Action.

Description

new swfaction ( string script)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swfaction() creates a new Action, and compiles the given script into an SWFAction object.

The script syntax is based on the C language, but with a lot taken out- the SWF bytecode machine is just too simpleminded to do a lot of things we might like. For instance, we can't implement function calls without a tremendous amount of hackery because the jump bytecode has a hardcoded offset value. No pushing your calling address to the stack and returning- every function would have to know exactly where to return to.

So what's left? The compiler recognises the following tokens:

  • break

  • for

  • continue

  • if

  • else

  • do

  • while

There is no typed data; all values in the SWF action machine are stored as strings. The following functions can be used in expressions:

time()

Returns the number of milliseconds (?) elapsed since the movie started.

random(seed)

Returns a pseudo-random number in the range 0-seed.

length(expr)

Returns the length of the given expression.

int(number)

Returns the given number rounded down to the nearest integer.

concat(expr, expr)

Returns the concatenation of the given expressions.

ord(expr)

Returns the ASCII code for the given character

chr(num)

Returns the character for the given ASCII code

substr(string, location, length)

Returns the substring of length length at location location of the given string string.

Additionally, the following commands may be used:

duplicateClip(clip, name, depth)

Duplicate the named movie clip (aka sprite). The new movie clip has name name and is at depth depth.

removeClip(expr)

Removes the named movie clip.

trace(expr)

Write the given expression to the trace log. Doubtful that the browser plugin does anything with this.

startDrag(target, lock, [left, top, right, bottom])

Start dragging the movie clip target. The lock argument indicates whether to lock the mouse (?)- use 0 (FALSE) or 1 (TRUE). Optional parameters define a bounding area for the dragging.

stopDrag()

Stop dragging my heart around. And this movie clip, too.

callFrame(expr)

Call the named frame as a function.

getURL(url, target, [method])

Load the given URL into the named target. The target argument corresponds to HTML document targets (such as "_top" or "_blank"). The optional method argument can be POST or GET if you want to submit variables back to the server.

loadMovie(url, target)

Load the given URL into the named target. The target argument can be a frame name (I think), or one of the magical values "_level0" (replaces current movie) or "_level1" (loads new movie on top of current movie).

nextFrame()

Go to the next frame.

prevFrame()

Go to the last (or, rather, previous) frame.

play()

Start playing the movie.

stop()

Stop playing the movie.

toggleQuality()

Toggle between high and low quality.

stopSounds()

Stop playing all sounds.

gotoFrame(num)

Go to frame number num. Frame numbers start at 0.

gotoFrame(name)

Go to the frame named name. Which does a lot of good, since I haven't added frame labels yet.

setTarget(expr)

Sets the context for action. Or so they say- I really have no idea what this does.

And there's one weird extra thing. The expression frameLoaded(num) can be used in if statements and while loops to check if the given frame number has been loaded yet. Well, it's supposed to, anyway, but I've never tested it and I seriously doubt it actually works. You can just use /:framesLoaded instead.

Movie clips (all together now- aka sprites) have properties. You can read all of them (or can you?), you can set some of them, and here they are:

  • x

  • y

  • xScale

  • yScale

  • currentFrame - (read-only)

  • totalFrames - (read-only)

  • alpha - transparency level

  • visible - 1=on, 0=off (?)

  • width - (read-only)

  • height - (read-only)

  • rotation

  • target - (read-only) (???)

  • framesLoaded - (read-only)

  • name

  • dropTarget - (read-only) (???)

  • url - (read-only) (???)

  • highQuality - 1=high, 0=low (?)

  • focusRect - (???)

  • soundBufTime - (???)

So, setting a sprite's x position is as simple as /box.x = 100;. Why the slash in front of the box, though? That's how flash keeps track of the sprites in the movie, just like a unix filesystem- here it shows that box is at the top level. If the sprite named box had another sprite named biff inside of it, you'd set its x position with /box/biff.x = 100;. At least, I think so; correct me if I'm wrong here.

This simple example will move the red square across the window.

Exemplo 1. swfaction() example

<?php
 $s = new SWFShape();
  $f = $s->addFill(0xff, 0, 0);
  $s->setRightFill($f);

  $s->movePenTo(-500,-500);
  $s->drawLineTo(500,-500);
  $s->drawLineTo(500,500);
  $s->drawLineTo(-500,500);
  $s->drawLineTo(-500,-500);

  $p = new SWFSprite();
  $i = $p->add($s);
  $i->setDepth(1);
  $p->nextFrame();

  for($n=0; $n<5; ++$n)
  {
    $i->rotate(-15);
    $p->nextFrame();
  }

  $m = new SWFMovie();
  $m->setBackground(0xff, 0xff, 0xff);
  $m->setDimension(6000,4000);

  $i = $m->add($p);
  $i->setDepth(1);
  $i->moveTo(-500,2000);
  $i->setName("box");

  $m->add(new SWFAction("/box.x += 3;"));
  $m->nextFrame();
  $m->add(new SWFAction("gotoFrame(0); play();"));
  $m->nextFrame();

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

This simple example tracks down your mouse on the screen.

Exemplo 2. swfaction() example

<?php

  $m = new SWFMovie();
  $m->setRate(36.0);
  $m->setDimension(1200, 800);
  $m->setBackground(0, 0, 0);

  /* mouse tracking sprite - empty, but follows mouse so we can
     get its x and y coordinates */

  $i = $m->add(new SWFSprite());
  $i->setName('mouse');

  $m->add(new SWFAction("
    startDrag('/mouse', 1); /* '1' means lock sprite to the mouse */
  "));

  /* might as well turn off antialiasing, since these are just squares. */

  $m->add(new SWFAction("
    this.quality = 0;
  "));

  /* morphing box */
  $r = new SWFMorph();
  $s = $r->getShape1();

  /* Note this is backwards from normal shapes.  No idea why. */
  $s->setLeftFill($s->addFill(0xff, 0xff, 0xff));
  $s->movePenTo(-40, -40);
  $s->drawLine(80, 0);
  $s->drawLine(0, 80);
  $s->drawLine(-80, 0);
  $s->drawLine(0, -80);

  $s = $r->getShape2();

  $s->setLeftFill($s->addFill(0x00, 0x00, 0x00));
  $s->movePenTo(-1, -1);
  $s->drawLine(2, 0);
  $s->drawLine(0, 2);
  $s->drawLine(-2, 0);
  $s->drawLine(0, -2);

  /* sprite container for morphing box -
     this is just a timeline w/ the box morphing */

  $box = new SWFSprite();
  $box->add(new SWFAction("
    stop();
  "));
  $i = $box->add($r);

  for($n=0; $n<=20; ++$n)
  {
    $i->setRatio($n/20);
    $box->nextFrame();
  }

  /* this container sprite allows us to use the same action code many times */

  $cell = new SWFSprite();
  $i = $cell->add($box);
  $i->setName('box');

  $cell->add(new SWFAction("

    setTarget('box');

    /* ...x means the x coordinate of the parent, i.e. (..).x */
    dx = (/mouse.x + random(6)-3 - ...x)/5;
    dy = (/mouse.y + random(6)-3 - ...y)/5;
    gotoFrame(int(dx*dx + dy*dy));

  "));

  $cell->nextFrame();
  $cell->add(new SWFAction("

    gotoFrame(0);
    play();

  "));

  $cell->nextFrame();

  /* finally, add a bunch of the cells to the movie */

  for($x=0; $x<12; ++$x)
  {
    for($y=0; $y<8; ++$y)
    {
      $i = $m->add($cell);
      $i->moveTo(100*$x+50, 100*$y+50);
    }
  }

  $m->nextFrame();

  $m->add(new SWFAction("

    gotoFrame(1);
    play();

  "));

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

Same as above, but with nice colored balls...

Exemplo 3. swfaction() example

<?php

  $m = new SWFMovie();
  $m->setDimension(11000, 8000);
  $m->setBackground(0x00, 0x00, 0x00);

  $m->add(new SWFAction("

this.quality = 0;
/frames.visible = 0;
startDrag('/mouse', 1);

  "));

  // mouse tracking sprite
  $t = new SWFSprite();
  $i = $m->add($t);
  $i->setName('mouse');

  $g = new SWFGradient();
  $g->addEntry(0, 0xff, 0xff, 0xff, 0xff);
  $g->addEntry(0.1, 0xff, 0xff, 0xff, 0xff);
  $g->addEntry(0.5, 0xff, 0xff, 0xff, 0x5f);
  $g->addEntry(1.0, 0xff, 0xff, 0xff, 0);

  // gradient shape thing
  $s = new SWFShape();
  $f = $s->addFill($g, SWFFILL_RADIAL_GRADIENT);
  $f->scaleTo(0.03);
  $s->setRightFill($f);
  $s->movePenTo(-600, -600);
  $s->drawLine(1200, 0);
  $s->drawLine(0, 1200);
  $s->drawLine(-1200, 0);
  $s->drawLine(0, -1200);

  // need to make this a sprite so we can multColor it
  $p = new SWFSprite();
  $p->add($s);
  $p->nextFrame();

  // put the shape in here, each frame a different color
  $q = new SWFSprite();
  $q->add(new SWFAction("gotoFrame(random(7)+1); stop();"));
  $i = $q->add($p);

  $i->multColor(1.0, 1.0, 1.0);
  $q->nextFrame();
  $i->multColor(1.0, 0.5, 0.5);
  $q->nextFrame();
  $i->multColor(1.0, 0.75, 0.5);
  $q->nextFrame();
  $i->multColor(1.0, 1.0, 0.5);
  $q->nextFrame();
  $i->multColor(0.5, 1.0, 0.5);
  $q->nextFrame();
  $i->multColor(0.5, 0.5, 1.0);
  $q->nextFrame();
  $i->multColor(1.0, 0.5, 1.0);
  $q->nextFrame();

  // finally, this one contains the action code
  $p = new SWFSprite();
  $i = $p->add($q);
  $i->setName('frames');
  $p->add(new SWFAction("

dx = (/:mousex-/:lastx)/3 + random(10)-5;
dy = (/:mousey-/:lasty)/3;
x = /:mousex;
y = /:mousey;
alpha = 100;

  "));
  $p->nextFrame();

  $p->add(new SWFAction("

this.x = x;
this.y = y;
this.alpha = alpha;
x += dx;
y += dy;
dy += 3;
alpha -= 8;

  "));
  $p->nextFrame();

  $p->add(new SWFAction("prevFrame(); play();"));
  $p->nextFrame();

  $i = $m->add($p);
  $i->setName('frames');
  $m->nextFrame();

  $m->add(new SWFAction("

lastx = mousex;
lasty = mousey;
mousex = /mouse.x;
mousey = /mouse.y;

++num;

if(num == 11)
  num = 1;

removeClip('char' & num);
duplicateClip(/frames, 'char' & num, num);

  "));

  $m->nextFrame();
  $m->add(new SWFAction("prevFrame(); play();"));

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

This simple example will handles keyboard actions. (You'll probably have to click in the window to give it focus. And you'll probably have to leave your mouse in the frame, too. If you know how to give buttons focus programatically, feel free to share, won't you?)

Exemplo 4. swfaction() example

<?php

  /* sprite has one letter per frame */

  $p = new SWFSprite();
  $p->add(new SWFAction("stop();"));

  $chars = "abcdefghijklmnopqrstuvwxyz".
       "ABCDEFGHIJKLMNOPQRSTUVWXYZ".
           "1234567890!@#$%^&/*()_+-=/[]{}|;:,.<>?`~";

  $f = new SWFFont("_sans");

  for($n=0; $nremove($i);
    $t = new SWFTextField();
    $t->setFont($f);
    $t->setHeight(240);
    $t->setBounds(600,240);
    $t->align(SWFTEXTFIELD_ALIGN_CENTER);
    $t->addString($c);
    $i = $p->add($t);
    $p->labelFrame($c);
    $p->nextFrame();
  }

  /* hit region for button - the entire frame */

  $s = new SWFShape();
  $s->setFillStyle0($s->addSolidFill(0, 0, 0, 0));
  $s->drawLine(600, 0);
  $s->drawLine(0, 400);
  $s->drawLine(-600, 0);
  $s->drawLine(0, -400);

  /* button checks for pressed key, sends sprite to the right frame */

  $b = new SWFButton();
  $b->addShape($s, SWFBUTTON_HIT);

  for($n=0; $naddAction(new SWFAction("

setTarget('/char');
gotoFrame('$c');

    "), SWFBUTTON_KEYPRESS($c));
  }

  $m = new SWFMovie();
  $m->setDimension(600,400);
  $i = $m->add($p);
  $i->setName('char');
  $i->moveTo(0,80);

  $m->add($b);

  header('Content-type: application/x-shockwave-flash');
  $m->output();

?>

SWFBitmap->getHeight

(no version information, might be only in CVS)

SWFBitmap->getHeight -- Returns the bitmap's height.

Description

int swfbitmap->getheight ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swfbitmap->getheight() returns the bitmap's height in pixels.

See also swfbitmap->getwidth().

SWFBitmap->getWidth

(no version information, might be only in CVS)

SWFBitmap->getWidth -- Returns the bitmap's width.

Description

int swfbitmap->getwidth ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swfbitmap->getwidth() returns the bitmap's width in pixels.

See also swfbitmap->getheight().

SWFBitmap

(PHP 4 >= 4.0.5)

SWFBitmap -- Loads Bitmap object

Description

new swfbitmap ( string filename [, int alphafilename])

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swfbitmap() creates a new SWFBitmap object from the Jpeg or DBL file named filename. alphafilename indicates a MSK file to be used as an alpha mask for a Jpeg image.

Nota: We can only deal with baseline (frame 0) jpegs, no baseline optimized or progressive scan jpegs!

SWFBitmap has the following methods : swfbitmap->getwidth() and swfbitmap->getheight().

You can't import png images directly, though- have to use the png2dbl utility to make a dbl ("define bits lossless") file from the png. The reason for this is that I don't want a dependency on the png library in ming- autoconf should solve this, but that's not set up yet.

Exemplo 1. Import PNG files

<?php
  $s = new SWFShape();
  $f = $s->addFill(new SWFBitmap("png.dbl"));
  $s->setRightFill($f);

  $s->drawLine(32, 0);
  $s->drawLine(0, 32);
  $s->drawLine(-32, 0);
  $s->drawLine(0, -32);

  $m = new SWFMovie();
  $m->setDimension(32, 32);
  $m->add($s);

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

And you can put an alpha mask on a jpeg fill.

Exemplo 2. swfbitmap() example

<?php

  $s = new SWFShape();

  // .msk file generated with "gif2mask" utility
  $f = $s->addFill(new SWFBitmap("alphafill.jpg", "alphafill.msk"));
  $s->setRightFill($f);

  $s->drawLine(640, 0);
  $s->drawLine(0, 480);
  $s->drawLine(-640, 0);
  $s->drawLine(0, -480);

  $c = new SWFShape();
  $c->setRightFill($c->addFill(0x99, 0x99, 0x99));
  $c->drawLine(40, 0);
  $c->drawLine(0, 40);
  $c->drawLine(-40, 0);
  $c->drawLine(0, -40);

  $m = new SWFMovie();
  $m->setDimension(640, 480);
  $m->setBackground(0xcc, 0xcc, 0xcc);

  // draw checkerboard background
  for($y=0; $y<480; $y+=40)
  {
    for($x=0; $x<640; $x+=80)
    {
      $i = $m->add($c);
      $i->moveTo($x, $y);
    }

    $y+=40;

    for($x=40; $x<640; $x+=80)
    {
      $i = $m->add($c);
      $i->moveTo($x, $y);
    }
  }

  $m->add($s);

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

swfbutton_keypress

(PHP 4 >= 4.0.5)

swfbutton_keypress --  Returns the action flag for keyPress(char)

Description

int swfbutton_keypress ( string str)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

SWFbutton->addAction

(no version information, might be only in CVS)

SWFbutton->addAction -- Adds an action

Description

void swfbutton->addaction ( ressource action, int flags)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swfbutton->addaction() adds the action action to this button for the given conditions. The following flags are valid: SWFBUTTON_MOUSEOVER, SWFBUTTON_MOUSEOUT, SWFBUTTON_MOUSEUP, SWFBUTTON_MOUSEUPOUTSIDE, SWFBUTTON_MOUSEDOWN, SWFBUTTON_DRAGOUT and SWFBUTTON_DRAGOVER.

See also swfbutton->addshape() and SWFAction().

SWFbutton->addShape

(no version information, might be only in CVS)

SWFbutton->addShape -- Adds a shape to a button

Description

void swfbutton->addshape ( ressource shape, int flags)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swfbutton->addshape() adds the shape shape to this button. The following flags' values are valid: SWFBUTTON_UP, SWFBUTTON_OVER, SWFBUTTON_DOWN or SWFBUTTON_HIT. SWFBUTTON_HIT isn't ever displayed, it defines the hit region for the button. That is, everywhere the hit shape would be drawn is considered a "touchable" part of the button.

SWFbutton->setAction

(no version information, might be only in CVS)

SWFbutton->setAction -- Sets the action

Description

void swfbutton->setaction ( ressource action)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swfbutton->setaction() sets the action to be performed when the button is clicked. Alias for addAction(shape, SWFBUTTON_MOUSEUP). action is a swfaction().

See also swfbutton->addshape() and SWFAction().

SWFbutton->setdown

(no version information, might be only in CVS)

SWFbutton->setdown -- Alias for addShape(shape, SWFBUTTON_DOWN))

Description

void swfbutton->setdown ( ressource shape)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swfbutton->setdown() alias for addShape(shape, SWFBUTTON_DOWN).

See also swfbutton->addshape() and SWFAction().

SWFbutton->setHit

(no version information, might be only in CVS)

SWFbutton->setHit -- Alias for addShape(shape, SWFBUTTON_HIT)

Description

void swfbutton->sethit ( ressource shape)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swfbutton->sethit() alias for addShape(shape, SWFBUTTON_HIT).

See also swfbutton->addshape() and SWFAction().

SWFbutton->setOver

(no version information, might be only in CVS)

SWFbutton->setOver -- Alias for addShape(shape, SWFBUTTON_OVER)

Description

void swfbutton->setover ( ressource shape)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swfbutton->setover() alias for addShape(shape, SWFBUTTON_OVER).

See also swfbutton->addshape() and SWFAction().

SWFbutton->setUp

(no version information, might be only in CVS)

SWFbutton->setUp -- Alias for addShape(shape, SWFBUTTON_UP)

Description

void swfbutton->setup ( ressource shape)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swfbutton->setup() alias for addShape(shape, SWFBUTTON_UP).

See also swfbutton->addshape() and SWFAction().

SWFbutton

(PHP 4 >= 4.0.5)

SWFbutton -- Creates a new Button.

Description

new swfbutton ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swfbutton() creates a new Button. Roll over it, click it, see it call action code. Swank.

SWFButton has the following methods : swfbutton->addshape(), swfbutton->setup(), swfbutton->setover() swfbutton->setdown(), swfbutton->sethit() swfbutton->setaction() and swfbutton->addaction().

This simple example will show your usual interactions with buttons : rollover, rollon, mouseup, mousedown, noaction.

Exemplo 1. swfbutton() example

<?php

  $f = new SWFFont("_serif");

  $p = new SWFSprite();

  function label($string)
  {
    global $f;

    $t = new SWFTextField();
    $t->setFont($f);
    $t->addString($string);
    $t->setHeight(200);
    $t->setBounds(3200,200);
    return $t;
  }
  function addLabel($string)
  {
    global $p;

    $i = $p->add(label($string));
    $p->nextFrame();
    $p->remove($i);
  }

  $p->add(new SWFAction("stop();"));
  addLabel("NO ACTION");
  addLabel("SWFBUTTON_MOUSEUP");
  addLabel("SWFBUTTON_MOUSEDOWN");
  addLabel("SWFBUTTON_MOUSEOVER");
  addLabel("SWFBUTTON_MOUSEOUT");
  addLabel("SWFBUTTON_MOUSEUPOUTSIDE");
  addLabel("SWFBUTTON_DRAGOVER");
  addLabel("SWFBUTTON_DRAGOUT");

  function rect($r, $g, $b)
  {
    $s = new SWFShape();
    $s->setRightFill($s->addFill($r, $g, $b));
    $s->drawLine(600,0);
    $s->drawLine(0,600);
    $s->drawLine(-600,0);
    $s->drawLine(0,-600);

    return $s;
  }

  $b = new SWFButton();
  $b->addShape(rect(0xff, 0, 0), SWFBUTTON_UP | SWFBUTTON_HIT);
  $b->addShape(rect(0, 0xff, 0), SWFBUTTON_OVER);
  $b->addShape(rect(0, 0, 0xff), SWFBUTTON_DOWN);

  $b->addAction(new SWFAction("setTarget('/label'); gotoFrame(1);"),
            SWFBUTTON_MOUSEUP);

  $b->addAction(new SWFAction("setTarget('/label'); gotoFrame(2);"),
        SWFBUTTON_MOUSEDOWN);

  $b->addAction(new SWFAction("setTarget('/label'); gotoFrame(3);"),
        SWFBUTTON_MOUSEOVER);

  $b->addAction(new SWFAction("setTarget('/label'); gotoFrame(4);"),
        SWFBUTTON_MOUSEOUT);

  $b->addAction(new SWFAction("setTarget('/label'); gotoFrame(5);"),
        SWFBUTTON_MOUSEUPOUTSIDE);

  $b->addAction(new SWFAction("setTarget('/label'); gotoFrame(6);"),
        SWFBUTTON_DRAGOVER);

  $b->addAction(new SWFAction("setTarget('/label'); gotoFrame(7);"),
        SWFBUTTON_DRAGOUT);

  $m = new SWFMovie();
  $m->setDimension(4000,3000);

  $i = $m->add($p);
  $i->setName("label");
  $i->moveTo(400,1900);

  $i = $m->add($b);
  $i->moveTo(400,900);

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

This simple example will enables you to drag draw a big red button on the windows. No drag-and-drop, just moving around.

Exemplo 2. swfbutton->addaction() example

<?php

  $s = new SWFShape();
  $s->setRightFill($s->addFill(0xff, 0, 0));
  $s->drawLine(1000,0);
  $s->drawLine(0,1000);
  $s->drawLine(-1000,0);
  $s->drawLine(0,-1000);

  $b = new SWFButton();
  $b->addShape($s, SWFBUTTON_HIT | SWFBUTTON_UP | SWFBUTTON_DOWN | SWFBUTTON_OVER);

  $b->addAction(new SWFAction("startDrag('/test', 0);"), // '0' means don't lock to mouse
        SWFBUTTON_MOUSEDOWN);

  $b->addAction(new SWFAction("stopDrag();"),
        SWFBUTTON_MOUSEUP | SWFBUTTON_MOUSEUPOUTSIDE);

  $p = new SWFSprite();
  $p->add($b);
  $p->nextFrame();

  $m = new SWFMovie();
  $i = $m->add($p);
  $i->setName('test');
  $i->moveTo(1000,1000);

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

SWFDisplayItem->addColor

(no version information, might be only in CVS)

SWFDisplayItem->addColor -- Adds the given color to this item's color transform.

Description

void swfdisplayitem->addcolor ( [int red [, int green [, int blue [, int a]]]])

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swfdisplayitem->addcolor() adds the color to this item's color transform. The color is given in its RGB form.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().

SWFDisplayItem->move

(no version information, might be only in CVS)

SWFDisplayItem->move -- Moves object in relative coordinates.

Description

void swfdisplayitem->move ( int dx, int dy)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swfdisplayitem->move() moves the current object by (dx,dy) from its current position.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().

See also swfdisplayitem->moveto().

SWFDisplayItem->moveTo

(no version information, might be only in CVS)

SWFDisplayItem->moveTo -- Moves object in global coordinates.

Description

void swfdisplayitem->moveto ( int x, int y)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swfdisplayitem->moveto() moves the current object to (x,y) in global coordinates.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().

See also swfdisplayitem->move().

SWFDisplayItem->multColor

(no version information, might be only in CVS)

SWFDisplayItem->multColor -- Multiplies the item's color transform.

Description

void swfdisplayitem->multcolor ( [int red [, int green [, int blue [, int a]]]])

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swfdisplayitem->multcolor() multiplies the item's color transform by the given values.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().

This simple example will modify your picture's atmospher to Halloween (use a landscape or bright picture).

Exemplo 1. swfdisplayitem->multcolor() example

<?php

  $b = new SWFBitmap("backyard.jpg");
  // note use your own picture :-)
  $s = new SWFShape();
  $s->setRightFill($s->addFill($b));
  $s->drawLine($b->getWidth(), 0);
  $s->drawLine(0, $b->getHeight());
  $s->drawLine(-$b->getWidth(), 0);
  $s->drawLine(0, -$b->getHeight());

  $m = new SWFMovie();
  $m->setDimension($b->getWidth(), $b->getHeight());

  $i = $m->add($s);

  for($n=0; $n<=20; ++$n)
  {
    $i->multColor(1.0-$n/10, 1.0, 1.0);
    $i->addColor(0xff*$n/20, 0, 0);
    $m->nextFrame();
  }

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

SWFDisplayItem->remove

(no version information, might be only in CVS)

SWFDisplayItem->remove -- Removes the object from the movie

Description

void swfdisplayitem->remove ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swfdisplayitem->remove() removes this object from the movie's display list.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().

See also swfmovie->add().

SWFDisplayItem->Rotate

(no version information, might be only in CVS)

SWFDisplayItem->Rotate -- Rotates in relative coordinates.

Description

void swfdisplayitem->rotate ( float ddegrees)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swfdisplayitem->rotate() rotates the current object by ddegrees degrees from its current rotation.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().

See also swfdisplayitem->rotateto().

SWFDisplayItem->rotateTo

(no version information, might be only in CVS)

SWFDisplayItem->rotateTo -- Rotates the object in global coordinates.

Description

void swfdisplayitem->rotateto ( float degrees)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swfdisplayitem->rotateto() set the current object rotation to degrees degrees in global coordinates.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().

This example bring three rotating string from the background to the foreground. Pretty nice.

Exemplo 1. swfdisplayitem->rotateto() example

<?php
  $thetext =  "ming!";

  $f = new SWFFont("Bauhaus 93.fdb");

  $m = new SWFMovie();
  $m->setRate(24.0);
  $m->setDimension(2400, 1600);
  $m->setBackground(0xff, 0xff, 0xff);

  // functions with huge numbers of arbitrary
  // arguments are always a good idea!  Really!

  function text($r, $g, $b, $a, $rot, $x, $y, $scale, $string)
  {
    global $f, $m;

    $t = new SWFText();
    $t->setFont($f);
    $t->setColor($r, $g, $b, $a);
    $t->setHeight(960);
    $t->moveTo(-($f->getWidth($string))/2, $f->getAscent()/2);
    $t->addString($string);

    // we can add properties just like a normal php var,
    // as long as the names aren't already used.
    // e.g., we can't set $i->scale, because that's a function

    $i = $m->add($t);
    $i->x = $x;
    $i->y = $y;
    $i->rot = $rot;
    $i->s = $scale;
    $i->rotateTo($rot);
    $i->scale($scale, $scale);

    // but the changes are local to the function, so we have to
    // return the changed object.  kinda weird..

    return $i;
 }

  function step($i)
  {
    $oldrot = $i->rot;
    $i->rot = 19*$i->rot/20;
    $i->x = (19*$i->x + 1200)/20;
    $i->y = (19*$i->y + 800)/20;
    $i->s = (19*$i->s + 1.0)/20;

    $i->rotateTo($i->rot);
    $i->scaleTo($i->s, $i->s);
    $i->moveTo($i->x, $i->y);

    return $i;
  }

  // see?  it sure paid off in legibility:

  $i1 = text(0xff, 0x33, 0x33, 0xff, 900, 1200, 800, 0.03, $thetext);
  $i2 = text(0x00, 0x33, 0xff, 0x7f, -560, 1200, 800, 0.04, $thetext);
  $i3 = text(0xff, 0xff, 0xff, 0x9f, 180, 1200, 800, 0.001, $thetext);

  for($i=1; $i<=100; ++$i)
  {
    $i1 = step($i1);
    $i2 = step($i2);
    $i3 = step($i3);

    $m->nextFrame();
  }

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

See also swfdisplayitem->rotate().

SWFDisplayItem->scale

(no version information, might be only in CVS)

SWFDisplayItem->scale -- Scales the object in relative coordinates.

Description

void swfdisplayitem->scale ( int dx, int dy)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swfdisplayitem->scale() scales the current object by (dx,dy) from its current size.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().

See also swfdisplayitem->scaleto().

SWFDisplayItem->scaleTo

(no version information, might be only in CVS)

SWFDisplayItem->scaleTo -- Scales the object in global coordinates.

Description

void swfdisplayitem->scaleto ( int x, int y)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swfdisplayitem->scaleto() scales the current object to (x,y) in global coordinates.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().

See also swfdisplayitem->scale().

SWFDisplayItem->setDepth

(no version information, might be only in CVS)

SWFDisplayItem->setDepth -- Sets z-order

Description

void swfdisplayitem->setdepth ( float depth)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swfdisplayitem->rotate() sets the object's z-order to depth. Depth defaults to the order in which instances are created (by add'ing a shape/text to a movie)- newer ones are on top of older ones. If two objects are given the same depth, only the later-defined one can be moved.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().

SWFDisplayItem->setName

(no version information, might be only in CVS)

SWFDisplayItem->setName -- Sets the object's name

Description

void swfdisplayitem->setname ( string name)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swfdisplayitem->setname() sets the object's name to name, for targetting with action script. Only useful on sprites.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().

SWFDisplayItem->setRatio

(no version information, might be only in CVS)

SWFDisplayItem->setRatio -- Sets the object's ratio.

Description

void swfdisplayitem->setratio ( float ratio)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swfdisplayitem->setratio() sets the object's ratio to ratio. Obviously only useful for morphs.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().

This simple example will morph nicely three concentric circles.

Exemplo 1. swfdisplayitem->setname() example

<?php

  $p = new SWFMorph();

  $g = new SWFGradient();
  $g->addEntry(0.0, 0, 0, 0);
  $g->addEntry(0.16, 0xff, 0xff, 0xff);
  $g->addEntry(0.32, 0, 0, 0);
  $g->addEntry(0.48, 0xff, 0xff, 0xff);
  $g->addEntry(0.64, 0, 0, 0);
  $g->addEntry(0.80, 0xff, 0xff, 0xff);
  $g->addEntry(1.00, 0, 0, 0);

  $s = $p->getShape1();
  $f = $s->addFill($g, SWFFILL_RADIAL_GRADIENT);
  $f->scaleTo(0.05);
  $s->setLeftFill($f);
  $s->movePenTo(-160, -120);
  $s->drawLine(320, 0);
  $s->drawLine(0, 240);
  $s->drawLine(-320, 0);
  $s->drawLine(0, -240);

  $g = new SWFGradient();
  $g->addEntry(0.0, 0, 0, 0);
  $g->addEntry(0.16, 0xff, 0, 0);
  $g->addEntry(0.32, 0, 0, 0);
  $g->addEntry(0.48, 0, 0xff, 0);
  $g->addEntry(0.64, 0, 0, 0);
  $g->addEntry(0.80, 0, 0, 0xff);
  $g->addEntry(1.00, 0, 0, 0);

  $s = $p->getShape2();
  $f = $s->addFill($g, SWFFILL_RADIAL_GRADIENT);
  $f->scaleTo(0.05);
  $f->skewXTo(1.0);
  $s->setLeftFill($f);
  $s->movePenTo(-160, -120);
  $s->drawLine(320, 0);
  $s->drawLine(0, 240);
  $s->drawLine(-320, 0);
  $s->drawLine(0, -240);

  $m = new SWFMovie();
  $m->setDimension(320, 240);
  $i = $m->add($p);
  $i->moveTo(160, 120);

  for($n=0; $n<=1.001; $n+=0.01)
  {
    $i->setRatio($n);
    $m->nextFrame();
  }

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

SWFDisplayItem->skewX

(no version information, might be only in CVS)

SWFDisplayItem->skewX -- Sets the X-skew.

Description

void swfdisplayitem->skewx ( float ddegrees)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swfdisplayitem->skewx() adds ddegrees to current x-skew.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().

See also swfdisplayitem->skewx(), swfdisplayitem->skewy() and swfdisplayitem->skewyto().

SWFDisplayItem->skewXTo

(no version information, might be only in CVS)

SWFDisplayItem->skewXTo -- Sets the X-skew.

Description

void swfdisplayitem->skewxto ( float degrees)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swfdisplayitem->skewxto() sets the x-skew to degrees. For degrees is 1.0, it means a 45-degree forward slant. More is more forward, less is more backward.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().

See also swfdisplayitem->skewx(), swfdisplayitem->skewy() and swfdisplayitem->skewyto().

SWFDisplayItem->skewY

(no version information, might be only in CVS)

SWFDisplayItem->skewY -- Sets the Y-skew.

Description

void swfdisplayitem->skewy ( float ddegrees)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swfdisplayitem->skewy() adds ddegrees to current y-skew.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().

See also swfdisplayitem->skewyto(), swfdisplayitem->skewx() and swfdisplayitem->skewxto().

SWFDisplayItem->skewYTo

(no version information, might be only in CVS)

SWFDisplayItem->skewYTo -- Sets the Y-skew.

Description

void swfdisplayitem->skewyto ( float degrees)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swfdisplayitem->skewyto() sets the y-skew to degrees. For degrees is 1.0, it means a 45-degree forward slant. More is more upward, less is more downward.

The object may be a swfshape(), a swfbutton(), a swftext() or a swfsprite() object. It must have been added using the swfmovie->add().

See also swfdisplayitem->skewy(), swfdisplayitem->skewx() and swfdisplayitem->skewxto().

SWFDisplayItem

(no version information, might be only in CVS)

SWFDisplayItem -- Creates a new displayitem object.

Description

new swfdisplayitem ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swfdisplayitem() creates a new swfdisplayitem object.

Here's where all the animation takes place. After you define a shape, a text object, a sprite, or a button, you add it to the movie, then use the returned handle to move, rotate, scale, or skew the thing.

SWFDisplayItem has the following methods : swfdisplayitem->move(), swfdisplayitem->moveto(), swfdisplayitem->scaleto(), swfdisplayitem->scale(), swfdisplayitem->rotate(), swfdisplayitem->rotateto(), swfdisplayitem->skewxto(), swfdisplayitem->skewx(), swfdisplayitem->skewyto() swfdisplayitem->skewyto(), swfdisplayitem->setdepth() swfdisplayitem->remove(), swfdisplayitem->setname() swfdisplayitem->setratio(), swfdisplayitem->addcolor() and swfdisplayitem->multcolor().

SWFFill->moveTo

(no version information, might be only in CVS)

SWFFill->moveTo -- Moves fill origin

Description

void swffill->moveto ( int x, int y)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swffill->moveto() moves fill's origin to (x,y) in global coordinates.

SWFFill->rotateTo

(no version information, might be only in CVS)

SWFFill->rotateTo -- Sets fill's rotation

Description

void swffill->rotateto ( float degrees)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swffill->rotateto() sets fill's rotation to degrees degrees.

SWFFill->scaleTo

(no version information, might be only in CVS)

SWFFill->scaleTo -- Sets fill's scale

Description

void swffill->scaleto ( int x, int y)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swffill->scaleto() sets fill's scale to x in the x-direction, y in the y-direction.

SWFFill->skewXTo

(no version information, might be only in CVS)

SWFFill->skewXTo -- Sets fill x-skew

Description

void swffill->skewxto ( float x)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swffill->skewxto() sets fill x-skew to x. For x is 1.0, it is a is a 45-degree forward slant. More is more forward, less is more backward.

SWFFill->skewYTo

(no version information, might be only in CVS)

SWFFill->skewYTo -- Sets fill y-skew

Description

void swffill->skewyto ( float y)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swffill->skewyto() sets fill y-skew to y. For y is 1.0, it is a is a 45-degree upward slant. More is more upward, less is more downward.

SWFFill

SWFFill -- Loads SWFFill object

Description

The swffill() object allows you to transform (scale, skew, rotate) bitmap and gradient fills. swffill() objects are created by the swfshape->addfill() methods.

SWFFill has the following methods : swffill->moveto() and swffill->scaleto(), swffill->rotateto(), swffill->skewxto() and swffill->skewyto().

swffont->getwidth

(no version information, might be only in CVS)

swffont->getwidth -- Returns the string's width

Description

int swffont->getwidth ( string string)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swffont->getwidth() returns the string string's width, using font's default scaling. You'll probably want to use the SWFText() version of this method which uses the text object's scale.

SWFFont

(PHP 4 >= 4.0.5)

SWFFont -- Loads a font definition

Description

new swffont ( string filename)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

If filename is the name of an FDB file (i.e., it ends in ".fdb"), load the font definition found in said file. Otherwise, create a browser-defined font reference.

FDB ("font definition block") is a very simple wrapper for the SWF DefineFont2 block which contains a full description of a font. One may create FDB files from SWT Generator template files with the included makefdb utility- look in the util directory off the main ming distribution directory.

Browser-defined fonts don't contain any information about the font other than its name. It is assumed that the font definition will be provided by the movie player. The fonts _serif, _sans, and _typewriter should always be available. For example:
<?php
$f = newSWFFont("_sans"); 
?>
will give you the standard sans-serif font, probably the same as what you'd get with <font name="sans-serif"> in HTML.

swffont() returns a reference to the font definition, for use in the SWFText->setFont() and the SWFTextField->setFont() methods.

SWFFont has the following methods : swffont->getwidth().

SWFGradient->addEntry

(no version information, might be only in CVS)

SWFGradient->addEntry -- Adds an entry to the gradient list.

Description

void swfgradient->addentry ( float ratio, int red, int green, int blue [, int a])

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swfgradient->addentry() adds an entry to the gradient list. ratio is a number between 0 and 1 indicating where in the gradient this color appears. Thou shalt add entries in order of increasing ratio.

red, green, blue is a color (RGB mode). Last parameter a is optional.

SWFGradient

(PHP 4 >= 4.0.5)

SWFGradient -- Creates a gradient object

Description

new swfgradient ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swfgradient() creates a new SWFGradient object.

After you've added the entries to your gradient, you can use the gradient in a shape fill with the swfshape->addfill() method.

SWFGradient has the following methods : swfgradient->addentry().

This simple example will draw a big black-to-white gradient as background, and a redish disc in its center.

Exemplo 1. swfgradient() example

<?php

  $m = new SWFMovie();
  $m->setDimension(320, 240);

  $s = new SWFShape();

  // first gradient- black to white
  $g = new SWFGradient();
  $g->addEntry(0.0, 0, 0, 0);
  $g->addEntry(1.0, 0xff, 0xff, 0xff);

  $f = $s->addFill($g, SWFFILL_LINEAR_GRADIENT);
  $f->scaleTo(0.01);
  $f->moveTo(160, 120);
  $s->setRightFill($f);
  $s->drawLine(320, 0);
  $s->drawLine(0, 240);
  $s->drawLine(-320, 0);
  $s->drawLine(0, -240);

  $m->add($s);

  $s = new SWFShape();

  // second gradient- radial gradient from red to transparent
  $g = new SWFGradient();
  $g->addEntry(0.0, 0xff, 0, 0, 0xff);
  $g->addEntry(1.0, 0xff, 0, 0, 0);

  $f = $s->addFill($g, SWFFILL_RADIAL_GRADIENT);
  $f->scaleTo(0.005);
  $f->moveTo(160, 120);
  $s->setRightFill($f);
  $s->drawLine(320, 0);
  $s->drawLine(0, 240);
  $s->drawLine(-320, 0);
  $s->drawLine(0, -240);

  $m->add($s);

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

SWFMorph->getshape1

(no version information, might be only in CVS)

SWFMorph->getshape1 -- Gets a handle to the starting shape

Description

mixed swfmorph->getshape1 ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swfmorph->getshape1() gets a handle to the morph's starting shape. swfmorph->getshape1() returns an swfshape() object.

SWFMorph->getshape2

(no version information, might be only in CVS)

SWFMorph->getshape2 -- Gets a handle to the ending shape

Description

mixed swfmorph->getshape2 ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swfmorph->getshape2() gets a handle to the morph's ending shape. swfmorph->getshape2() returns an swfshape() object.

SWFMorph

(PHP 4 >= 4.0.5)

SWFMorph -- Creates a new SWFMorph object.

Description

new swfmorph ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swfmorph() creates a new SWFMorph object.

Also called a "shape tween". This thing lets you make those tacky twisting things that make your computer choke. Oh, joy!

The methods here are sort of weird. It would make more sense to just have newSWFMorph(shape1, shape2);, but as things are now, shape2 needs to know that it's the second part of a morph. (This, because it starts writing its output as soon as it gets drawing commands- if it kept its own description of its shapes and wrote on completion this and some other things would be much easier.)

SWFMorph has the following methods : swfmorph->getshape1() and swfmorph->getshape1().

This simple example will morph a big red square into a smaller blue black-bordered square.

Exemplo 1. swfmorph() example

<?php
  $p = new SWFMorph();

  $s = $p->getShape1();
  $s->setLine(0,0,0,0);

  /* Note that this is backwards from normal shapes (left instead of right).
     I have no idea why, but this seems to work.. */

  $s->setLeftFill($s->addFill(0xff, 0, 0));
  $s->movePenTo(-1000,-1000);
  $s->drawLine(2000,0);
  $s->drawLine(0,2000);
  $s->drawLine(-2000,0);
  $s->drawLine(0,-2000);

  $s = $p->getShape2();
  $s->setLine(60,0,0,0);
  $s->setLeftFill($s->addFill(0, 0, 0xff));
  $s->movePenTo(0,-1000);
  $s->drawLine(1000,1000);
  $s->drawLine(-1000,1000);
  $s->drawLine(-1000,-1000);
  $s->drawLine(1000,-1000);

  $m = new SWFMovie();
  $m->setDimension(3000,2000);
  $m->setBackground(0xff, 0xff, 0xff);

  $i = $m->add($p);
  $i->moveTo(1500,1000);

  for($r=0.0; $r<=1.0; $r+=0.1)
  {
    $i->setRatio($r);
    $m->nextFrame();
  }

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

SWFMovie->add

(no version information, might be only in CVS)

SWFMovie->add -- Adds any type of data to a movie.

Description

void swfmovie->add ( ressource instance)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swfmovie->add() adds instance to the current movie. instance is any type of data : Shapes, text, fonts, etc. must all be add'ed to the movie to make this work.

For displayable types (shape, text, button, sprite), this returns an SWFDisplayItem(), a handle to the object in a display list. Thus, you can add the same shape to a movie multiple times and get separate handles back for each separate instance.

See also all other objects (adding this later), and swfmovie->remove()

See examples in : swfdisplayitem->rotateto() and swfshape->addfill().

SWFMovie->nextframe

(no version information, might be only in CVS)

SWFMovie->nextframe -- Moves to the next frame of the animation.

Description

void swfmovie->nextframe ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swfmovie->nextframe() moves to the next frame of the animation.

SWFMovie->output

(no version information, might be only in CVS)

SWFMovie->output -- Dumps your lovingly prepared movie out.

Description

void swfmovie->output ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swfmovie->output() dumps your lovingly prepared movie out. In PHP, preceding this with the command
<?php
header('Content-type: application/x-shockwave-flash'); 
?>
convinces the browser to display this as a flash movie.

See also swfmovie->save().

See examples in : swfmovie->streammp3(), swfdisplayitem->rotateto(), swfaction()... Any example will use this method.

SWFMovie->remove

(no version information, might be only in CVS)

SWFMovie->remove -- Removes the object instance from the display list.

Description

void swfmovie->remove ( resource instance)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swfmovie->remove() removes the object instance instance from the display list.

See also swfmovie->add().

SWFMovie->save

(no version information, might be only in CVS)

SWFMovie->save -- Saves your movie in a file.

Description

void swfmovie->save ( string filename)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swfmovie->save() saves your movie to the file named filename.

See also output().

SWFMovie->setbackground

(no version information, might be only in CVS)

SWFMovie->setbackground -- Sets the background color.

Description

void swfmovie->setbackground ( int red, int green, int blue)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swfmovie->setbackground() sets the background color. Why is there no rgba version? Think about it. (Actually, that's not such a dumb question after all- you might want to let the html background show through. There's a way to do that, but it only works on IE4. Search the http://www.macromedia.com/ site for details.)

SWFMovie->setdimension

(no version information, might be only in CVS)

SWFMovie->setdimension -- Sets the movie's width and height.

Description

void swfmovie->setdimension ( int width, int height)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swfmovie->setdimension() sets the movie's width to width and height to height.

SWFMovie->setframes

(no version information, might be only in CVS)

SWFMovie->setframes -- Sets the total number of frames in the animation.

Description

void swfmovie->setframes ( string numberofframes)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swfmovie->setframes() sets the total number of frames in the animation to numberofframes.

SWFMovie->setrate

(no version information, might be only in CVS)

SWFMovie->setrate -- Sets the animation's frame rate.

Description

void swfmovie->setrate ( int rate)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swfmovie->setrate() sets the frame rate to rate, in frame per seconds. Animation will slow down if the player can't render frames fast enough- unless there's a streaming sound, in which case display frames are sacrificed to keep sound from skipping.

SWFMovie->streammp3

(no version information, might be only in CVS)

SWFMovie->streammp3 -- Streams a MP3 file.

Description

void swfmovie->streammp3 ( string mp3FileName)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swfmovie->streammp3() streams the mp3 file mp3FileName. Not very robust in dealing with oddities (can skip over an initial ID3 tag, but that's about it). Like SWFShape->addJpegFill(), this isn't a stable function- we'll probably need to make a separate SWFSound object to contain sound types.

Note that the movie isn't smart enough to put enough frames in to contain the entire mp3 stream- you'll have to add (length of song * frames per second) frames to get the entire stream in.

Yes, now you can use ming to put that rock and roll devil worship music into your SWF files. Just don't tell the RIAA.

Exemplo 1. swfmovie->streammp3() example

<?php
  $m = new SWFMovie();
  $m->setRate(12.0);
  $m->streamMp3("distortobass.mp3");
  // use your own MP3

  // 11.85 seconds at 12.0 fps = 142 frames
  $m->setFrames(142);

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

SWFMovie

(PHP 4 >= 4.0.5)

SWFMovie -- Creates a new movie object, representing an SWF version 4 movie.

Description

new swfmovie ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swfmovie() creates a new movie object, representing an SWF version 4 movie.

SWFMovie has the following methods : swfmovie->output(),swfmovie->save(), swfmovie->add(), swfmovie->remove(), swfmovie->nextframe(), swfmovie->setbackground(), swfmovie->setrate(), swfmovie->setdimension(), swfmovie->setframes() and swfmovie->streammp3().

See examples in : swfdisplayitem->rotateto(), swfshape->setline(), swfshape->addfill()... Any example will use this object.

SWFShape->addFill

(no version information, might be only in CVS)

SWFShape->addFill -- Adds a solid fill to the shape.

Description

void swfshape->addfill ( int red, int green, int blue [, int a])

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

void swfshape->addfill ( SWFbitmap bitmap [, int flags])

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

void swfshape->addfill ( SWFGradient gradient [, int flags])

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swfshape->addfill() adds a solid fill to the shape's list of fill styles. swfshape->addfill() accepts three different types of arguments.

red, green, blue is a color (RGB mode). Last parameter a is optional.

The bitmap argument is an swfbitmap() object. The flags argument can be one of the following values : SWFFILL_CLIPPED_BITMAP or SWFFILL_TILED_BITMAP. Default is SWFFILL_TILED_BITMAP. I think.

The gradient argument is an swfgradient() object. The flags argument can be one of the following values : SWFFILL_RADIAL_GRADIENT or SWFFILL_LINEAR_GRADIENT. Default is SWFFILL_LINEAR_GRADIENT. I'm sure about this one. Really.

swfshape->addfill() returns an swffill() object for use with the swfshape->setleftfill() and swfshape->setrightfill() functions described below.

See also swfshape->setleftfill() and swfshape->setrightfill().

This simple example will draw a frame on a bitmap. Ah, here's another buglet in the flash player- it doesn't seem to care about the second shape's bitmap's transformation in a morph. According to spec, the bitmap should stretch along with the shape in this example..

Exemplo 1. swfshape->addfill() example

<?php

  $p = new SWFMorph();

  $b = new SWFBitmap("alphafill.jpg");
  // use your own bitmap
  $width = $b->getWidth();
  $height = $b->getHeight();

  $s = $p->getShape1();
  $f = $s->addFill($b, SWFFILL_TILED_BITMAP);
  $f->moveTo(-$width/2, -$height/4);
  $f->scaleTo(1.0, 0.5);
  $s->setLeftFill($f);
  $s->movePenTo(-$width/2, -$height/4);
  $s->drawLine($width, 0);
  $s->drawLine(0, $height/2);
  $s->drawLine(-$width, 0);
  $s->drawLine(0, -$height/2);

  $s = $p->getShape2();
  $f = $s->addFill($b, SWFFILL_TILED_BITMAP);

  // these two have no effect!
  $f->moveTo(-$width/4, -$height/2);
  $f->scaleTo(0.5, 1.0);

  $s->setLeftFill($f);
  $s->movePenTo(-$width/4, -$height/2);
  $s->drawLine($width/2, 0);
  $s->drawLine(0, $height);
  $s->drawLine(-$width/2, 0);
  $s->drawLine(0, -$height);

  $m = new SWFMovie();
  $m->setDimension($width, $height);
  $i = $m->add($p);
  $i->moveTo($width/2, $height/2);

  for($n=0; $n<1.001; $n+=0.03)
  {
    $i->setRatio($n);
    $m->nextFrame();
  }

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

SWFShape->drawCurve

(no version information, might be only in CVS)

SWFShape->drawCurve -- Draws a curve (relative).

Description

void swfshape->drawcurve ( int controldx, int controldy, int anchordx, int anchordy)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swfshape->drawcurve() draws a quadratic curve (using the current line style,set by swfshape->setline()) from the current pen position to the relative position (anchorx,anchory) using relative control point (controlx,controly). That is, head towards the control point, then smoothly turn to the anchor point.

See also swfshape->drawlineto(), swfshape->drawline(), swfshape->movepento() and swfshape->movepen().

SWFShape->drawCurveTo

(no version information, might be only in CVS)

SWFShape->drawCurveTo -- Draws a curve.

Description

void swfshape->drawcurveto ( int controlx, int controly, int anchorx, int anchory)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swfshape->drawcurveto() draws a quadratic curve (using the current line style, set by swfshape->setline()) from the current pen position to (anchorx,anchory) using (controlx,controly) as a control point. That is, head towards the control point, then smoothly turn to the anchor point.

See also swfshape->drawlineto(), swfshape->drawline(), swfshape->movepento() and swfshape->movepen().

SWFShape->drawLine

(no version information, might be only in CVS)

SWFShape->drawLine -- Draws a line (relative).

Description

void swfshape->drawline ( int dx, int dy)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swfshape->drawline() draws a line (using the current line style set by swfshape->setline()) from the current pen position to displacement (dx,dy).

See also swfshape->movepento(), swfshape->drawcurveto(), swfshape->movepen() and swfshape->drawlineto().

SWFShape->drawLineTo

(no version information, might be only in CVS)

SWFShape->drawLineTo -- Draws a line.

Description

void swfshape->drawlineto ( int x, int y)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swfshape->setrightfill() draws a line (using the current line style, set by swfshape->setline()) from the current pen position to point (x,y) in the shape's coordinate space.

See also swfshape->movepento(), swfshape->drawcurveto(), swfshape->movepen() and swfshape->drawline().

SWFShape->movePen

(no version information, might be only in CVS)

SWFShape->movePen -- Moves the shape's pen (relative).

Description

void swfshape->movepen ( int dx, int dy)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swfshape->setrightfill() move the shape's pen from coordinates (current x,current y) to (current x + dx, current y + dy) in the shape's coordinate space.

See also swfshape->movepento(), swfshape->drawcurveto(), swfshape->drawlineto() and swfshape->drawline().

SWFShape->movePenTo

(no version information, might be only in CVS)

SWFShape->movePenTo -- Moves the shape's pen.

Description

void swfshape->movepento ( int x, int y)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swfshape->setrightfill() move the shape's pen to (x,y) in the shape's coordinate space.

See also swfshape->movepen(), swfshape->drawcurveto(), swfshape->drawlineto() and swfshape->drawline().

SWFShape->setLeftFill

(no version information, might be only in CVS)

SWFShape->setLeftFill -- Sets left rasterizing color.

Description

void swfshape->setleftfill ( swfgradient fill)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

void swfshape->setleftfill ( int red, int green, int blue [, int a])

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

What this nonsense is about is, every edge segment borders at most two fills. When rasterizing the object, it's pretty handy to know what those fills are ahead of time, so the swf format requires these to be specified.

swfshape->setleftfill() sets the fill on the left side of the edge- that is, on the interior if you're defining the outline of the shape in a counter-clockwise fashion. The fill object is an SWFFill object returned from one of the addFill functions above.

This seems to be reversed when you're defining a shape in a morph, though. If your browser crashes, just try setting the fill on the other side.

Shortcut for swfshape->setleftfill($s->addfill($r, $g, $b [, $a]));.

See also swfshape->setrightfill().

SWFShape->setLine

(no version information, might be only in CVS)

SWFShape->setLine -- Sets the shape's line style.

Description

void swfshape->setline ( int width [, int red [, int green [, int blue [, int a]]]])

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swfshape->setline() sets the shape's line style. width is the line's width. If width is 0, the line's style is removed (then, all other arguments are ignored). If width > 0, then line's color is set to red, green, blue. Last parameter a is optional.

swfshape->setline() accepts 1, 4 or 5 arguments (not 3 or 2).

You must declare all line styles before you use them (see example).

This simple example will draw a big "!#%*@", in funny colors and gracious style.

Exemplo 1. swfshape->setline() example

<?php
  $s = new SWFShape();
  $f1 = $s->addFill(0xff, 0, 0);
  $f2 = $s->addFill(0xff, 0x7f, 0);
  $f3 = $s->addFill(0xff, 0xff, 0);
  $f4 = $s->addFill(0, 0xff, 0);
  $f5 = $s->addFill(0, 0, 0xff);

  // bug: have to declare all line styles before you use them
  $s->setLine(40, 0x7f, 0, 0);
  $s->setLine(40, 0x7f, 0x3f, 0);
  $s->setLine(40, 0x7f, 0x7f, 0);
  $s->setLine(40, 0, 0x7f, 0);
  $s->setLine(40, 0, 0, 0x7f);

  $f = new SWFFont('Techno.fdb');

  $s->setRightFill($f1);
  $s->setLine(40, 0x7f, 0, 0);
  $s->drawGlyph($f, '!');
  $s->movePen($f->getWidth('!'), 0);

  $s->setRightFill($f2);
  $s->setLine(40, 0x7f, 0x3f, 0);
  $s->drawGlyph($f, '#');
  $s->movePen($f->getWidth('#'), 0);

  $s->setRightFill($f3);
  $s->setLine(40, 0x7f, 0x7f, 0);
  $s->drawGlyph($f, '%');
  $s->movePen($f->getWidth('%'), 0);

  $s->setRightFill($f4);
  $s->setLine(40, 0, 0x7f, 0);
  $s->drawGlyph($f, '*');
  $s->movePen($f->getWidth('*'), 0);

  $s->setRightFill($f5);
  $s->setLine(40, 0, 0, 0x7f);
  $s->drawGlyph($f, '@');

  $m = new SWFMovie();
  $m->setDimension(3000,2000);
  $m->setRate(12.0);
  $i = $m->add($s);
  $i->moveTo(1500-$f->getWidth("!#%*@")/2, 1000+$f->getAscent()/2);

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

SWFShape->setRightFill

(no version information, might be only in CVS)

SWFShape->setRightFill -- Sets right rasterizing color.

Description

void swfshape->setrightfill ( swfgradient fill)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

void swfshape->setrightfill ( int red, int green, int blue [, int a])

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

See also swfshape->setleftfill().

Shortcut for swfshape->setrightfill($s->addfill($r, $g, $b [, $a]));.

SWFShape

(PHP 4 >= 4.0.5)

SWFShape -- Creates a new shape object.

Description

new swfshape ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swfshape() creates a new shape object.

SWFShape has the following methods : swfshape->setline(), swfshape->addfill(), swfshape->setleftfill(), swfshape->setrightfill(), swfshape->movepento(), swfshape->movepen(), swfshape->drawlineto(), swfshape->drawline(), swfshape->drawcurveto() and swfshape->drawcurve().

This simple example will draw a big red elliptic quadrant.

Exemplo 1. swfshape() example

<?php
  $s = new SWFShape();
  $s->setLine(40, 0x7f, 0, 0);
  $s->setRightFill($s->addFill(0xff, 0, 0));
  $s->movePenTo(200, 200);
  $s->drawLineTo(6200, 200);
  $s->drawLineTo(6200, 4600);
  $s->drawCurveTo(200, 4600, 200, 200);

  $m = new SWFMovie();
  $m->setDimension(6400, 4800);
  $m->setRate(12.0);
  $m->add($s);
  $m->nextFrame();

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

SWFSprite->add

(no version information, might be only in CVS)

SWFSprite->add -- Adds an object to a sprite

Description

void swfsprite->add ( resource object)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swfsprite->add() adds a swfshape(), a swfbutton(), a swftext(), a swfaction() or a swfsprite() object.

For displayable types (swfshape(), swfbutton(), swftext(), swfaction() or swfsprite()), this returns a handle to the object in a display list.

SWFSprite->nextframe

(no version information, might be only in CVS)

SWFSprite->nextframe -- Moves to the next frame of the animation.

Description

void swfsprite->nextframe ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swfsprite->setframes() moves to the next frame of the animation.

SWFSprite->remove

(no version information, might be only in CVS)

SWFSprite->remove -- Removes an object to a sprite

Description

void swfsprite->remove ( ressource object)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swfsprite->remove() remove a swfshape(), a swfbutton(), a swftext(), a swfaction() or a swfsprite() object from the sprite.

SWFSprite->setframes

(no version information, might be only in CVS)

SWFSprite->setframes -- Sets the total number of frames in the animation.

Description

void swfsprite->setframes ( int numberofframes)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swfsprite->setframes() sets the total number of frames in the animation to numberofframes.

SWFSprite

(PHP 4 >= 4.0.5)

SWFSprite -- Creates a movie clip (a sprite)

Description

new swfsprite ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swfsprite() are also known as a "movie clip", this allows one to create objects which are animated in their own timelines. Hence, the sprite has most of the same methods as the movie.

swfsprite() has the following methods : swfsprite->add(), swfsprite->remove(), swfsprite->nextframe() and swfsprite->setframes().

This simple example will spin gracefully a big red square.

Exemplo 1. swfsprite() example

<?php
  $s = new SWFShape();
  $s->setRightFill($s->addFill(0xff, 0, 0));
  $s->movePenTo(-500,-500);
  $s->drawLineTo(500,-500);
  $s->drawLineTo(500,500);
  $s->drawLineTo(-500,500);
  $s->drawLineTo(-500,-500);

  $p = new SWFSprite();
  $i = $p->add($s);
  $p->nextFrame();
  $i->rotate(15);
  $p->nextFrame();
  $i->rotate(15);
  $p->nextFrame();
  $i->rotate(15);
  $p->nextFrame();
  $i->rotate(15);
  $p->nextFrame();
  $i->rotate(15);
  $p->nextFrame();

  $m = new SWFMovie();
  $i = $m->add($p);
  $i->moveTo(1500,1000);
  $i->setName("blah");

  $m->setBackground(0xff, 0xff, 0xff);
  $m->setDimension(3000,2000);

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

SWFText->addString

(no version information, might be only in CVS)

SWFText->addString -- Draws a string

Description

void swftext->addstring ( string string)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swftext->addstring() draws the string string at the current pen (cursor) location. Pen is at the baseline of the text; i.e., ascending text is in the -y direction.

SWFText->getWidth

(no version information, might be only in CVS)

SWFText->getWidth -- Computes string's width

Description

void swftext->addstring ( string string)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swftext->addstring() returns the rendered width of the string string at the text object's current font, scale, and spacing settings.

SWFText->moveTo

(no version information, might be only in CVS)

SWFText->moveTo -- Moves the pen

Description

void swftext->moveto ( int x, int y)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swftext->moveto() moves the pen (or cursor, if that makes more sense) to (x,y) in text object's coordinate space. If either is zero, though, value in that dimension stays the same. Annoying, should be fixed.

SWFText->setColor

(no version information, might be only in CVS)

SWFText->setColor -- Sets the current font color

Description

void swftext->setcolor ( int red, int green, int blue [, int a])

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swftext->setspacing() changes the current text color. Default is black. I think. Color is represented using the RGB system.

SWFText->setFont

(no version information, might be only in CVS)

SWFText->setFont -- Sets the current font

Description

void swftext->setfont ( string font)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swftext->setfont() sets the current font to font.

SWFText->setHeight

(no version information, might be only in CVS)

SWFText->setHeight -- Sets the current font height

Description

void swftext->setheight ( int height)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swftext->setheight() sets the current font height to height. Default is 240.

SWFText->setSpacing

(no version information, might be only in CVS)

SWFText->setSpacing -- Sets the current font spacing

Description

void swftext->setspacing ( float spacing)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swftext->setspacing() sets the current font spacing to spacingspacing. Default is 1.0. 0 is all of the letters written at the same point. This doesn't really work that well because it inflates the advance across the letter, doesn't add the same amount of spacing between the letters. I should try and explain that better, prolly. Or just fix the damn thing to do constant spacing. This was really just a way to figure out how letter advances work, anyway.. So nyah.

SWFText

(PHP 4 >= 4.0.5)

SWFText -- Creates a new SWFText object.

Description

new swftext ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swftext() creates a new SWFText object, fresh for manipulating.

SWFText has the following methods : swftext->setfont(), swftext->setheight(), swftext->setspacing(), swftext->setcolor(), swftext->moveto(), swftext->addstring() and swftext->getwidth().

This simple example will draw a big yellow "PHP generates Flash with Ming" text, on white background.

Exemplo 1. swftext() example

<?php
  $f = new SWFFont("Techno.fdb");
  $t = new SWFText();
  $t->setFont($f);
  $t->moveTo(200, 2400);
  $t->setColor(0xff, 0xff, 0);
  $t->setHeight(1200);
  $t->addString("PHP generates Flash with Ming!!");

  $m = new SWFMovie();
  $m->setDimension(5400, 3600);

  $m->add($t);

  header('Content-type: application/x-shockwave-flash');
  $m->output();
?>

SWFTextField->addstring

(no version information, might be only in CVS)

SWFTextField->addstring -- Concatenates the given string to the text field

Description

void swftextfield->addstring ( string string)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swftextfield->setname() concatenates the string string to the text field.

SWFTextField->align

(no version information, might be only in CVS)

SWFTextField->align -- Sets the text field alignment

Description

void swftextfield->align ( int alignement)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swftextfield->align() sets the text field alignment to alignement. Valid values for alignement are : SWFTEXTFIELD_ALIGN_LEFT, SWFTEXTFIELD_ALIGN_RIGHT, SWFTEXTFIELD_ALIGN_CENTER and SWFTEXTFIELD_ALIGN_JUSTIFY.

SWFTextField->setbounds

(no version information, might be only in CVS)

SWFTextField->setbounds -- Sets the text field width and height

Description

void swftextfield->setbounds ( int width, int height)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swftextfield->setbounds() sets the text field width to width and height to height. If you don't set the bounds yourself, Ming makes a poor guess at what the bounds are.

SWFTextField->setcolor

(no version information, might be only in CVS)

SWFTextField->setcolor -- Sets the color of the text field.

Description

void swftextfield->setcolor ( int red, int green, int blue [, int a])

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swftextfield->setcolor() sets the color of the text field. Default is fully opaque black. Color is represented using RGB system.

SWFTextField->setFont

(no version information, might be only in CVS)

SWFTextField->setFont -- Sets the text field font

Description

void swftextfield->setfont ( string font)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swftextfield->setfont() sets the text field font to the [browser-defined?] font font.

SWFTextField->setHeight

(no version information, might be only in CVS)

SWFTextField->setHeight -- Sets the font height of this text field font.

Description

void swftextfield->setheight ( int height)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swftextfield->setheight() sets the font height of this text field font to the given height height. Default is 240.

SWFTextField->setindentation

(no version information, might be only in CVS)

SWFTextField->setindentation -- Sets the indentation of the first line.

Description

void swftextfield->setindentation ( int width)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swftextfield->setindentation() sets the indentation of the first line in the text field, to width.

SWFTextField->setLeftMargin

(no version information, might be only in CVS)

SWFTextField->setLeftMargin -- Sets the left margin width of the text field.

Description

void swftextfield->setleftmargin ( int width)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swftextfield->setleftmargin() sets the left margin width of the text field to width. Default is 0.

SWFTextField->setLineSpacing

(no version information, might be only in CVS)

SWFTextField->setLineSpacing -- Sets the line spacing of the text field.

Description

void swftextfield->setlinespacing ( int height)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swftextfield->setlinespacing() sets the line spacing of the text field to the height of height. Default is 40.

SWFTextField->setMargins

(no version information, might be only in CVS)

SWFTextField->setMargins -- Sets the margins width of the text field.

Description

void swftextfield->setmargins ( int left, int right)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swftextfield->setmargins() set both margins at once, for the man on the go.

SWFTextField->setname

(no version information, might be only in CVS)

SWFTextField->setname -- Sets the variable name

Description

void swftextfield->setname ( string name)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swftextfield->setname() sets the variable name of this text field to name, for form posting and action scripting purposes.

SWFTextField->setrightMargin

(no version information, might be only in CVS)

SWFTextField->setrightMargin -- Sets the right margin width of the text field.

Description

void swftextfield->setrightmargin ( int width)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swftextfield->setrightmargin() sets the right margin width of the text field to width. Default is 0.

SWFTextField

(PHP 4 >= 4.0.5)

SWFTextField -- Creates a text field object

Description

new swftextfield ( [int flags])

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

swftextfield() creates a new text field object. Text Fields are less flexible than swftext() objects- they can't be rotated, scaled non-proportionally, or skewed, but they can be used as form entries, and they can use browser-defined fonts.

The optional flags change the text field's behavior. It has the following possibles values :

  • SWFTEXTFIELD_DRAWBOX draws the outline of the textfield

  • SWFTEXTFIELD_HASLENGTH

  • SWFTEXTFIELD_HTML allows text markup using HTML-tags

  • SWFTEXTFIELD_MULTILINE allows multiple lines

  • SWFTEXTFIELD_NOEDIT indicates that the field shouldn't be user-editable

  • SWFTEXTFIELD_NOSELECT makes the field non-selectable

  • SWFTEXTFIELD_PASSWORD obscures the data entry

  • SWFTEXTFIELD_WORDWRAP allows text to wrap

Flags are combined with the bitwise OR operation. For example,
<?php
$t = newSWFTextField(SWFTEXTFIELD_PASSWORD | SWFTEXTFIELD_NOEDIT); 
?>
creates a totally useless non-editable password field.

SWFTextField has the following methods : swftextfield->setfont(), swftextfield->setbounds(), swftextfield->align(), swftextfield->setheight(), swftextfield->setleftmargin(), swftextfield->setrightmargin(), swftextfield->setmargins(), swftextfield->setindentation(), swftextfield->setlinespacing(), swftextfield->setcolor(), swftextfield->setname() and swftextfield->addstring().

LX. Funções de Miscelânea

Introdução

Estas funções foram colocadas aqui porque pareciam não caber em nenhuma outra categoria.


Requisitos

Nenhuma biblioteca externa é necessária para compilar esta extensão.


Instalação

Não há nenhuma instalação nescessária para utilizar estas funções, elas fazem parte do núcleo do PHP.


Configuração durante execução

O comportamento dessas funções podem ser modificado pelas configurações do php.ini.

Tabela 1. Opções de Configuração

Nome Padrão Modificável
ignore_user_abort "0" PHP_INI_ALL
highlight.string #CC0000 PHP_INI_ALL
highlight.comment #FF9900 PHP_INI_ALL
highlight.keyword #006600 PHP_INI_ALL
highlight.bg #FFFFFF PHP_INI_ALL
highlight.default #0000CC PHP_INI_ALL
highlight.html #000000 PHP_INI_ALL
browscap NULL PHP_INI_SYSTEM
Para maiores detalhes e definição das constantes PHP_INI_* veja ini_set().

Aqui esta uma pequena explicação das diretivas de configuração.

ignore_user_abort boolean

TRUE por padrão. Se modificado para FALSE os scripts terminaram assim que o cliente tentar enviar algo após o cliente ter abortado sua conexão.

Veja também ignore_user_abort().

highlight.xxx string

Cores para o modo de destaque da sintaxe. Qualquer coisa aceitável em <font color="??????"> deve funcionar.

browscap string

Nome (ex: browscap.ini)e localização do arquivo com as capacidades do browser. Veja também get_browser().


Tipos Resource

Esta extensão não possui nenhum tipo resource.


Constantes Predefinidas

Esta extensão não possui nenhuma constante.

Índice
connection_aborted -- Retorna TRUE se o cliente desconectou
connection_status -- Retorna o status da conexão
connection_timeout -- Retorna TRUE se o script ultrapassou o limite de tempo
constant -- Retorna o valor de uma constante
define -- Define uma constante.
defined --  Confere se uma constante existe
die -- Apelido para exit()
eval -- Executa uma string como código PHP
exit -- Mostra uma mensagem e termina o script atual
get_browser --  Diz o que o browser do usuário pode fazer
highlight_file -- Destaca a sintaxe de um arquivo
highlight_string -- Destaque da sintaxe de uma string
ignore_user_abort --  Estabelece se acontecerá o enceramento do script quando o usuário abortar a conexão
pack -- Pack data into binary string.
show_source -- Destaca a sintaxe de um arquivo
sleep -- Atrasa a execução do script
uniqid -- Gera um ID unico
unpack -- Unpack data from binary string
usleep -- Atrasa a execução em milionésimos de segundo

connection_aborted

(PHP 3>= 3.0.7, PHP 4 )

connection_aborted -- Retorna TRUE se o cliente desconectou

Descrição

int connection_aborted ( void)

Retorna TRUE se o cliente desconectou. Veja a descrição de Connection Handling no capitulo Features para uma explicação completa.

connection_status

(PHP 3>= 3.0.7, PHP 4 )

connection_status -- Retorna o status da conexão

Descrição

int connection_status ( void)

Retorna o estado da conexão. Veja a descrição de Connection Handling no capitulo Features para uma explicação completa.

connection_timeout

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

connection_timeout -- Retorna TRUE se o script ultrapassou o limite de tempo

Descrição

bool connection_timeout ( void)

Retorna TRUE se o script ultrapassou o limite de tempo.

Obsoleta

Esta função é obsoleta, e não existe mais desde o PHP 4.0.5.

Veja a descrição de Connection Handling no capitulo Features para uma explicação completa.

constant

(PHP 4 >= 4.0.4)

constant -- Retorna o valor de uma constante

Descrição

mixed constant ( string name)

A função constant() irá retornar o valor de uma constante indicada pelo parâmetro name.

A função constant() é útil se você precisa pegar o valor de uma constante, mas não sabe o seu nome. Ex: esta guardada em uma variável ou é retornada por uma função.

Exemplo 1. Exemplo constant()

<?php

define ("MAXSIZE", 100);

echo MAXSIZE;
echo constant("MAXSIZE"); // mesma coisa que a linha anterior

?>

Veja também define(), defined() e a seção sobre Constantes.

define

(PHP 3, PHP 4 )

define -- Define uma constante.

Descrição

bool define ( string name, mixed value [, bool case_insensitive])

Define uma constante. Veja a seção sobre constantes para maiores detalhes.

O nome da constante é dado pelo parâmetro name; o valor é dado por value.

O terceiro parâmetro, que é opcional, case_insensitive também esta disponível. Se é dado o valor TRUE, então a constante será definida como case-insensitive. O padrão é case-sensitive; ex. CONSTANTE e Constante representam valores diferentes.

Exemplo 1. Definindo Constantes

<?php
define ("CONSTANTE", "Alô Mundo.");
echo CONSTANTE; // mostra "Alô Mundo."
echo Constante; // mostra "Constante" e dá um aviso.

define ("GREETING", "Alô Você.",TRUE);
echo GREETING; // mostra "Alô você."
echo Greeting; // mostra "Alô você."

?>

Retorna TRUE em caso de sucesso ou FALSE em falhas.

Vejá também defined(), constant()e a seção sobre Constantes.

defined

(PHP 3, PHP 4 )

defined --  Confere se uma constante existe

Descrição

bool defined ( string name)

Retorna TRUE se a constante dada pelo parâmetro name já foi definida, em outro caso FALSE.

Exemplo 1. Conferindo Constantes

<?php
if (defined("CONSTANT")){ //Note que deve estar entre aspas
    echo CONSTANT; //
    }
?>

Veja também define(), constant(), get_defined_constants()e a seção sobre Constants.

die

die -- Apelido para exit()

Descrição

Esta função é um apelido para exit().

eval

(PHP 3, PHP 4 )

eval -- Executa uma string como código PHP

Descrição

mixed eval ( string code_str)

A função eval() executa a string dada no parâmetro code_str como código PHP. Entre outras coisas, isto pode ser útil para guardar código em um campo de texto de um banco de dados para execução posterior.

Há alguns fatores para lembrar quando usar eval(). Lembre-se que a string passada deve ser código PHP valido, incluindo coisas como terminar os comandos com ponto-e-vírgula assim o compilador não morre uma linha após eval(), escapar as coisas propriamente em code_str.

Também se lembre que as variáveis que tenham seus valores em eval() irão reter estes valores para o resto do script.

Um comando return irá terminar a execução do script imediatamente No PHP 4, eval() retorna NULL a menos que return() seja chamado no código executado, caso no qual o valor passado para return() é retornado. No PHP 3, eval() não retorna um valor.

Exemplo 1. Exemplo eval()

<?php
$string = 'taça';
$name = 'café';
$str = 'Esta é uma $string com o meu $name nela.<br>';
echo $str;
eval ("\$str = \"$str\";");
echo $str;
?>

O exemplo acima irá mostrar
Esta é uma $string com o meu $name nela.
Esta é uma taça com o meu café nela.

Dica: Como toda saída é normalmente enviada direto para o browser, você pode usar as Funções de Controle de Output para capturar o resultado e guardá-lo em uma string (por exemplo).

exit

(PHP 3, PHP 4 )

exit -- Mostra uma mensagem e termina o script atual

Descrição

void exit ( [string status])

void exit ( int status)

Nota: Esta não é uma função real, mas uma construção da linguagem.

A função exit() termina a execução do script. Ela mostra o parâmetro status justamente antes de sair.

Se status é um integer, este valor será usado como estado se saída. Estados de saída deve, estar no intervalo de 1 a 254, o estado de saída 255 é reservado pelo php e não deve ser usado.

Nota: A versão atual do CVS NÃO mostra status se for um integer.

Nota: A função die() é um apelido para a função exit().

Exemplo 1. Exemplo exit()

<?php

$filename = '/caminho/para/arquivo';
$file = fopen ($filename, 'r')
    or exit("Não pude abrir o arquivo ($filename)");

?>

get_browser

(PHP 3, PHP 4 )

get_browser --  Diz o que o browser do usuário pode fazer

Descrição

object get_browser ( [string user_agent])

get_browser() tenta determinar as capacidades do browser do usuário. Isto é feito procurando a informação do browser no arquivo browscap.ini. Por padrão, o valor de $HTTP_USER_AGENT é usado; em qualquer caso você pode alterar isto (ex., procurar informação de outro browser) passando o parâmetro opcional user_agent para a função get_browser().

A informação é retornada como um objeto, que contém vários elementos com dados representando, por exemplo, os números de versão maior e menor, a string de ID, valores TRUE/false para coisas como frames, JavaScript, e cookies; e assim em diante.

Enquanto browscap.ini contém informações sobre vários browser, ele precisa de atualizações para manter o banco de dados atual. O formato do arquivo é auto-explicatório.

O exemplo a seguir irá mostrar uma possível lista de toda a informação disponível sobre o browser do usuário.

Exemplo 1. Exemplo get_browser()

<?php
function list_array ($array) {
    while (list ($key, $value) = each ($array)) {
    $str .= "<b>$key:</b> $value<br />\n";
    }
    return $str;
}
echo "$HTTP_USER_AGENT<hr />\n";
$browser = get_browser();
echo list_array ((array) $browser);
?>

A saída do script acima deve ser algo como isto:

Mozilla/4.5 [en] (X11; U; Linux 2.2.9 i586)<hr />
<b>browser_name_pattern:</b> Mozilla/4\.5.*<br />
<b>parent:</b> Netscape 4.0<br />
<b>platform:</b> Unknown<br />
<b>majorver:</b> 4<br />
<b>minorver:</b> 5<br />
<b>browser:</b> Netscape<br />
<b>version:</b> 4<br />
<b>frames:</b> 1<br />
<b>tables:</b> 1<br />
<b>cookies:</b> 1<br />
<b>backgroundsounds:</b> <br />
<b>vbscript:</b> <br />
<b>javascript:</b> 1<br />
<b>javaapplets:</b> 1<br />
<b>activexcontrols:</b> <br />
<b>beta:</b> <br />
<b>crawler:</b> <br />
<b>authenticodeupdate:</b> <br />
<b>msn:</b> <br />

In order for this to work, your browscap configuration file setting must point to the correct location of the browscap.ini file.

For more information (including locations from which you may obtain a browscap.ini file), check the PHP FAQ at http://www.php.net/FAQ.php.

highlight_file

(PHP 4 )

highlight_file -- Destaca a sintaxe de um arquivo

Descrição

mixed highlight_file ( string filename [, bool return])

A função highlight_file() mostra uma versão do código contido em filename com a sintaxe destacada usando as cores definidas pelo destacador de sintaxe do PHP.

Se o segundo parâmetro return for TRUE então highlight_file() irá retornar o código como uma string ao invés de mostrá-lo. Se o segundo parâmetro não for TRUE então highlight_file() irá retornar TRUE se funcionar, FALSE em caso de falha.

Nota: O parâmetro return tornou-se disponível no PHP 4.2.0. Antes disso é usado como o padrão, que é FALSE.

Nota: Deve se tomar cuidado quando usar as funções show_source() e highlight_file() para ter certeza que você não irá inadvertidamente revelar informações sensíveis como senhas ou outros tipos de informação que possam criar um risco de segurança em potencial.

Nota: Desde o PHP 4.2.1 esta função também é afetada por safe_mode e open_basedir.

Exemplo 1. Criando uma URL para destaque da sintaxe

Para configurar uma url que possa fazer o destaque da sintaxe de qualquer script que você passar para ela, nós iremos fazer uso da diretiva "ForceType" no Apache para gerar um bom modelo de URL, e usar a função highlight_file() para mostrar o código com uma boa aparência.

No seu httpd.conf você pode adicionar o seguinte:

<Location /source>
    ForceType application/x-httpd-php
</Location>

E então faça um arquivo chamado "source" e coloque-o no seu diretório raiz do servidor web.

<HTML>
<HEAD>
<TITLE>Mostrar Fonte</TITLE>
</HEAD>
<BODY BGCOLOR="white">
<?php
    $script = getenv ("PATH_TRANSLATED");
    if(!$script) {
    echo "<BR><B>ERRO: Necessário o nome do script</B><BR>";
    } else {
    if (ereg("(\.php|\.inc)$",$script)) {
    echo "<H1>Source of: $PATH_INFO</H1>\n<HR>\n";
    highlight_file($script);
    } else {
    echo "<H1>ERRO: Somente PHP ou script de inclusão(.inc) são permitidos</H1>"; 
    }
    }
    echo "<HR>Processado: ".date("Y/M/d H:i:s",time());
?>
</BODY>
</HTML>

Então você pode usar uma URL como a abaixo para mostrar uma versão colorida do script localizado em "/caminho/para/script.php" no seu site web.

http://your.server.com/source/caminnho/para/script.php

Veja também highlight_string(), show_source().

highlight_string

(PHP 4 )

highlight_string -- Destaque da sintaxe de uma string

Descrição

mixed highlight_string ( string str [, bool return])

A função highlight_string() mostra o destaque da sintaxe para o parâmetro str usando as cores definidas para o destacador de sintaxe do PHP.

Se o segundo parâmetro return for TRUE então a função highlight_string() irá retornar o código com a sintaxe destacada ao invés de mostrá-lo. Se o segundo parâmetro não for TRUE então highlight_string() irá retornar TRUE se funcionar, FALSE se ocorrer falha.

Nota: O parâmetro return tornou-se disponível no PHP 4.2.0. Antes disso é usado como o padrão, que é FALSE

Veja também highlight_file(), e show_source().

ignore_user_abort

(PHP 3>= 3.0.7, PHP 4 )

ignore_user_abort --  Estabelece se acontecerá o enceramento do script quando o usuário abortar a conexão

Descrição

int ignore_user_abort ( [int setting])

Esta função estabelece se quando o usuário desconectar deve acontecer o fim do script. Irá retornar o que foi estabelecido anteriormente e pode ser chamado sem argumentos para retornar o que esta estabelecido e não muda-lo. Veja a seção Connection Handling no capitulo Features para uma completa descrição do manuseio de conexões no PHP.

pack

(PHP 3, PHP 4 )

pack -- Pack data into binary string.

Description

string pack ( string format [, mixed args])

Pack given arguments into binary string according to format. Returns binary string containing data.

The idea to this function was taken from Perl and all formatting codes work the same as there, however, there are some formatting codes that are missing such as Perl's "u" format code. The format string consists of format codes followed by an optional repeater argument. The repeater argument can be either an integer value or * for repeating to the end of the input data. For a, A, h, H the repeat count specifies how many characters of one data argument are taken, for @ it is the absolute position where to put the next data, for everything else the repeat count specifies how many data arguments are consumed and packed into the resulting binary string. Currently implemented are

  • a NUL-padded string

  • A SPACE-padded string

  • h Hex string, low nibble first

  • H Hex string, high nibble first

  • c signed char

  • C unsigned char

  • s signed short (always 16 bit, machine byte order)

  • S unsigned short (always 16 bit, machine byte order)

  • n unsigned short (always 16 bit, big endian byte order)

  • v unsigned short (always 16 bit, little endian byte order)

  • i signed integer (machine dependent size and byte order)

  • I unsigned integer (machine dependent size and byte order)

  • l signed long (always 32 bit, machine byte order)

  • L unsigned long (always 32 bit, machine byte order)

  • N unsigned long (always 32 bit, big endian byte order)

  • V unsigned long (always 32 bit, little endian byte order)

  • f float (machine dependent size and representation)

  • d double (machine dependent size and representation)

  • x NUL byte

  • X Back up one byte

  • @ NUL-fill to absolute position

Exemplo 1. pack() format string

$binarydata = pack ("nvc*", 0x1234, 0x5678, 65, 66);

The resulting binary string will be 6 bytes long and contain the byte sequence 0x12, 0x34, 0x78, 0x56, 0x41, 0x42.

Note that the distinction between signed and unsigned values only affects the function unpack(), where as function pack() gives the same result for signed and unsigned format codes.

Also note that PHP internally stores integer values as signed values of a machine dependent size. If you give it an unsigned integer value too large to be stored that way it is converted to a float which often yields an undesired result.

show_source

(PHP 4 )

show_source -- Destaca a sintaxe de um arquivo

Descrição

bool show_source ( string filename [, bool return])

Esta função é um apelido para highlight_file(). Para maiores informações veja a documentação lá.

Veja também highlight_string() e highlight_file().

sleep

(PHP 3, PHP 4 )

sleep -- Atrasa a execução do script

Descrição

void sleep ( int seconds)

A função sleep() atrasa a execução do programa de acordo com a quantidade de segundos dados no parâmetro seconds.

Veja também usleep() e set_time_limit()

uniqid

(PHP 3, PHP 4 )

uniqid -- Gera um ID unico

Descrição

string uniqid ( string prefix [, bool lcg])

uniqid() retorna um identificador unico prefixado baseado no tempo atual em milionésimos de segundo. O Prefixo pode ser usado se você gera identificadores em vários servidores simultaneamente pode acontecer de gerar o identificador no mesmo milionésimo de segundo. Prefix pode ter até 114 caracteres.

Se o parâmetro lcg, que é opcional, for TRUE, uniqid() irá adicionar a entropia "LCG combinada" ao final do valor retornado, o que deve fazer o resultado mais unico.

Com o parâmetro prefix vazio, a string retornada terá 13 caracteres. Se o parâmetro lcg for TRUE, terá 23 caracteres.

Nota: O parâmetro lcg somente esta disponivel no PHP 4 e PHP 3.0.13 e posterior.

Se você precisa um identificador unico e pretende dar o seu identificador via rede(ex. cookies de seção), é recomendado que você use algo como

$token = md5(uniqid("")); // sem prefixo
$better_token = md5(uniqid(rand(),1)); // melhor, dificil de adivinhar

Isto irá criar um identificador de 32 caracteres(a 128 bit hex number) que é extremamente dificil de prever.

unpack

(PHP 3, PHP 4 )

unpack -- Unpack data from binary string

Description

array unpack ( string format, string data)

unpack() from binary string into array according to format. Returns array containing unpacked elements of binary string.

unpack() works slightly different from Perl as the unpacked data is stored in an associative array. To accomplish this you have to name the different format codes and separate them by a slash /.

Exemplo 1. unpack() format string

$array = unpack ("c2chars/nint", $binarydata);

The resulting array will contain the entries "chars1", "chars2" and "int".

For an explanation of the format codes see also: pack()

Note that PHP internally stores integral values as signed. If you unpack a large unsigned long and it is of the same size as PHP internally stored values the result will be a negative number even though unsigned unpacking was specified.

usleep

(PHP 3, PHP 4 )

usleep -- Atrasa a execução em milionésimos de segundo

Descrição

void usleep ( int micro_seconds)

A função usleep() atrasa a execução do programa para o número dado no parâmetro micro_seconds em milionésimos de segundo.

Veja também sleep() e set_time_limit().

Nota: Esta função não funciona em sistemas Windows.

LXI. mnoGoSearch Functions

Introdução

These functions allow you to access the mnoGoSearch (former UdmSearch) free search engine. mnoGoSearch is a full-featured search engine software for intranet and internet servers, distributed under the GNU license. mnoGoSearch has a number of unique features, which makes it appropriate for a wide range of applications from search within your site to a specialized search system such as cooking recipes or newspaper search, FTP archive search, news articles search, etc. It offers full-text indexing and searching for HTML, PDF, and text documents. mnoGoSearch consists of two parts. The first is an indexing mechanism (indexer). The purpose of the indexer is to walk through HTTP, FTP, NEWS servers or local files, recursively grabbing all the documents and storing meta-data about that documents in a SQL database in a smart and effective manner. After every document is referenced by its corresponding URL, meta-data is collected by the indexer for later use in a search process. The search is performed via Web interface. C, CGI, PHP and Perl search front ends are included.

More information about mnoGoSearch can be found at http://www.mnogosearch.ru/.

Nota: This extension is not available on Windows platforms.


Requisitos

Download mnoGosearch from http://www.mnogosearch.ru/ and install it on your system. You need at least version 3.1.10 of mnoGoSearch installed to use these functions.


Instalação

In order to have these functions available, you must compile PHP with mnoGosearch support by using the --with-mnogosearchoption. If you use this option without specifying the path to mnoGosearch, PHP will look for mnoGosearch under /usr/local/mnogosearch path by default. If you installed mnoGosearch at a different location you should specify it: --with-mnogosearch=DIR.

Nota: PHP contains built-in MySQL access library, which can be used to access MySQL. It is known that mnoGoSearch is not compatible with this built-in library and can work only with generic MySQL libraries. Thus, if you use mnoGoSearch with MySQL, during PHP configuration you have to indicate the directory of your MySQL installation, that was used during mnoGoSearch configuration, i.e. for example: --with-mnogosearch --with-mysql=/usr.


Configuração durante execução

Esta extenção não define nenhum parâmetro de configuração no php.ini.


Tipos Resource


Constantes Predefinidas

As contantes abaixo são definidas por esta extensão e somente estarão disponíveis quando a extensão foi compilada com o PHP ou carregada dinamicamente durante a execução.

UDM_FIELD_URLID (integer)

UDM_FIELD_URL (integer)

UDM_FIELD_CONTENT (integer)

UDM_FIELD_TITLE (integer)

UDM_FIELD_KEYWORDS (integer)

UDM_FIELD_DESC (integer)

UDM_FIELD_DESCRIPTION (integer)

UDM_FIELD_TEXT (integer)

UDM_FIELD_SIZE (integer)

UDM_FIELD_RATING (integer)

UDM_FIELD_SCORE (integer)

UDM_FIELD_MODIFIED (integer)

UDM_FIELD_ORDER (integer)

UDM_FIELD_CRC (integer)

UDM_FIELD_CATEGORY (integer)

UDM_FIELD_LANG (integer)

UDM_FIELD_CHARSET (integer)

UDM_PARAM_PAGE_SIZE (integer)

UDM_PARAM_PAGE_NUM (integer)

UDM_PARAM_SEARCH_MODE (integer)

UDM_PARAM_CACHE_MODE (integer)

UDM_PARAM_TRACK_MODE (integer)

UDM_PARAM_PHRASE_MODE (integer)

UDM_PARAM_CHARSET (integer)

UDM_PARAM_LOCAL_CHARSET (integer)

UDM_PARAM_BROWSER_CHARSET (integer)

UDM_PARAM_STOPTABLE (integer)

UDM_PARAM_STOP_TABLE (integer)

UDM_PARAM_STOPFILE (integer)

UDM_PARAM_STOP_FILE (integer)

UDM_PARAM_WEIGHT_FACTOR (integer)

UDM_PARAM_WORD_MATCH (integer)

UDM_PARAM_MAX_WORD_LEN (integer)

UDM_PARAM_MAX_WORDLEN (integer)

UDM_PARAM_MIN_WORD_LEN (integer)

UDM_PARAM_MIN_WORDLEN (integer)

UDM_PARAM_ISPELL_PREFIXES (integer)

UDM_PARAM_ISPELL_PREFIX (integer)

UDM_PARAM_PREFIXES (integer)

UDM_PARAM_PREFIX (integer)

UDM_PARAM_CROSS_WORDS (integer)

UDM_PARAM_CROSSWORDS (integer)

UDM_PARAM_VARDIR (integer)

UDM_PARAM_DATADIR (integer)

UDM_PARAM_HLBEG (integer)

UDM_PARAM_HLEND (integer)

UDM_PARAM_SYNONYM (integer)

UDM_PARAM_SEARCHD (integer)

UDM_PARAM_QSTRING (integer)

UDM_PARAM_REMOTE_ADDR (integer)

UDM_LIMIT_CAT (integer)

UDM_LIMIT_URL (integer)

UDM_LIMIT_TAG (integer)

UDM_LIMIT_LANG (integer)

UDM_LIMIT_DATE (integer)

UDM_PARAM_FOUND (integer)

UDM_PARAM_NUM_ROWS (integer)

UDM_PARAM_WORDINFO (integer)

UDM_PARAM_WORD_INFO (integer)

UDM_PARAM_SEARCHTIME (integer)

UDM_PARAM_SEARCH_TIME (integer)

UDM_PARAM_FIRST_DOC (integer)

UDM_PARAM_LAST_DOC (integer)

UDM_MODE_ALL (integer)

UDM_MODE_ANY (integer)

UDM_MODE_BOOL (integer)

UDM_MODE_PHRASE (integer)

UDM_CACHE_ENABLED (integer)

UDM_CACHE_DISABLED (integer)

UDM_TRACK_ENABLED (integer)

UDM_TRACK_DISABLED (integer)

UDM_PHRASE_ENABLED (integer)

UDM_PHRASE_DISABLED (integer)

UDM_CROSS_WORDS_ENABLED (integer)

UDM_CROSSWORDS_ENABLED (integer)

UDM_CROSS_WORDS_DISABLED (integer)

UDM_CROSSWORDS_DISABLED (integer)

UDM_PREFIXES_ENABLED (integer)

UDM_PREFIX_ENABLED (integer)

UDM_ISPELL_PREFIXES_ENABLED (integer)

UDM_ISPELL_PREFIX_ENABLED (integer)

UDM_PREFIXES_DISABLED (integer)

UDM_PREFIX_DISABLED (integer)

UDM_ISPELL_PREFIXES_DISABLED (integer)

UDM_ISPELL_PREFIX_DISABLED (integer)

UDM_ISPELL_TYPE_AFFIX (integer)

UDM_ISPELL_TYPE_SPELL (integer)

UDM_ISPELL_TYPE_DB (integer)

UDM_ISPELL_TYPE_SERVER (integer)

UDM_MATCH_WORD (integer)

UDM_MATCH_BEGIN (integer)

UDM_MATCH_SUBSTR (integer)

UDM_MATCH_END (integer)

Índice
udm_add_search_limit -- Add various search limits
udm_alloc_agent -- Allocate mnoGoSearch session
udm_api_version -- Get mnoGoSearch API version.
udm_cat_list -- Get all the categories on the same level with the current one.
udm_cat_path -- Get the path to the current category.
udm_check_charset --  Check if the given charset is known to mnogosearch
udm_check_stored --  Check connection to stored
udm_clear_search_limits -- Clear all mnoGoSearch search restrictions
udm_close_stored --  Close connection to stored
udm_crc32 --  Return CRC32 checksum of gived string
udm_errno -- Get mnoGoSearch error number
udm_error -- Get mnoGoSearch error message
udm_find -- Perform search
udm_free_agent -- Free mnoGoSearch session
udm_free_ispell_data -- Free memory allocated for ispell data
udm_free_res -- Free mnoGoSearch result
udm_get_doc_count -- Get total number of documents in database.
udm_get_res_field -- Fetch mnoGoSearch result field
udm_get_res_param -- Get mnoGoSearch result parameters
udm_load_ispell_data -- Load ispell data
udm_open_stored --  Open connection to stored
udm_set_agent_param -- Set mnoGoSearch agent session parameters

udm_add_search_limit

(PHP 4 >= 4.0.5)

udm_add_search_limit -- Add various search limits

Description

int udm_add_search_limit ( int agent, int var, string val)

udm_add_search_limit() returns TRUE on success, FALSE on error. Adds search restrictions.

agent - a link to Agent, received after call to udm_alloc_agent().

var - defines parameter, indicating limit.

val - defines value of the current parameter.

Possible var values:

  • UDM_LIMIT_URL - defines document URL limitations to limit search through subsection of database. It supports SQL % and _ LIKE wildcards, where % matches any number of characters, even zero characters, and _ matches exactly one character. E.g. http://my.domain.__/catalog may stand for http://my.domain.ru/catalog and http://my.domain.ua/catalog.

  • UDM_LIMIT_TAG - defines site TAG limitations. In indexer-conf you can assign specific TAGs to various sites and parts of a site. Tags in mnoGoSearch 3.1.x are lines, that may contain metasymbols % and _. Metasymbols allow searching among groups of tags. E.g. there are links with tags ABCD and ABCE, and search restriction is by ABC_ - the search will be made among both of the tags.

  • UDM_LIMIT_LANG - defines document language limitations.

  • UDM_LIMIT_CAT - defines document category limitations. Categories are similar to tag feature, but nested. So you can have one category inside another and so on. You have to use two characters for each level. Use a hex number going from 0-F or a 36 base number going from 0-Z. Therefore a top-level category like 'Auto' would be 01. If it has a subcategory like 'Ford', then it would be 01 (the parent category) and then 'Ford' which we will give 01. Put those together and you get 0101. If 'Auto' had another subcategory named 'VW', then it's id would be 01 because it belongs to the 'Ford' category and then 02 because it's the next category. So it's id would be 0102. If VW had a sub category called 'Engine' then it's id would start at 01 again and it would get the 'VW' id 02 and 'Auto' id of 01, making it 010201. If you want to search for sites under that category then you pass it cat=010201 in the url.

  • UDM_LIMIT_DATE - defines limitation by date document was modified.

    Format of parameter value: a string with first character < or >, then with no space - date in unixtime format, for example:

    Udm_Add_Search_Limit($udm,UDM_LIMIT_DATE,"<908012006");

    If > character is used, then search will be restricted to those documents having modification date greater than entered. If <, then smaller.

udm_alloc_agent

(PHP 4 >= 4.0.5)

udm_alloc_agent -- Allocate mnoGoSearch session

Description

int udm_alloc_agent ( string dbaddr [, string dbmode])

udm_alloc_agent() returns mnogosearch agent identifier on success, FALSE on error. This function creates a session with database parameters.

dbaddr - URL-style database description. Options (type, host, database name, port, user and password) to connect to SQL database. Do not matter for built-in text files support. Format: DBAddr DBType:[//[DBUser[:DBPass]@]DBHost[:DBPort]]/DBName/ Currently supported DBType values are: mysql, pgsql, msql, solid, mssql, oracle, ibase. Actually, it does not matter for native libraries support. But ODBC users should specify one of supported values. If your database type is not supported, you may use "unknown" instead.

dbmode - You may select SQL database mode of words storage. When "single" is specified, all words are stored in the same table. If "multi" is selected, words will be located in different tables depending of their lengths. "multi" mode is usually faster but requires more tables in database. If "crc" mode is selected, mnoGoSearch will store 32 bit integer word IDs calculated by CRC32 algorythm instead of words. This mode requres less disk space and it is faster comparing with "single" and "multi" modes. "crc-multi" uses the same storage structure with the "crc" mode, but also stores words in different tables depending on words lengths like "multi" mode. Format: DBMode single/multi/crc/crc-multi

Nota: dbaddr and dbmode must match those used during indexing.

Nota: In fact this function does not open connection to database and thus does not check entered login and password. Actual connection to database and login/password verification is done by udm_find().

udm_api_version

(PHP 4 >= 4.0.5)

udm_api_version -- Get mnoGoSearch API version.

Description

int udm_api_version ( void)

udm_api_version() returns mnoGoSearch API version number. E.g. if mnoGoSearch 3.1.10 API is used, this function will return 30110.

This function allows user to identify which API functions are available, e.g. udm_get_doc_count() function is only available in mnoGoSearch 3.1.11 or later.

Example:

if (udm_api_version() >= 30111) {
   print  "Total number of urls in database: ".udm_get_doc_count($udm)."<br>\n";
   }

udm_cat_list

(PHP 4 >= 4.0.6)

udm_cat_list -- Get all the categories on the same level with the current one.

Description

array udm_cat_list ( int agent, string category)

udm_cat_list() returns array listing all categories of the same level as current category in the categories tree.

The function can be useful for developing categories tree browser.

Returns array with the following format:

The array consists of pairs. Elements with even index numbers contain category paths, odd elements contain corresponding category names.



  $array[0] will contain '020300'
  $array[1] will contain 'Audi'
  $array[2] will contain '020301'
  $array[3] will contain 'BMW'
  $array[4] will contain '020302'
  $array[5] will contain 'Opel'
  ...
 etc.

   


Following is an example of displaying links of the current level in format:
  Audi
  BMW
  Opel
  ...
   

<?php
 $cat_list_arr = udm_cat_list($udm_agent,$cat);
 $cat_list = '';
 for ($i=0; $i<count($cat_list_arr); $i+=2) {
   $path = $cat_list_arr[$i];
   $name = $cat_list_arr[$i+1];
   $cat_list .= "<a href=\"$PHP_SELF?cat=$path\">$name</a><br>";
 }
?>

udm_cat_path

(PHP 4 >= 4.0.6)

udm_cat_path -- Get the path to the current category.

Description

array udm_cat_path ( int agent, string category)

udm_cat_path() returns array describing path in the categories tree from the tree root to the current category.

agent - agent link identifier.

category - current category - the one to get path to.

Returns array with the following format:

The array consists of pairs. Elements with even index numbers contain category paths, odd elements contain corresponding category names.

For example, the call $array=udm_cat_path($agent, '02031D'); may return the following array:



 $array[0] will contain ''
 $array[1] will contain 'Root'
 $array[2] will contain '02'
 $array[3] will contain 'Sport'
 $array[4] will contain '0203'
 $array[5] will contain 'Auto'
 $array[4] will contain '02031D'
 $array[5] will contain 'Ferrari'

   

Exemplo 1. Specifying path to the current category in the following format: '> Root > Sport > Auto > Ferrari'

<?php
  $cat_path_arr = udm_cat_path($udm_agent,$cat);
  $cat_path = '';
  for ($i=0; $i<count($cat_path_arr); $i+=2) {
    $path = $cat_path_arr[$i];
    $name = $cat_path_arr[$i+1];
    $cat_path .= " > <a href=\"$PHP_SELF?cat=$path\">$name</a> ";
  }
?>

udm_check_charset

(PHP 4 >= 4.2.0)

udm_check_charset --  Check if the given charset is known to mnogosearch

Description

int udm_check_charset ( int agent, string charset)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

udm_check_stored

(PHP 4 >= 4.2.0)

udm_check_stored --  Check connection to stored

Description

int udm_check_stored ( int agent, int link, string doc_id)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

udm_clear_search_limits

(PHP 4 >= 4.0.5)

udm_clear_search_limits -- Clear all mnoGoSearch search restrictions

Description

int udm_clear_search_limits ( int agent)

udm_clear_search_limits() resets defined search limitations and returns TRUE.

udm_close_stored

(PHP 4 >= 4.2.0)

udm_close_stored --  Close connection to stored

Description

int udm_close_stored ( int agent, int link)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

udm_crc32

(PHP 4 >= 4.2.0)

udm_crc32 --  Return CRC32 checksum of gived string

Description

int udm_crc32 ( int agent, string str)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

udm_errno

(PHP 4 >= 4.0.5)

udm_errno -- Get mnoGoSearch error number

Description

int udm_errno ( int agent)

udm_errno() returns mnoGoSearch error number, zero if no error.

agent - link to agent identifier, received after call to udm_alloc_agent().

Receiving numeric agent error code.

udm_error

(PHP 4 >= 4.0.5)

udm_error -- Get mnoGoSearch error message

Description

string udm_error ( int agent)

udm_error() returns mnoGoSearch error message, empty string if no error.

agent - link to agent identifier, received after call to udm_alloc_agent().

Receiving agent error message.

udm_find

(PHP 4 >= 4.0.5)

udm_find -- Perform search

Description

int udm_find ( int agent, string query)

udm_find() returns result link identifier on success, FALSE on error.

The search itself. The first argument - session, the next one - query itself. To find something just type words you want to find and press SUBMIT button. For example, "mysql odbc". You should not use quotes " in query, they are written here only to divide a query from other text. mnoGoSearch will find all documents that contain word "mysql" and/or word "odbc". Best documents having bigger weights will be displayed first. If you use search mode ALL, search will return documents that contain both (or more) words you entered. In case you use mode ANY, the search will return list of documents that contain any of the words you entered. If you want more advanced results you may use query language. You should select "bool" match mode in the search from.

mnoGoSearch understands the following boolean operators:

& - logical AND. For example, "mysql & odbc". mnoGoSearch will find any URLs that contain both "mysql" and "odbc".

| - logical OR. For example "mysql|odbc". mnoGoSearch will find any URLs, that contain word "mysql" or word "odbc".

~ - logical NOT. For example "mysql & ~odbc". mnoGoSearch will find URLs that contain word "mysql" and do not contain word "odbc" at the same time. Note that ~ just excludes given word from results. Query "~odbc" will find nothing!

() - group command to compose more complex queries. For example "(mysql | msql) & ~postgres". Query language is simple and powerful at the same time. Just consider query as usual boolean expression.

udm_free_agent

(PHP 4 >= 4.0.5)

udm_free_agent -- Free mnoGoSearch session

Description

int udm_free_agent ( int agent)

udm_free_agent() returns TRUE on success, FALSE on error.

agent - link to agent identifier, received ` after call to udm_alloc_agent().

Freeing up memory allocated for agent session.

udm_free_ispell_data

(PHP 4 >= 4.0.5)

udm_free_ispell_data -- Free memory allocated for ispell data

Description

int udm_free_ispell_data ( int agent)

udm_free_ispell_data() always returns TRUE.

agent - agent link identifier, received after call to udm_alloc_agent().

Nota: This function is supported beginning from version 3.1.12 of mnoGoSearch and it does not do anything in previous versions.

udm_free_res

(PHP 4 >= 4.0.5)

udm_free_res -- Free mnoGoSearch result

Description

int udm_free_res ( int res)

udm_free_res() returns TRUE on success, FALSE on error.

res - a link to result identifier, received after call to udm_find().

Freeing up memory allocated for results.

udm_get_doc_count

(PHP 4 >= 4.0.5)

udm_get_doc_count -- Get total number of documents in database.

Description

int udm_get_doc_count ( int agent)

udm_get_doc_count() returns number of documents in database.

agent - link to agent identifier, received after call to udm_alloc_agent().

Nota: This function is supported only in mnoGoSearch 3.1.11 or later.

udm_get_res_field

(PHP 4 >= 4.0.5)

udm_get_res_field -- Fetch mnoGoSearch result field

Description

string udm_get_res_field ( int res, int row, int field)

udm_get_res_field() returns result field value on success, FALSE on error.

res - a link to result identifier, received after call to udm_find().

row - the number of the link on the current page. May have values from 0 to UDM_PARAM_NUM_ROWS-1.

field - field identifier, may have the following values:

  • UDM_FIELD_URL - document URL field

  • UDM_FIELD_CONTENT - document Content-type field (for example, text/html).

  • UDM_FIELD_CATEGORY - document category field. Use udm_cat_path() to get full path to current category from the categories tree root. (This parameter is available only in PHP 4.0.6 or later).

  • UDM_FIELD_TITLE - document title field.

  • UDM_FIELD_KEYWORDS - document keywords field (from META KEYWORDS tag).

  • UDM_FIELD_DESC - document description field (from META DESCRIPTION tag).

  • UDM_FIELD_TEXT - document body text (the first couple of lines to give an idea of what the document is about).

  • UDM_FIELD_SIZE - document size.

  • UDM_FIELD_URLID - unique URL ID of the link.

  • UDM_FIELD_RATING - page rating (as calculated by mnoGoSearch).

  • UDM_FIELD_MODIFIED - last-modified field in unixtime format.

  • UDM_FIELD_ORDER - the number of the current document in set of found documents.

  • UDM_FIELD_CRC - document CRC.

udm_get_res_param

(PHP 4 >= 4.0.5)

udm_get_res_param -- Get mnoGoSearch result parameters

Description

string udm_get_res_param ( int res, int param)

udm_get_res_param() returns result parameter value on success, FALSE on error.

res - a link to result identifier, received after call to udm_find().

param - parameter identifier, may have the following values:

  • UDM_PARAM_NUM_ROWS - number of received found links on the current page. It is equal to UDM_PARAM_PAGE_SIZE for all search pages, on the last page - the rest of links.

  • UDM_PARAM_FOUND - total number of results matching the query.

  • UDM_PARAM_WORDINFO - information on the words found. E.g. search for "a good book" will return "a: stopword, good:5637, book: 120"

  • UDM_PARAM_SEARCHTIME - search time in seconds.

  • UDM_PARAM_FIRST_DOC - the number of the first document displayed on current page.

  • UDM_PARAM_LAST_DOC - the number of the last document displayed on current page.

udm_load_ispell_data

(PHP 4 >= 4.0.5)

udm_load_ispell_data -- Load ispell data

Description

int udm_load_ispell_data ( int agent, int var, string val1, string val2, int flag)

udm_load_ispell_data() loads ispell data. Returns TRUE on success, FALSE on error.

agent - agent link identifier, received after call to udm_alloc_agent().

var - parameter, indicating the source for ispell data. May have the following values:

After using this function to free memory allocated for ispell data, please use udm_free_ispell_data(), even if you use UDM_ISPELL_TYPE_SERVER mode.

The fastest mode is UDM_ISPELL_TYPE_SERVER. UDM_ISPELL_TYPE_TEXT is slower and UDM_ISPELL_TYPE_DB is the slowest. The above pattern is TRUE for mnoGoSearch 3.1.10 - 3.1.11. It is planned to speed up DB mode in future versions and it is going to be faster than TEXT mode.

  • UDM_ISPELL_TYPE_DB - indicates that ispell data should be loaded from SQL. In this case, parameters val1 and val2 are ignored and should be left blank. flag should be equal to 1.

    Nota: flag indicates that after loading ispell data from defined source it sould be sorted (it is necessary for correct functioning of ispell). In case of loading ispell data from files there may be several calls to udm_load_ispell_data(), and there is no sense to sort data after every call, but only after the last one. Since in db mode all the data is loaded by one call, this parameter should have the value 1. In this mode in case of error, e.g. if ispell tables are absent, the function will return FALSE and code and error message will be accessible through udm_error() and udm_errno().

    Example:

    if (! udm_load_ispell_data($udm,UDM_ISPELL_TYPE_DB,'','',1)) {
      printf("Error #%d: '%s'\n", udm_errno($udm), udm_error($udm));
      exit;
    }

  • UDM_ISPELL_TYPE_AFFIX - indicates that ispell data should be loaded from file and initiates loading affixes file. In this case val1 defines double letter language code for which affixes are loaded, and val2 - file path. Please note, that if a relative path entered, the module looks for the file not in UDM_CONF_DIR, but in relation to current path, i.e. to the path where the script is executed. In case of error in this mode, e.g. if file is absent, the function will return FALSE, and an error message will be displayed. Error message text cannot be accessed through udm_error() and udm_errno(), since those functions can only return messages associated with SQL. Please, see flag parameter description in UDM_ISPELL_TYPE_DB.

    Example:

    if ((! udm_load_ispell_data($udm,UDM_ISPELL_TYPE_AFFIX,'en','/opt/ispell/en.aff',0)) ||
            (! udm_load_ispell_data($udm,UDM_ISPELL_TYPE_AFFIX,'ru','/opt/ispell/ru.aff',0)) ||
            (! udm_load_ispell_data($udm,UDM_ISPELL_TYPE_SPELL,'en','/opt/ispell/en.dict',0)) ||
            (! udm_load_ispell_data($udm,UDM_ISPELL_TYPE_SPELL,'ru','/opt/ispell/ru.dict',1))) {
         exit;
         }

    Nota: flag is equal to 1 only in the last call.

  • UDM_ISPELL_TYPE_SPELL - indicates that ispell data should be loaded from file and initiates loading of ispell dictionary file. In this case val1 defines double letter language code for which affixes are loaded, and val2 - file path. Please note, that if a relative path entered, the module looks for the file not in UDM_CONF_DIR, but in relation to current path, i.e. to the path where the script is executed. In case of error in this mode, e.g. if file is absent, the function will return FALSE, and an error message will be displayed. Error message text cannot be accessed through udm_error() and udm_errno(), since those functions can only return messages associated with SQL. Please, see flag parameter description in UDM_ISPELL_TYPE_DB.

    if ((! Udm_Load_Ispell_Data($udm,UDM_ISPELL_TYPE_AFFIX,'en','/opt/ispell/en.aff',0)) ||
            (! Udm_Load_Ispell_Data($udm,UDM_ISPELL_TYPE_AFFIX,'ru','/opt/ispell/ru.aff',0)) ||
            (! Udm_Load_Ispell_Data($udm,UDM_ISPELL_TYPE_SPELL,'en','/opt/ispell/en.dict',0)) ||
            (! Udm_Load_Ispell_Data($udm,UDM_ISPELL_TYPE_SPELL,'ru','/opt/ispell/ru.dict',1))) {
          exit;
          }

    Nota: flag is equal to 1 only in the last call.

  • UDM_ISPELL_TYPE_SERVER - enables spell server support. val1 parameter indicates address of the host running spell server. val2 ` is not used yet, but in future releases it is going to indicate number of port used by spell server. flag parameter in this case is not needed since ispell data is stored on spellserver already sorted.

    Spelld server reads spell-data from a separate configuration file (/usr/local/mnogosearch/etc/spelld.conf by default), sorts it and stores in memory. With clients server communicates in two ways: to indexer all the data is transferred (so that indexer starts faster), from search.cgi server receives word to normalize and then passes over to client (search.cgi) list of normalized word forms. This allows fastest, compared to db and text modes processing of search queries (by omitting loading and sorting all the spell data).

    udm_load_ispell_data() function in UDM_ISPELL_TYPE_SERVER mode does not actually load ispell data, but only defines server address. In fact, server is automatically used by udm_find() function when performing search. In case of errors, e.g. if spellserver is not running or invalid host indicated, there are no messages returned and ispell conversion does not work.

    Nota: This function is available in mnoGoSearch 3.1.12 or later.

    Example:

    if (!udm_load_ispell_data($udm,UDM_ISPELL_TYPE_SERVER,'','',1)) {
        printf("Error loading ispell data from server<br>\n");
        exit;
    }

udm_open_stored

(PHP 4 >= 4.2.0)

udm_open_stored --  Open connection to stored

Description

int udm_open_stored ( int agent, string storedaddr)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

udm_set_agent_param

(PHP 4 >= 4.0.5)

udm_set_agent_param -- Set mnoGoSearch agent session parameters

Description

int udm_set_agent_param ( int agent, int var, string val)

udm_set_agent_param() returns TRUE on success, FALSE on error. Defines mnoGoSearch session parameters.

The following parameters and their values are available:

  • UDM_PARAM_PAGE_NUM - used to choose search results page number (results are returned by pages beginning from 0, with UDM_PARAM_PAGE_SIZE results per page).

  • UDM_PARAM_PAGE_SIZE - number of search results displayed on one page.

  • UDM_PARAM_SEARCH_MODE - search mode. The following values available: UDM_MODE_ALL - search for all words; UDM_MODE_ANY - search for any word; UDM_MODE_PHRASE - phrase search; UDM_MODE_BOOL - boolean search. See udm_find() for details on boolean search.

  • UDM_PARAM_CACHE_MODE - turns on or off search result cache mode. When enabled, the search engine will store search results to disk. In case a similar search is performed later, the engine will take results from the cache for faster performance. Available values: UDM_CACHE_ENABLED, UDM_CACHE_DISABLED.

  • UDM_PARAM_TRACK_MODE - turns on or off trackquery mode. Since version 3.1.2 mnoGoSearch has a query tracking support. Note that tracking is implemented in SQL version only and not available in built-in database. To use tracking, you have to create tables for tracking support. For MySQL, use create/mysql/track.txt. When doing a search, front-end uses those tables to store query words, a number of found documents and current UNIX timestamp in seconds. Available values: UDM_TRACK_ENABLED, UDM_TRACK_DISABLED.

  • UDM_PARAM_PHRASE_MODE - defines whether index database using phrases ("phrase" parameter in indexer.conf). Possible values: UDM_PHRASE_ENABLED and UDM_PHRASE_DISABLED. Please note, that if phrase search is enabled (UDM_PHRASE_ENABLED), it is still possible to do search in any mode (ANY, ALL, BOOL or PHRASE). In 3.1.10 version of mnoGoSearch phrase search is supported only in sql and built-in database modes, while beginning with 3.1.11 phrases are supported in cachemode as well.

    Examples of phrase search:

    "Arizona desert" - This query returns all indexed documents that contain "Arizona desert" as a phrase. Notice that you need to put double quotes around the phrase

  • UDM_PARAM_CHARSET - defines local charset. Available values: set of charsets supported by mnoGoSearch, e.g. koi8-r, cp1251, ...

  • UDM_PARAM_STOPFILE - Defines name and path to stopwords file. (There is a small difference with mnoGoSearch - while in mnoGoSearch if relative path or no path entered, it looks for this file in relation to UDM_CONF_DIR, the module looks for the file in relation to current path, i.e. to the path where the php script is executed.)

  • UDM_PARAM_STOPTABLE - Load stop words from the given SQL table. You may use several StopwordTable commands. This command has no effect when compiled without SQL database support.

  • UDM_PARAM_WEIGHT_FACTOR - represents weight factors for specific document parts. Currently body, title, keywords, description, url are supported. To activate this feature please use degrees of 2 in *Weight commands of the indexer.conf. Let's imagine that we have these weights:


      URLWeight     1
      BodyWeight    2
      TitleWeight   4
      KeywordWeight 8
      DescWeight    16
         

    As far as indexer uses bit OR operation for word weights when some word presents several time in the same document, it is possible at search time to detect word appearance in different document parts. Word which appears only in the body will have 00000010 argegate weight (in binary notation). Word used in all document parts will have 00011111 aggregate weight.

    This parameter's value is a string of hex digits ABCDE. Each digit is a factor for corresponding bit in word weight. For the given above weights configuration:


       E is a factor for weight 1  (URL Weight bit)
       D is a factor for weight 2  (BodyWeight bit)
       C is a factor for weight 4  (TitleWeight bit)
       B is a factor for weight 8  (KeywordWeight bit)
       A is a factor for weight 16 (DescWeight bit)
         

    Examples:

    UDM_PARAM_WEIGHT_FACTOR=00001 will search through URLs only.

    UDM_PARAM_WEIGHT_FACTOR=00100 will search through Titles only.

    UDM_PARAM_WEIGHT_FACTOR=11100 will search through Title,Keywords,Description but not through URL and Body.

    UDM_PARAM_WEIGHT_FACTOR=F9421 will search through:


        Description with factor 15  (F hex)
        Keywords with factor 9
        Title with factor  4
        Body with factor 2
        URL with factor 1
         

    If UDM_PARAM_WEIGHT_FACTOR variable is ommited, original weight value is taken to sort results. For a given above weight configuration it means that document description has a most big weight 16.

  • UDM_PARAM_WORD_MATCH - word match. You may use this parameter to choose word match type. This feature works only in "single" and "multi" modes using SQL based and built-in database. It does not work in cachemode and other modes since they use word CRC and do not support substring search. Available values:

    UDM_MATCH_BEGIN - word beginning match;

    UDM_MATCH_END - word ending match;

    UDM_MATCH_WORD - whole word match;

    UDM_MATCH_SUBSTR - word substring match.

  • UDM_PARAM_MIN_WORD_LEN - defines minimal word length. Any word shorter this limit is considered to be a stopword. Please note that this parameter value is inclusive, i.e. if UDM_PARAM_MIN_WORD_LEN=3, a word 3 characters long will not be considered a stopword, while a word 2 characters long will be. Default value is 1.

  • UDM_PARAM_ISPELL_PREFIXES - Possible values: UDM_PREFIXES_ENABLED and UDM_PREFIXES_DISABLED, that respectively enable or disable using prefixes. E.g. if a word "tested" is in search query, also words like "test", "testing", etc. Only suffixes are supported by default. Prefixes usually change word meanings, for example if somebody is searching for the word "tested" one hardly wants "untested" to be found. Prefixes support may also be found useful for site's spelling checking purposes. In order to enable ispell, you have to load ispell data with udm_load_ispell_data().

  • UDM_PARAM_CROSS_WORDS - enables or disables crosswords support. Possible values: UDM_CROSS_WORDS_ENABLED and UDM_CROSS_WORDS_DISABLED.

    The corsswords feature allows to assign words between <a href="xxx"> and </a> also to a document this link leads to. It works in SQL database mode and is not supported in built-in database and Cachemode.

    Nota: Crosswords are supported only in mnoGoSearch 3.1.11 or later.

  • UDM_PARAM_VARDIR - specifies a custom path to directory where indexer stores data when using built-in database and in cache mode. By default /var directory of mnoGoSearch installation is used. Can have only string values. The parameter is available in PHP 4.1.0 or later.

  • UDM_PARAM_VARDIR - specifies a custom path to directory where indexer stores data when using built-in database and in cache mode. By default /var directory of mnoGoSearch installation is used. Can have only string values. The parameter is available in PHP 4.1.0 or later.

LXII. mSQL functions

Introdução

These functions allow you to access mSQL database servers. More information about mSQL can be found at http://www.hughes.com.au/.


Requisitos


Instalação

In order to have these functions available, you must compile PHP with msql support by using the --with-msql[=DIR] option. DIR is the mSQL base install directory, defaults to /usr/local/Hughes.

Note to Win32 Users: In order to enable this module on a Windows environment, you must copy msql.dll from the DLL folder of the PHP/Win32 binary package to the SYSTEM32 folder of your windows machine. (Ex: C:\WINNT\SYSTEM32 or C:\WINDOWS\SYSTEM32)


Configuração durante execução

O comportamento dessas funções podem ser modificado pelas configurações do php.ini.

Tabela 1. mSQL configuration options

Name Default Changeable
msql.allow_persistent "On" PHP_INI_SYSTEM
msql.max_persistent "-1" PHP_INI_SYSTEM
msql.max_links "-1" PHP_INI_SYSTEM
For further details and definition of the PHP_INI_* constants see ini_set().

Here is a short explanation of the configuration directives.

msql.allow_persistent boolean

Whether to allow persistent mSQL connections.

msql.max_persistent integer

The maximum number of persistent mSQL connections per process.

msql.max_links integer

The maximum number of mSQL connections per process, including persistent connections.


Tipos Resource


Constantes Predefinidas

As contantes abaixo são definidas por esta extensão e somente estarão disponíveis quando a extensão foi compilada com o PHP ou carregada dinamicamente durante a execução.

MSQL_ASSOC (integer)

MSQL_NUM (integer)

MSQL_BOTH (integer)

Índice
msql_affected_rows -- Returns number of affected rows
msql_close -- Close mSQL connection
msql_connect -- Open mSQL connection
msql_create_db -- Create mSQL database
msql_createdb -- Create mSQL database
msql_data_seek -- Move internal row pointer
msql_dbname -- Get current mSQL database name
msql_drop_db -- Drop (delete) mSQL database
msql_dropdb -- Drop (delete) mSQL database
msql_error -- Returns error message of last msql call
msql_fetch_array -- Fetch row as array
msql_fetch_field -- Get field information
msql_fetch_object -- Fetch row as object
msql_fetch_row -- Get row as enumerated array
msql_field_seek -- Set field offset
msql_fieldflags -- Get field flags
msql_fieldlen -- Get field length
msql_fieldname -- Get field name
msql_fieldtable -- Get table name for field
msql_fieldtype -- Get field type
msql_free_result -- Free result memory
msql_freeresult -- Free result memory
msql_list_dbs -- List mSQL databases on server
msql_list_fields -- List result fields
msql_list_tables -- List tables in an mSQL database
msql_listdbs -- List mSQL databases on server
msql_listfields -- List result fields
msql_listtables -- List tables in an mSQL database
msql_num_fields -- Get number of fields in result
msql_num_rows -- Get number of rows in result
msql_numfields -- Get number of fields in result
msql_numrows -- Get number of rows in result
msql_pconnect -- Open persistent mSQL connection
msql_query -- Send mSQL query
msql_regcase --  Make regular expression for case insensitive match
msql_result -- Get result data
msql_select_db -- Select mSQL database
msql_selectdb -- Select mSQL database
msql_tablename -- Get table name of field
msql -- Send mSQL query

msql_affected_rows

(PHP 3>= 3.0.6, PHP 4 )

msql_affected_rows -- Returns number of affected rows

Description

int msql_affected_rows ( int query_identifier)

Returns number of affected ("touched") rows by a specific query (i.e. the number of rows returned by a SELECT, the number of rows modified by an update, or the number of rows removed by a delete).

See also: msql_query().

msql_close

(PHP 3, PHP 4 )

msql_close -- Close mSQL connection

Description

int msql_close ( int link_identifier)

Returns TRUE on success, FALSE on error.

msql_close() closes the link to a mSQL database that's associated with the specified link identifier. If the link identifier isn't specified, the last opened link is assumed.

Note that this isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution.

msql_close() will not close persistent links generated by msql_pconnect().

See also: msql_connect() and msql_pconnect().

msql_connect

(PHP 3, PHP 4 )

msql_connect -- Open mSQL connection

Description

int msql_connect ( [string hostname [, string server [, string username [, string password]]]])

Returns a positive mSQL link identifier on success, or FALSE on error.

msql_connect() establishes a connection to a mSQL server. The server parameter can also include a port number. eg. "hostname:port". It defaults to 'localhost'.

In case a second call is made to msql_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned.

The link to the server will be closed as soon as the execution of the script ends, unless it's closed earlier by explicitly calling msql_close().

See also msql_pconnect(), msql_close().

msql_create_db

(PHP 3, PHP 4 )

msql_create_db -- Create mSQL database

Description

int msql_create_db ( string database name [, int link_identifier])

msql_create_db() attempts to create a new database on the server associated with the specified link identifier.

See also: msql_drop_db().

msql_createdb

(PHP 3, PHP 4 )

msql_createdb -- Create mSQL database

Description

int msql_createdb ( string database name [, int link_identifier])

Identical to msql_create_db().

msql_data_seek

(PHP 3, PHP 4 )

msql_data_seek -- Move internal row pointer

Description

int msql_data_seek ( int query_identifier, int row_number)

Retorna TRUE em caso de sucesso ou FALSE em falhas.

msql_data_seek() moves the internal row pointer of the mSQL result associated with the specified query identifier to point to the specifyed row number. The next call to msql_fetch_row() would return that row.

See also: msql_fetch_row().

msql_dbname

(PHP 3, PHP 4 )

msql_dbname -- Get current mSQL database name

Description

string msql_dbname ( int query_identifier, int i)

msql_dbname() returns the database name stored in position i of the result pointer returned from the msql_listdbs() function. The msql_numrows() function can be used to determine how many database names are available.

msql_drop_db

(PHP 3, PHP 4 )

msql_drop_db -- Drop (delete) mSQL database

Description

int msql_drop_db ( string database_name, int link_identifier)

Retorna TRUE em caso de sucesso ou FALSE em falhas.

msql_drop_db() attempts to drop (remove) an entire database from the server associated with the specified link identifier.

See also: msql_create_db().

msql_dropdb

msql_dropdb -- Drop (delete) mSQL database

Description

See msql_drop_db().

msql_error

(PHP 3, PHP 4 )

msql_error -- Returns error message of last msql call

Description

string msql_error ( [int link_identifier])

Errors coming back from the mSQL database backend no longer issue warnings. Instead, use these functions to retrieve the error string.

msql_fetch_array

(PHP 3, PHP 4 )

msql_fetch_array -- Fetch row as array

Description

int msql_fetch_array ( int query_identifier [, int result_type])

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

msql_fetch_array() is an extended version of msql_fetch_row(). In addition to storing the data in the numeric indices of the result array, it also stores the data in associative indices, using the field names as keys.

The second optional argument result_type in msql_fetch_array() is a constant and can take the following values: MSQL_ASSOC, MSQL_NUM, and MSQL_BOTH.

Be careful if you are retrieving results from a query that may return a record that contains only one field that has a value of 0 (or an empty string, or NULL).

An important thing to note is that using msql_fetch_array() is NOT significantly slower than using msql_fetch_row(), while it provides a significant added value.

For further details, also see msql_fetch_row().

msql_fetch_field

(PHP 3, PHP 4 )

msql_fetch_field -- Get field information

Description

object msql_fetch_field ( int query_identifier, int field_offset)

Returns an object containing field information

msql_fetch_field() can be used in order to obtain information about fields in a certain query result. If the field offset isn't specified, the next field that wasn't yet retreived by msql_fetch_field() is retreived.

The properties of the object are:

  • name - column name

  • table - name of the table the column belongs to

  • not_null - 1 if the column cannot be NULL

  • primary_key - 1 if the column is a primary key

  • unique - 1 if the column is a unique key

  • type - the type of the column

See also msql_field_seek().

msql_fetch_object

(PHP 3, PHP 4 )

msql_fetch_object -- Fetch row as object

Description

int msql_fetch_object ( int query_identifier [, int result_type])

Returns an object with properties that correspond to the fetched row, or FALSE if there are no more rows.

msql_fetch_object() is similar to msql_fetch_array(), with one difference - an object is returned, instead of an array. Indirectly, that means that you can only access the data by the field names, and not by their offsets (numbers are illegal property names).

The optional second argument result_type in msql_fetch_array() is a constant and can take the following values: MSQL_ASSOC, MSQL_NUM, and MSQL_BOTH.

Speed-wise, the function is identical to msql_fetch_array(), and almost as quick as msql_fetch_row() (the difference is insignificant).

See also: msql_fetch_array() and msql_fetch_row().

msql_fetch_row

(PHP 3, PHP 4 )

msql_fetch_row -- Get row as enumerated array

Description

array msql_fetch_row ( int query_identifier)

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

msql_fetch_row() fetches one row of data from the result associated with the specified query identifier. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0.

Subsequent call to msql_fetch_row() would return the next row in the result set, or FALSE if there are no more rows.

See also: msql_fetch_array(), msql_fetch_object(), msql_data_seek(), and msql_result().

msql_field_seek

(PHP 3, PHP 4 )

msql_field_seek -- Set field offset

Description

int msql_field_seek ( int query_identifier, int field_offset)

Seeks to the specified field offset. If the next call to msql_fetch_field() won't include a field offset, this field would be returned.

See also: msql_fetch_field().

msql_fieldflags

(PHP 3, PHP 4 )

msql_fieldflags -- Get field flags

Description

string msql_fieldflags ( int query_identifier, int i)

msql_fieldflags() returns the field flags of the specified field. Currently this is either, "not NULL", "primary key", a combination of the two or "" (an empty string).

msql_fieldlen

(PHP 3, PHP 4 )

msql_fieldlen -- Get field length

Description

int msql_fieldlen ( int query_identifier, int i)

msql_fieldlen() returns the length of the specified field.

msql_fieldname

(PHP 3, PHP 4 )

msql_fieldname -- Get field name

Description

string msql_fieldname ( int query_identifier, int field)

msql_fieldname() returns the name of the specified field. query_identifier is the query identifier, and field is the field index. msql_fieldname($result, 2); will return the name of the second field in the result associated with the result identifier.

msql_fieldtable

(PHP 3, PHP 4 )

msql_fieldtable -- Get table name for field

Description

int msql_fieldtable ( int query_identifier, int field)

Returns the name of the table field was fetched from.

msql_fieldtype

(PHP 3, PHP 4 )

msql_fieldtype -- Get field type

Description

string msql_fieldtype ( int query_identifier, int i)

msql_fieldtype() is similar to the msql_fieldname() function. The arguments are identical, but the field type is returned. This will be one of "int", "char" or "real".

msql_free_result

(PHP 3, PHP 4 )

msql_free_result -- Free result memory

Description

int msql_free_result ( int query_identifier)

msql_free_result() frees the memory associated with query_identifier. When PHP completes a request, this memory is freed automatically, so you only need to call this function when you want to make sure you don't use too much memory while the script is running.

msql_freeresult

msql_freeresult -- Free result memory

Description

See msql_free_result()

msql_list_dbs

(PHP 3, PHP 4 )

msql_list_dbs -- List mSQL databases on server

Description

int msql_list_dbs ( void)

msql_list_dbs() will return a result pointer containing the databases available from the current msql daemon. Use the msql_dbname() function to traverse this result pointer.

msql_list_fields

(PHP 3, PHP 4 )

msql_list_fields -- List result fields

Description

int msql_list_fields ( string database, string tablename)

msql_list_fields() retrieves information about the given tablename. Arguments are the database name and the table name. A result pointer is returned which can be used with msql_fieldflags(), msql_fieldlen(), msql_fieldname(), and msql_fieldtype(). A query identifier is a positive integer. The function returns -1 if a error occurs. A string describing the error will be placed in $phperrmsg, and unless the function was called as @msql_list_fields() then this error string will also be printed out.

See also msql_error().

msql_list_tables

(PHP 3, PHP 4 )

msql_list_tables -- List tables in an mSQL database

Description

int msql_list_tables ( string database)

msql_list_tables() takes a database name and result pointer much like the msql() function. The msql_tablename() function should be used to extract the actual table names from the result pointer.

msql_listdbs

msql_listdbs -- List mSQL databases on server

Description

See msql_list_dbs().

msql_listfields

msql_listfields -- List result fields

Description

See msql_list_fields().

msql_listtables

msql_listtables -- List tables in an mSQL database

Description

See msql_list_tables().

msql_num_fields

(PHP 3, PHP 4 )

msql_num_fields -- Get number of fields in result

Description

int msql_num_fields ( int query_identifier)

msql_num_fields() returns the number of fields in a result set.

See also: msql(), msql_query(), msql_fetch_field(), and msql_num_rows().

msql_num_rows

(PHP 3, PHP 4 )

msql_num_rows -- Get number of rows in result

Description

int msql_num_rows ( int query_identifier)

msql_num_rows() returns the number of rows in a result set.

See also: msql(), msql_query(), and msql_fetch_row().

msql_numfields

(PHP 3, PHP 4 )

msql_numfields -- Get number of fields in result

Description

int msql_numfields ( int query_identifier)

Identical to msql_num_fields().

msql_numrows

(PHP 3, PHP 4 )

msql_numrows -- Get number of rows in result

Description

int msql_numrows ( void)

Identical to msql_num_rows().

msql_pconnect

(PHP 3, PHP 4 )

msql_pconnect -- Open persistent mSQL connection

Description

int msql_pconnect ( [string server [, string username [, string password]]])

Returns a positive mSQL persistent link identifier on success, or FALSE on error.

msql_pconnect() acts very much like msql_connect() with two major differences.

First, when connecting, the function would first try to find a (persistent) link that's already open with the same host. If one is found, an identifier for it will be returned instead of opening a new connection.

Second, the connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (msql_close() will not close links established by msql_pconnect()).

This type of links is therefore called 'persistent'.

msql_query

(PHP 3, PHP 4 )

msql_query -- Send mSQL query

Description

int msql_query ( string query, int link_identifier)

msql_query() sends a query to the currently active database on the server that's associated with the specified link identifier. If the link identifier isn't specified, the last opened link is assumed. If no link is open, the function tries to establish a link as if msql_connect() was called, and use it.

Returns a positive mSQL query identifier on success, or FALSE on error.

Exemplo 1. msql_query()

<?php 
$link = msql_connect("dbserver")
   or die("unable to connect to msql server: ".msql_error());
msql_select_db("db", $link)
   or die("unable to select database 'db': ".msql_error());

$result = msql_query("SELECT * FROM table WHERE id=1", $link);
if (!$result) {
   die("query failed: ".msql_error());
}

while ($row = msql_fetch_array($result)) {
    echo $row["id"];
}
?>

See also: msql(), msql_select_db(), and msql_connect().

msql_regcase

msql_regcase --  Make regular expression for case insensitive match

Description

See sql_regcase().

msql_result

(PHP 3, PHP 4 )

msql_result -- Get result data

Description

int msql_result ( int query_identifier, int i, mixed field)

Returns the contents of the cell at the row and offset in the specified mSQL result set.

msql_result() returns the contents of one cell from a mSQL result set. The field argument can be the field's offset, or the field's name, or the field's table dot field's name (fieldname.tablename). If the column name has been aliased ('select foo as bar from ...'), use the alias instead of the column name.

When working on large result sets, you should consider using one of the functions that fetch an entire row (specified below). As these functions return the contents of multiple cells in one function call, they're MUCH quicker than msql_result(). Also, note that specifying a numeric offset for the field argument is much quicker than specifying a fieldname or tablename.fieldname argument.

Recommended high-performance alternatives: msql_fetch_row(), msql_fetch_array(), and msql_fetch_object().

msql_select_db

(PHP 3, PHP 4 )

msql_select_db -- Select mSQL database

Description

int msql_select_db ( string database_name, int link_identifier)

Returns TRUE on success, FALSE on error.

msql_select_db() sets the current active database on the server that's associated with the specified link identifier. If no link identifier is specified, the last opened link is assumed. If no link is open, the function will try to establish a link as if msql_connect() was called, and use it.

Every subsequent call to msql_query() will be made on the active database.

See also: msql_connect(), msql_pconnect(), and msql_query().

msql_selectdb

msql_selectdb -- Select mSQL database

Description

See msql_select_db().

msql_tablename

(PHP 3, PHP 4 )

msql_tablename -- Get table name of field

Description

string msql_tablename ( int query_identifier, int field)

msql_tablename() takes a result pointer returned by the msql_list_tables() function as well as an integer index and returns the name of a table. The msql_numrows() function may be used to determine the number of tables in the result pointer.

Exemplo 1. msql_tablename() example

<?php 
msql_connect ("localhost");
$result = msql_list_tables ("wisconsin");
$i = 0;
while ($i < msql_numrows ($result)) {
    $tb_names[$i] = msql_tablename ($result, $i);
    echo $tb_names[$i] . "<BR>";
    $i++; 
}
?>

msql

(PHP 3, PHP 4 )

msql -- Send mSQL query

Description

int msql ( string database, string query, int link_identifier)

Returns a positive mSQL query identifier to the query result, or FALSE on error.

msql() selects a database and executes a query on it. If the optional link identifier isn't specified, the function will try to find an open link to the mSQL server and if no such link is found it'll try to create one as if msql_connect() was called with no arguments (see msql_connect()).

LXIII. MySQL

Introdução

Estas funções permitem acessar os servidores de banco de dados do MYSQL. Maiores informações podem ser encontradas em http://www.mysql.com/.

Documentação para MySQL pode ser encontrada em http://www.mysql.com/documentation/.


Requisitos

Para ter estas funções disponiveis, você deve compilar o PHP com suporte a MySQL.


Instalação

Usando a opção de configuração --with-mysql você permite ao PHP acessar banco de dados do MySQL. Se você usar esta opção sem especificar o caminho para o MySQL, o PHP usará as bibliotecas do cliente que vem com ele. Com o PHP4, o suporte a MySQL esta sempre ativado; se você não especificar a opção de configuração, as bibliotecas que vem com o PHP serão usadas. Usuários que usam outras aplicações que usam MySQL (por exemplos, executando PHP3 e PHP4 como modulos do apache, ou auth-mysql) devem sempre espicificar o caminho para o MySQL: --with-mysql=/caminho/para/mysql. Isto irá forçar o PHP a usar as bibliotecas de cliente instaladas com o MySQL, evitando quaisquer conflitos.

Atenção

Quebras e problemas de inicialização do PHP podem ser encontrados quando carrega-se esta extensão em conjunto com a extensão recode. Veja a extensão recode para maiores informações.


Configuração durante execução

O comportamento dessas funções podem ser modificado pelas configurações do php.ini.

Tabela 1. Opções de configuração do MySQL

Nome Padrão Modificável
mysql.allow_persistent "On" PHP_INI_SYSTEM
mysql.max_persistent "-1" PHP_INI_SYSTEM
mysql.max_links "-1" PHP_INI_SYSTEM
mysql.default_port NULL PHP_INI_ALL
mysql.default_socket NULL PHP_INI_ALL
mysql.default_host NULL PHP_INI_ALL
mysql.default_user NULL PHP_INI_ALL
mysql.default_password NULL PHP_INI_ALL
mysql.connect_timeout "0" PHP_INI_SYSTEM
Para maiores detalhes e deinição de constantes PHP_INI_* veja ini_set().

Aqui esta uma pequena explicação das diretivas de configuração.

mysql.allow_persistent boolean

Quando permitir conexões persistentes para o MySQL.

mysql.max_persistent integer

O número máximo de conexões persistentes com o MySQL por processo.

mysql.max_links integer

O número maximo de conexões com o MYSQL por processo, incluindo conexões persistentes.

mysql.default_port string

O número padrão da porta TCP a usar quando conectar com o servidor do banco de dados se nenhuma outra porta for especificada. Se nenhum padrão for especificado, aporta será obtida da variavel de ambiente MYSQL_TCP_PORT, da entrada mysql-tcp em /etc/services ou da constante da compilação MYSQL_PORT, nesta ordem. Windows irá usar somente a constante MYSQL_PORT.

mysql.default_socket string

O nome padrão do socket para usar quando conectar com um servidor de banco de dados local se outro nome de socket não for especificado.

mysql.default_host string

O servidor padrão para usar quando conectar com um servidor de banco de dados se outro servidor não for encontrado. Não se aplica em safe mode.

mysql.default_user string

O nome padrão de usuário para conectar ao servidor de banco de dados se outro nome não for especificado. Não se aplica em safe mode.

mysql.default_password string

A senha padrão para usar ao conectar ao servidor de banco de dados se outra senha não for especificada. Não se aplica em safe mode.

mysql.connect_timeout integer

Limite de tempo da conexão em segundos. No Linux este limite é também usado para a espera da primeira resposta do servidor.


Tipos Resource

Há dois tipos de recursos usados no modulo MySql. O primeiro é a identificação do link da conexão com o banco de dados, o segundo é o que guarda o resultado de uma query.


Constantes Predefinidas

As contantes abaixo são definidas por esta extensão e somente estarão disponíveis quando a extensão foi compilada com o PHP ou carregada dinamicamente durante a execução.

Desde PHP 4.3.0 é possivel especificar opções adicionais para as funções mysql_connect() and mysql_pconnect() As seguintes constantes são definidas:

Tabela 2. Constante do cliente MySQL

constante descrição
MYSQL_CLIENT_COMPRESS usa o protocolo de compressão
MYSQL_CLIENT_IGNORE_SPACE Permite espaço após o nome de função
MYSQL_CLIENT_INTERACTIVE Permite interactive_timeout segundos (ao inves de wait_timeout) de inatividade antes de fechar a conexão.

A função mysql_fetch_array() usa uma constante para cada diferentes tipos de matrizes de resultado. As seguintes constantes são definidas:

Tabela 3. MySQL fetch constants

constante descrição
MYSQL_ASSOC As colunas são retornadas na matriz tendo o nome do campo como índice da matriz.
MYSQL_BOTH As colunas são retornadas na matriz tendo ambos os indices: um numérico e o um com o nome do campo.
MYSQL_NUM As colunas são retornadas numa matriz tendo um indice numérico dos campos. Este indice começa com 0, o primeiro campo no resultado.


Exemplos

Este exemplo simples mostra como conectar, executar uma query, mostrar o resultado e desconectar do banco de dados do MySQL.

Exemplo 1. Exemplo da extensão do MySQL

<?php
    /* Conectando, escolhendo o banco de dados */
    $link = mysql_connect("mysql_host", "mysql_user", "mysql_password")
        or die("Não pude conectar");
    print "Conexão bem sucedida";
    mysql_select_db("my_database") or die("Não pude selecionar o banco de dados");

    /* Fazendo a query SQL*/
    $query = "SELECT * FROM my_table";
    $result = mysql_query($query) or die("Query falhou");

    /* Mostrando os resultados em HTML */
    print "<table>\n";
    while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
        print "\t<tr>\n";
        foreach ($line as $col_value) {
            print "\t\t<td>$col_value</td>\n";
        }
        print "\t</tr>\n";
    }
    print "</table>\n";

    /* Liberando o resultado */
    mysql_free_result($result);

    /* Fechando a conexão */
    mysql_close($link);
?>

Índice
mysql_affected_rows -- Devolve o número de linhas afetadas na operação anterior com o MySQL
mysql_change_user --  Muda o usuário logado da conexão ativa
mysql_client_encoding -- Retorna o nome do conjunto de caracteres
mysql_close -- Fecha a conexão com o MySQL
mysql_connect -- Abre uma conexão com o servidor MySQL
mysql_create_db -- Cria um banco de dados do MySQL
mysql_data_seek -- Move o ponteiro interno do resultado
mysql_db_name -- Retorna os nomes dos bancos de dados
mysql_db_query -- Envia uma query ao MySQL
mysql_drop_db -- Apaga um banco de dados do MySQL
mysql_errno --  Retorna o valor numérico da mensagem de erro da operação anterior do MySQL
mysql_error --  Retorna o texto da mensagem de erro da operação anterior do MySQL
mysql_escape_string --  Escapa uma string para uso com o mysql_query.
mysql_fetch_array --  Busca o resultado de uma linha e o coloca como uma matriz associativa, matriz numérica ou ambas.
mysql_fetch_assoc --  Busca o resultado de uma linha e o coloca numa matriz associativa
mysql_fetch_field --  Retorna informação sobre uma coluna de um resultado como um objeto
mysql_fetch_lengths --  Retorna o tamanho de cada campo do resultado
mysql_fetch_object -- Retorna o resultado de uma linha como um objeto
mysql_fetch_row -- Retorna o resultado de uma linha numa matriz numérica
mysql_field_flags --  Pega as flags do campo especificado no resultado
mysql_field_len --  Retorna o tamanho do campo
mysql_field_name --  Retorna o nome do campo especificado no resultado de uma query
mysql_field_seek --  Move o ponteiro do resultado para um campo especificado
mysql_field_table --  Retorna o nome da tabela onde esta o campo especificado
mysql_field_type --  Retorna o tipo do campo especificado em um resultado de query
mysql_free_result -- Libera a memória do resultado de uma query
mysql_get_client_info -- Retorna informação da versão do cliente MySQL
mysql_get_host_info -- Retorna informação sobre o host do MySQL
mysql_get_proto_info -- Retorna informação do protocolo do MySQL
mysql_get_server_info -- Retorna informação do servidor MySQL
mysql_info --  Retorna informação sobre a última query
mysql_insert_id --  Retorna o ID gerado da operação INSERT anterior
mysql_list_dbs --  Lista os bancos de dados disponiveis o servidor do MySQL
mysql_list_fields -- Lista os campos de uma tabela
mysql_list_processes -- Lista os processos MySQL
mysql_list_tables -- Lista as tabelas em um banco de dados MySQL
mysql_num_fields -- Retorna o número de campos no resulatdo
mysql_num_rows -- Retorna o número de linhas em um resultado
mysql_pconnect --  Abre uma conexão persistente com um servidor MySQL
mysql_ping -- Pinga uma conexão ou reconecta se não houver conexão
mysql_query -- Realiza uma query MySQL
mysql_real_escape_string --  Escapa os caracteres especiais numa string para usar em um comando SQL, levando em conta o conjunto atual de caracteres.
mysql_result -- Retorna dados do resultado
mysql_select_db -- Seleciona um banco de dados MySQL
mysql_stat -- Retorna o status atual do sistema
mysql_tablename -- Retorna o nome da tabela do campo
mysql_thread_id -- Returna o ID da thread atual
mysql_unbuffered_query --  Envia uma query para o MySQL, sem retornar e colocar em buffer as linhas do resultado

mysql_affected_rows

(PHP 3, PHP 4 )

mysql_affected_rows -- Devolve o número de linhas afetadas na operação anterior com o MySQL

Descrição

int mysql_affected_rows ( [resource link_identifier])

mysql_affected_rows() retorna o número de linhas afetadas pela ultima query INSERT, UPDATE ou DELETE associada a link_identifier. Se o identificador de link não é especificado, o ultimo link aberto por mysql_connect() é utilizado.

Nota: Se você esta usando transações, você deve chamar mysql_affected_rows() após sua query INSERT, UPDATE, ou DELETE, não depois de commit.

Se a ultima query foi um DELETE sem a cláusula WHERE, todos os registros foram apagados da tabela, mas esta função retornará zero.

Nota: Quando usando UPDATE, o MySQL não atualizará as colunas onde o novo valor é o mesmo que o valor anterior. Isto cria a possibilidade de que a função mysql_affected_rows() não seja atualmente igual ao número de linhas encontradas, somente o número de linhas que literalmente foram afetadas pela query.

A função mysql_affected_rows() não funciona com os comandos SELECT; somente comandos que modificam os registros. Para pegar o número de linhas retornados por SELECT, use mysql_num_rows().

Se a ultima query falhou, esta função irá retornar -1.

Exemplo 1. Delete-Query

<?php
    /* Conecta com o banco de dados */
    mysql_pconnect("localhost", "mysql_user", "mysql_password") or
        die ("Não pude conectar: " . mysql_error());

    /* Este deve retornar o número coreto de registros excluídos */
    mysql_query("DELETE FROM mytable WHERE id < 10");
    printf ("Registros excluídos: %d\n", mysql_affected_rows());

    /* Sem a clausula where no comando delete, deve retornar 0 */
    mysql_query("DELETE FROM mytable");
    printf ("Registros excluídos: %d\n", mysql_affected_rows());
?>

O exemplo acima deve produzir a seguinte saída:
Registros excluídos: 10
Registros excluídos: 0

Exemplo 2. Update-Query

<?php
    /* conecta com o banco de dados */
    mysql_pconnect("localhost", "mysql_user", "mysql_password") or
        die ("Não pude conectar: " . mysql_error());

    /* Atualiza os registros */
    mysql_query("UPDATE mytable SET used=1 WHERE id < 10");
    printf ("Registros atualizados: %d\n", mysql_affected_rows());
mysql_query("COMMIT");
?>

O exemplo acima deve produzir a seguinte saída:
Registros atualizados: 10

Veja também: mysql_num_rows(), mysql_info().

mysql_change_user

(PHP 3>= 3.0.13)

mysql_change_user --  Muda o usuário logado da conexão ativa

Descrição

int mysql_change_user ( string user, string password [, string database [, resource link_identifier]])

A função mysql_change_user() muda o usuário logado da conexão ativa atual, ou da conexão dada pelo parâmetro opcional link_identifier. Se um banco de dados é especificado, este será o banco de dados atual depois que mudar de usuário. Se houver erro na troca de usuário o que esta atualmente conectado permanece como o usuário ativo. Retorna TRUE em caso de sucesso ou FALSE em falhas.

Nota: Esta função foi introduzida no PHP 3.0.13 e requer MySQL 3.23.3 ou superior. Ela não esta disponível no PHP 4.

mysql_client_encoding

(PHP 4 >= 4.3.0)

mysql_client_encoding -- Retorna o nome do conjunto de caracteres

Descrição

int mysql_client_encoding ( [resource link_identifier])

A função mysql_client_encoding() retorna o conjunto de caracteres padrão para a conexão atual.

Exemplo 1. Exemplo mysql_client_encoding()

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$charset = mysql_client_encoding($link);
printf ("Conjunto atual de caracteres é %s\n", $charset);
?>

O exemplo acima deve produzir a seguinte saida:
Conjunto atual de caracteres é latin1

Veja também: mysql_real_escape_string()

mysql_close

(PHP 3, PHP 4 )

mysql_close -- Fecha a conexão com o MySQL

Descrição

bool mysql_close ( [resource link_identifier])

Retorna TRUE em caso de sucesso ou FALSE em falhas.

A função mysql_close() fecha a conexão com o servidor MySQL que você referir com o link_identifier. Se o parâmetro link_identifier não é especificado a ultima conexão aberta é usada.

Usar a função mysql_close() não é atualmente necessário, porque conexões não persistentes são automaticamente fechadas ao final da execução do script. Veja também freeing resources.

Nota: mysql_close() não irá fechar conexões persistentes criadas por mysql_pconnect().

Exemplo 1. Exemplo MySQL close

<?php
    $link = mysql_connect("localhost", "mysql_user", "mysql_password")
        or die("Não pude conectar: " . mysql_error());
    print ("Conectado!");
    mysql_close($link);
?>

Veja também: mysql_connect(), e mysql_pconnect().

mysql_connect

(PHP 3, PHP 4 )

mysql_connect -- Abre uma conexão com o servidor MySQL

Descrição

resource mysql_connect ( [string server [, string username [, string password [, bool new_link [, int client_flags]]]]])

Retorna um identificador de link (link_identifier) com o MySQL se der certo, ou FALSE se falhar.

mysql_connect() estabelece uma conexão com o servidor MySQL. Os seguintes padrões são assumidos para os argumentos opcionais que estiverem faltando: server = 'localhost:3306', username = nome do usuário dono do processo do servidor, password = senha vazia.

O parâmetro server pode também incluir um número de porta. Exemplo: "hostname:port" ou um caminho para um socket, exemplo. ":/path/to/socket" para o servidor local (localhost).

Nota: Suporte para ":port" foi adicionado no PHP 3.0B4.

Suporte para ":/path/to/socket" foi adicionado no PHP 3.0.10.

Você pode suprimir a mensagem de erro em caso de falha colocando um @ antes do nome da função.

Se uma segunda chamada é feita para mysql_connect() com os mesmos argumentos, um novo link não será estabelecido, mas ao invés disto o identificador da conexão já aberta será retornado. O parâmetro new_link modifica esta opção e faz com que a função mysql_connect() sempre abra um novo link, mesmo que mysql_connect() seja chamada com os mesmos parâmetros. O parâmetro client_flags pode ser uma combinação das constantes MYSQL_CLIENT_SSL, MYSQL_CLIENT_COMPRESS, MYSQL_CLIENT_IGNORE_SPACE ou MYSQL_CLIENT_INTERACTIVE.

Nota: O parâmetro new_link tornou-se disponível no PHP 4.2.0

O parâmetro client_flags tornou-se disponível no PHP 4.3.0

O link com o servidor será fechado tão logo a execução do script termine, se não tiver sido fechado anteriormente por chamar explicita à mysql_close().

Exemplo 1. Exemplo de conexão MySQL

<?php
    $link = mysql_connect("localhost", "mysql_user", "mysql_password")
        or die("Não pude conectar: " . mysql_error());
    print ("Conectado");
    mysql_close($link);
?>

Veja também mysql_pconnect() e mysql_close().

mysql_create_db

(PHP 3, PHP 4 )

mysql_create_db -- Cria um banco de dados do MySQL

Descrição

bool mysql_create_db ( string database name [, resource link_identifier])

mysql_create_db() tenta criar um novo banco de dados no servidor especificado pelo identificador de link (link_identifier) indicado.

Retorna TRUE em caso de sucesso ou FALSE em falhas.

Exemplo 1. Exemplo MySQL create database

<?php
    $link = mysql_pconnect("localhost", "mysql_user", "mysql_password")
        or die("Não pude conectar: " . mysql_error());

    if (mysql_create_db("my_db")) {
        print ("Banco de dados criado\n");
    } else {
        printf ("Erro criando o banco de dados: %s\n", mysql_error());
    }
?>

Para compatibilidade com versões anteriores mysql_createdb() também pode ser usada. Em todo o caso ela esta obsoleta.

Nota: A função mysql_create_db() está obsoleta. É preferível usar mysql_query() para fazer o comando SQL CREATE DATABASE.

Veja também: mysql_drop_db(), mysql_query().

mysql_data_seek

(PHP 3, PHP 4 )

mysql_data_seek -- Move o ponteiro interno do resultado

Descrição

bool mysql_data_seek ( resource result_identifier, int row_number)

Retorna TRUE em caso de sucesso ou FALSE em falhas.

mysql_data_seek() move o ponteiro interno do resultado MySQL associado ao identificador de resultado (result_identifier) especificado para apontar a linha identificada. A próxima chamada a mysql_fetch_row() irá retornar esta linha.

O parâmetro row_number (número de linha) começa no 0. O row_number deve ser um valor entre 0 e mysql_num_rows - 1.

Nota: A função mysql_data_seek() pode ser usada somente em conjunto com mysql_query(), não com mysql_unbuffered_query().

Exemplo 1. Exemplo MySQL data seek

<?php
    $link = mysql_pconnect("localhost", "mysql_user", "mysql_password")
        or die("Não pude conectar: " . mysql_error());

    mysql_select_db("samp_db")
        or die("Não pude selecionar o banco de dados: " . mysql_error());
    $query = "SELECT last_name, first_name FROM friends";
    $result = mysql_query($query)
        or die("Query falhou: " . mysql_error());

    /* fetch rows in reverse order */
    for ($i = mysql_num_rows($result) - 1; $i >= 0; $i--) {
        if (!mysql_data_seek($result, $i)) {
            echo "Não pude ir para a linha $i:" . mysql_error() . "\n";
            continue;
        }

        if(!($row = mysql_fetch_object($result)))
            continue;

        echo "$row->last_name $row->first_name<br />\n";
    }

    mysql_free_result($result);
?>

Veja também: mysql_query() e mysql_num_rows().

mysql_db_name

(PHP 3>= 3.0.6, PHP 4 )

mysql_db_name -- Retorna os nomes dos bancos de dados

Descrição

string mysql_db_name ( resource result, int row [, mixed field])

mysql_db_name() tem como primeiro parâmetro o resultado de uma chamada a mysql_list_dbs(). O parâmetro row é o índice no conjunto de respostas.

Se houver um erro é retornado FALSE. Use mysql_errno() e mysql_error() para determinar a natureza do erro.

Exemplo 1. Exemplo mysql_db_name()

<?php
    error_reporting(E_ALL);

    mysql_connect('dbhost', 'username', 'password');
    $db_list = mysql_list_dbs();

    $i = 0;
    $cnt = mysql_num_rows($db_list);
    while ($i < $cnt) {
        echo mysql_db_name($db_list, $i) . "\n";
        $i++;
    }
?>

Para compatibilidade com versões anteriores, mysql_dbname() também é aceito. Seu uso está obsoleto.

mysql_db_query

(PHP 3, PHP 4 )

mysql_db_query -- Envia uma query ao MySQL

Descrição

resource mysql_db_query ( string database, string query [, resource link_identifier])

Retorna um recurso com o resultado de uma query, ou FALSE se houver erro. A função também retorna TRUE/FALSE para as query INSERT/UPDATE/DELETE para indicar sucesso ou falha.

mysql_db_query() seleciona um banco de dados e executa uma query nele. Se o link_identifier não for especificado (é opcional), a função tenterá achar um link aberto para o servidor MySQL, e se nenhum for encontrado, a função tenterá criar um como se a função mysql_connect() fosse chamada sem argumentos.

Tenha cuidado pois esta função NÃO seleciona de volta o banco de dados que você estava conectado antes. Em outras palavras, você não pode usar esta função para executar uma query temporariamente em outro banco de dados, você deve manualmente trocar de volta o banco de dados. É fortemente recomendado usar a sintaxe database.table nas suas queries ao invés desta função.

Veja também mysql_connect() e mysql_query().

Nota: Esta função é obsoleta desde PHP 4.0.6. Não use esta função. Ao invés utilize mysql_select_db() e mysql_query().

mysql_drop_db

(PHP 3, PHP 4 )

mysql_drop_db -- Apaga um banco de dados do MySQL

Descrição

bool mysql_drop_db ( string database_name [, resource link_identifier])

Retorna TRUE em caso de sucesso ou FALSE em falhas.

mysql_drop_db() tenta remover todo um banco de dados do servidor especificado em link_identifier.

Para compatibilidade com as versãoes anteriores, mysql_dropdb() pode ser usada também. Esta função é obsoleta.

Nota: A função mysql_drop_db() é obsoleta. É preferivel usar mysql_query() ao invés um comando SQL DROP DATABASE.

Veja também: mysql_create_db() e mysql_query().

mysql_errno

(PHP 3, PHP 4 )

mysql_errno --  Retorna o valor numérico da mensagem de erro da operação anterior do MySQL

Descrição

int mysql_errno ( [resource link_identifier])

Retorna o número do erro da ultima função do MySQL, ou 0 (zero) se não houve erro.

Erros vindos do MySQL não causam avisos. Ao invés, use mysql_errno() para obter o código de erro. Note que esta função somente retorna o código de erro da ultima função do MySQL que foi executada(não incluindo mysql_error() e mysql_errno()), assim se você quer usa-la, tenha certeza de utiliza-la antes de chamar outra função do MySQL.

Exemplo 1. Exemplo mysql_errno

<?php
    mysql_connect("localhost", "mysql_user", "mysql_password");

    mysql_select_db("arquivonaoexistente");
    echo mysql_errno() . ": " . mysql_error(). "\n";

    mysql_select_db("kossu");
    mysql_query("SELECT * FROM tabelanaoexistente");
    echo mysql_errno() . ": " . mysql_error() . "\n";
?>

O exemplo acima deve produzir a seguinte saida:

1049: Unknown database 'arquivonaoexistente'
1146: Table 'kossu.tabelanaoexistente' doesn't exist

Nota: Se o argumento opcional é especificado, a conexão indicada é usada para obter o código de erro. Se não, a ultima conexão aberta é usada.

Veja também: mysql_error()

mysql_error

(PHP 3, PHP 4 )

mysql_error --  Retorna o texto da mensagem de erro da operação anterior do MySQL

Descrição

string mysql_error ( [resource link_identifier])

Retorna o texto do erro da ultima função do MySQL, ou '' (Uma string vazia) se não houve erro.

Erros vindo do MySQL não causam avisos. Ao invés, use mysql_error() para obter o texto do erro. Note que esta função somente retorna o texto de erro da ultima função do MySQL que foi executada(não incluindo mysql_error() e mysql_errno()), assim se você quer usa-la, tenha certeza de utiliza-la antes de chamar outra função do MySQL.

Exemplo 1. Exemplo mysql_error

<?php
    mysql_connect("localhost", "mysql_user", "mysql_password");

    mysql_select_db("arquivonaoexistente");
    echo mysql_errno() . ": " . mysql_error(). "\n";

    mysql_select_db("kossu");
    mysql_query("SELECT * FROM tabelanaoexistente");
    echo mysql_errno() . ": " . mysql_error() . "\n";
?>

O exemplo acima deve produzir a seguinte saida:

1049: Unknown database 'arquivonaoexistente'
1146: Table 'kossu.tabelanaoexistente' doesn't exist

Nota: Se o argumento opcional é especificado, a conexão indicada é usada para obter o código de erro. Se não, a ultima conexão aberta é usada.

Veja também: mysql_errno()

mysql_escape_string

(PHP 4 >= 4.0.3)

mysql_escape_string --  Escapa uma string para uso com o mysql_query.

Descrição

string mysql_escape_string ( string unescaped_string)

Esta função irá escapar o unescaped_string, assim será seguro coloca-la na função mysql_query().

Nota: mysql_escape_string() não escapa % e _.

Esta função é identica a mysql_real_escape_string() exceto que mysql_real_escape_string() precisa de um identificador de conexão e escapa a string de acordo com o conjunto atual de caracteres atual. mysql_escape_string() não precisa de um identificador de conexão e não respeita o conjunto atual de caracteres.

Exemplo 1. Exemplo mysql_escape_string()

<?php
    $item = "Zak's Laptop";
    $escaped_item = mysql_escape_string($item);
    printf ("String escapada: %s\n", $escaped_item);
?>

O exemplo acima deve produzir a seguinte saida:
Escaped string: Zak\'s Laptop

Veja também: mysql_real_escape_string(), addslashes(), e a diretiva magic_quotes_gpc.

mysql_fetch_array

(PHP 3, PHP 4 )

mysql_fetch_array --  Busca o resultado de uma linha e o coloca como uma matriz associativa, matriz numérica ou ambas.

Descrição

array mysql_fetch_array ( resource result [, int result_type])

Retorna uma matriz que corresponde a linha buscada, ou FALSE se não houverem mais linhas.

mysql_fetch_array() é uma versão estendida de mysql_fetch_row(). Além de guardar os dados em um índice numérico na matriz, também guarda os dados em índices associativos, usando o nome do campo como chave.

Se duas ou mais colunas do resultado tiverem o mesmo nome do campo, a ultima coluna terá precedência. Para acessar as outras coluna(s) com o mesmo nome, você deve usar o índice numérico da coluna ou fazer um apelido para a coluna. Para colunas com apelido, você não pode acessar os conteúdos com o nome original da coluna (usando 'field' neste exemplo).

Exemplo 1. Query com nomes de campo duplicados

select table1.field as foo table2.field as bar from table1, table2

Uma coisa importante para notar é que usar mysql_fetch_array() não é significativamente mais lenta do que usar mysql_fetch_row(), enquanto que produz um resultado melhor de se usar.

O segundo argumento, que é opcional, result_type em mysql_fetch_array() é uma constante que pode ter os seguintes valores: MYSQL_ASSOC, MYSQL_NUM, e MYSQL_BOTH. Isto foi adicionado no PHP 3.0.7. MYSQL_BOTH é o padrão para este argumento.

Usando MYSQL_BOTH, você terá uma matriz com os índices associativos e numéricos. Usando MYSQL_ASSOC, você terá apenas os índices associativos (como funciona mysql_fetch_assoc()), usando MYSQL_NUM, você terá apenas os índices numéricos (como funciona mysql_fetch_row()).

Exemplo 2. mysql_fetch_array com MYSQL_NUM

<?php
    mysql_connect("localhost", "mysql_user", "mysql_password") or
        die("Não pude conectar: " . mysql_error());
    mysql_select_db("mydb");

    $result = mysql_query("SELECT id, name FROM mytable");

    while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
        printf ("ID: %s  Name: %s", $row[0], $row[1]);  
    }

    mysql_free_result($result);
?>

Exemplo 3. mysql_fetch_array com MYSQL_ASSOC

<?php
    mysql_connect("localhost", "mysql_user", "mysql_password") or
        die("Não pude conectar: " . mysql_error());
    mysql_select_db("mydb");

    $result = mysql_query("SELECT id, name FROM mytable");

    while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
        printf ("ID: %s  Name: %s", $row["id"], $row["name"]);
    }

    mysql_free_result($result);
?>

Exemplo 4. mysql_fetch_array com MYSQL_BOTH

<?php
    mysql_connect("localhost", "mysql_user", "mysql_password") or
        die("Não pude conectar: " . mysql_error());
    mysql_select_db("mydb");

    $result = mysql_query("SELECT id, name FROM mytable");

    while ($row = mysql_fetch_array($result, MYSQL_BOTH)) {
        printf ("ID: %s  Name: %s", $row[0], $row["name"]);
    }

    mysql_free_result($result);
?>

Para maiores detalhes, veja também mysql_fetch_row() e mysql_fetch_assoc().

mysql_fetch_assoc

(PHP 4 >= 4.0.3)

mysql_fetch_assoc --  Busca o resultado de uma linha e o coloca numa matriz associativa

Descrição

array mysql_fetch_assoc ( resource result)

Retorna uma matriz associativa que corresponde a linha ou FALSE se não houverem mais linhas.

mysql_fetch_assoc() é equivalente a chamar mysql_fetch_array() com MYSQL_ASSOC para o segundo parâmetro, que é opcional. Somente retorna uma matriz associativa. Este é o jeito que mysql_fetch_array() funcionava originalmente. Se você precisa dos índices numéricos assim como o associativo, use mysql_fetch_array().

Se duas ou mais colunas do resultado tiverem o mesmo nome do campo, a ultima coluna terá precedência. Para acessar as outras coluna(s) com o mesmo nome, você deve usar o índice numérico da coluna usando mysql_fetch_row() ou fazer um apelido para a coluna. Veja o exemplo em mysql_fetch_array() uma descrição para apelidos.

Uma coisa importante para notar é que usar mysql_fetch_assoc() não é significativamente mais lenta do que usar mysql_fetch_row(), enquanto produz um resultado melhor de usar.

Exemplo 1. mysql_fetch_assoc()

<?php

    $conn = mysql_connect("localhost", "mysql_user", "mysql_password");
    
    if (!$conn) {
        echo "Não foi possível conectar: " . mysql_error();
        exit;
    }

    if (!mysql_select_db("mydbname")) {
        echo "Não foi possível selecionar mydbname: " . mysql_error();
        exit;
    }

    $sql = "SELECT id as userid, fullname, userstatus
            FROM   sometable
            WHERE  userstatus = 1";

    $result = mysql_query($sql);

    if (!$result) {
        echo "Não foi possível executar a query ($sql): " . mysql_error();
        exit;
    }

    if (mysql_num_rows($result) == 0) {
        echo "Nenhuma linha encontrada, nada para mostrar, então estou saindo";
        exit;
    }

    // Enquanto uma linha com dados existir, coloca esta linha em $row como uma matriz associativa
    // Nota: Se você esta esperando somente uma linha, não é necessário usar o loop
    // Note: Se você colocar extract($row); dentro o loop a seguir,
    //       então você irá criar $userid, $fullname, and $userstatus
    while ($row = mysql_fetch_assoc($result)) {
        echo $row["userid"];
        echo $row["fullname"];
        echo $row["userstatus"];
    }

    mysql_free_result($result);

?>

Para maiores detalhes, veja também mysql_fetch_row(), mysql_fetch_array() e mysql_query().

mysql_fetch_field

(PHP 3, PHP 4 )

mysql_fetch_field --  Retorna informação sobre uma coluna de um resultado como um objeto

Descrição

object mysql_fetch_field ( resource result [, int field_offset])

Retorna um objeto contendo informação sobre um campo.

mysql_fetch_field() pode ser usado para obter informações sobre os campos num certo resultado de uma query. Se o índice do campo não é especificado, o próximo campo que não foi ainda retornado por mysql_fetch_field() é retornado.

As propriedades do objeto são:

  • name - nome da coluna

  • table - nome da tabela onde esta o campo

  • max_length - o limite de tamanho para a coluna

  • not_null - 1 se a coluna não pode ser NULL

  • primary_key - 1 se a coluna é a chave primária

  • unique_key - 1 se a coluna é a chave única

  • multiple_key - 1 se a coluna é uma chave não única

  • numeric - 1 se a coluna é numérica

  • blob - 1 se a coluna é BLOB

  • type - o tipo da coluna

  • unsigned - 1 se a coluna é unsigned(sem sinal)

  • zerofill - 1 se a coluna é preenchida com zero

Exemplo 1. mysql_fetch_field()

<?php
mysql_connect('localhost:3306', $user, $password)
    or die ("Não pude conectar: " . mysql_error());
mysql_select_db("database");
$result = mysql_query("select * from table")
    or die("A query falhou: " . mysql_error());
/* get column metadata */
$i = 0;
while ($i < mysql_num_fields($result)) {
    echo "Informação para a coluna $i:<br />\n";
    $meta = mysql_fetch_field($result);
    if (!$meta) {
        echo "Informação não disponivel<br />\n";
    }
    echo "<pre>
blob:         $meta->blob
max_length:   $meta->max_length
multiple_key: $meta->multiple_key
name:         $meta->name
not_null:     $meta->not_null
numeric:      $meta->numeric
primary_key:  $meta->primary_key
table:        $meta->table
type:         $meta->type
unique_key:   $meta->unique_key
unsigned:     $meta->unsigned
zerofill:     $meta->zerofill
</pre>";
    $i++;
}
mysql_free_result($result);
?>

Veja também mysql_field_seek().

mysql_fetch_lengths

(PHP 3, PHP 4 )

mysql_fetch_lengths --  Retorna o tamanho de cada campo do resultado

Descrição

array mysql_fetch_lengths ( resource result)

Retorna uma matriz que corresponte ao tamanho de cada campo na ultima coluna retornada por mysql_fetch_row(), ou FALSE se houver erro.

mysql_fetch_lengths() guarda o tamanho de cada coluna do resultado retornado por mysql_fetch_row(), mysql_fetch_array(), e mysql_fetch_object() numa matriz, com o índice começando em 0.

Veja também: mysql_fetch_row().

mysql_fetch_object

(PHP 3, PHP 4 )

mysql_fetch_object -- Retorna o resultado de uma linha como um objeto

Descrição

object mysql_fetch_object ( resource result)

Retorna um objeto com propriedades que correspondem a linha, ou FALSE se não houverem mais linhas.

mysql_fetch_object() é similar a mysql_fetch_array(), com uma diferença - um objeto é retornado ao invés de uma matriz. Indiretamente, isto indica que você só pode acessar os dados pelo nome do campo, e não pelos seus índices (números como nomes de propriedades são inválidos).

<?php

/* Isto é válido */
echo $row->field;
/* Isto é inválido */
echo $row->0;

?>

Em velocidade, a função é identica a mysql_fetch_array(), e quase tão rapida quanto mysql_fetch_row() (a diferença é insignificante).

Exemplo 1. Exemplo mysql_fetch_object()

<?php
mysql_connect("hostname", "user", "password");
mysql_select_db($db);
$result = mysql_query("select * from table");
while ($row = mysql_fetch_object($result)) {
    echo $row->user_id;
    echo $row->fullname;
}
mysql_free_result($result);
?>

Veja também: mysql_fetch_array() e mysql_fetch_row().

mysql_fetch_row

(PHP 3, PHP 4 )

mysql_fetch_row -- Retorna o resultado de uma linha numa matriz numérica

Descrição

array mysql_fetch_row ( resource result)

Retorna uma matriz numérica que corresponde a linha, ou FALSE se não houverem mais linhas.

mysql_fetch_row() retorna os dados de uma linha do resultado identificado por result(resultado de uma query). A linha é retornada como uma matriz. Cada coluna é um índice da matriz, começando em 0.

A próxima chamada a mysql_fetch_row() irá retornar a próxima linha do conjunto de resultados, ou FALSE se não houverem mais linhas.

Veja também: mysql_fetch_array(), mysql_fetch_object(), mysql_data_seek(), mysql_fetch_lengths(), e mysql_result().

mysql_field_flags

(PHP 3, PHP 4 )

mysql_field_flags --  Pega as flags do campo especificado no resultado

Descrição

string mysql_field_flags ( resource result, int field_offset)

mysql_field_flags() retorna as flags do campo especificado. As flags são retornadas como uma única palavra separadas por um único espaço, assim você pode separar o valor retornado com explode().

As seguintes flags são retornadas, se a sua versão do MySQL é atual o suficiente para reporta-las: "not_null", "primary_key", "unique_key", "multiple_key", "blob", "unsigned", "zerofill", "binary", "enum", "auto_increment", "timestamp".

Para compatibilidade com as versões anteriores mysql_fieldflags() também pode ser usada. Esta função esta depreciada.

mysql_field_len

(PHP 3, PHP 4 )

mysql_field_len --  Retorna o tamanho do campo

Descrição

int mysql_field_len ( resource result, int field_offset)

mysql_field_len() retorna o tamanho do campo especificado.

Para compatibilidade com versões anteriores mysql_fieldlen() pode também ser usada. Esta função está depreciada.

mysql_field_name

(PHP 3, PHP 4 )

mysql_field_name --  Retorna o nome do campo especificado no resultado de uma query

Descrição

string mysql_field_name ( resource result, int field_index)

mysql_field_name() retorna o nome do campo do índice especificado. result deve ser um identificador de resultado(de uma query) valido e field_index é o índice do campo.

Nota: field_index começa em 0.

Dica. O índice do terceiro campo deve ser 2, o índice do quarto campo deve ser 3 e assim em diante.

Exemplo 1. Exemplo mysql_field_name()

/* A tabela users consiste de três campos:
 *   user_id
 *   username
 *   password.
 */
$link = mysql_connect('localhost', "mysql_user", "mysql_password");
mysql_select_db($dbname, $link)
    or die("Could not set $dbname: " . mysql_error());
$res = mysql_query("select * from users", $link);

echo mysql_field_name($res, 0) . "\n";
echo mysql_field_name($res, 2);

O exemplo acima deve produzir a seguinte saída:
user_id
password

Para compatibilidade com versões anteriores mysql_fieldname() também pode ser usada. Esta função está depreciada.

mysql_field_seek

(PHP 3, PHP 4 )

mysql_field_seek --  Move o ponteiro do resultado para um campo especificado

Descrição

int mysql_field_seek ( resource result, int field_offset)

Move o ponteiro para o índice especificado. Se a próxima chamada a mysql_fetch_field() não incluir um índice do campo, o índice especificado em mysql_field_seek() será retornado.

Veja também: mysql_fetch_field().

mysql_field_table

(PHP 3, PHP 4 )

mysql_field_table --  Retorna o nome da tabela onde esta o campo especificado

Descrição

string mysql_field_table ( resource result, int field_offset)

Retorna o nome da tabela onde esta o campo especificado.

Para compatibilidade com versões anteriores mysql_fieldtable() também pode ser usada. Esta função está depreciada.

mysql_field_type

(PHP 3, PHP 4 )

mysql_field_type --  Retorna o tipo do campo especificado em um resultado de query

Descrição

string mysql_field_type ( resource result, int field_offset)

mysql_field_type() é similar a mysql_field_name(). Os argumentos são identicos, mas ao invés é retornado o tipo do campo. O tipo do campo será um de "int", "real", "string", "blob", e outros detalhados na documentação do MySQL.

Exemplo 1. Tipos de campo do MySQL

<?php
    mysql_connect("localhost", "mysql_username", "mysql_password");
    mysql_select_db("mysql");
    $result = mysql_query("SELECT * FROM func");
    $fields = mysql_num_fields($result);
    $rows   = mysql_num_rows($result);
    $table = mysql_field_table($result, 0);
    echo "Your '".$table."' table has ".$fields." fields and ".$rows." record(s)\n";
    echo "The table has the following fields:\n";
    for ($i=0; $i < $fields; $i++) {
        $type  = mysql_field_type($result, $i);
        $name  = mysql_field_name($result, $i);
        $len   = mysql_field_len($result, $i);
        $flags = mysql_field_flags($result, $i);
        echo $type." ".$name." ".$len." ".$flags."\n";
    }
    mysql_free_result($result);
    mysql_close();
?>

A tabela acima irá produzir a seguinte saída:

Your 'func' table has 4 fields and 1 record(s)
The table has the following fields:
string name 64 not_null primary_key binary
int ret 1 not_null
string dl 128 not_null
string type 9 not_null enum

Para compatibilidade com versões anteriores mysql_fieldtype() também pode ser usada. Esta função está depreciada.

mysql_free_result

(PHP 3, PHP 4 )

mysql_free_result -- Libera a memória do resultado de uma query

Descrição

bool mysql_free_result ( resource result)

mysql_free_result() irá liberar toda a memória usada com o identificador de resultado result.

mysql_free_result() somente precisa ser chamado se você esta preocupado em quanta memória esta sendo usada para query num grande conjunto de resultados. Toda a memória usada do resultado é liberada automaticamente ao final da execução do script.

Retorna TRUE em caso de sucesso ou FALSE em falhas.

Para compatibilidade com versões anteriores mysql_freeresult() também pode ser usada. Esta função está depreciada.

mysql_get_client_info

(PHP 4 >= 4.0.5)

mysql_get_client_info -- Retorna informação da versão do cliente MySQL

Descrição

string mysql_get_client_info ( void)

mysql_get_client_info() retorna uma string que representa a versão da biblioteca do cliente.

Exemplo 1. Exemplo mysql_get_client_info

<?php
    printf ("MySQL client info: %s\n", mysql_get_client_info());
?>

O exemplo acima deve produzir a seguinte saída:

MySQL client info: 3.23.39

Veja também: mysql_get_host_info(), mysql_get_proto_info() e mysql_get_server_info().

mysql_get_host_info

(PHP 4 >= 4.0.5)

mysql_get_host_info -- Retorna informação sobre o host do MySQL

Descrição

string mysql_get_host_info ( [resource link_identifier])

mysql_get_host_info() retorna uma string descrevendo o tipo de conexão em uso para a conexão link_identifier, incluindo o nome de host do servidor. Se o parâmetro link_identifier é omitido, a ultima conexão aberta é usada.

Exemplo 1. Exemplo mysql_get_host_info

<?php
    mysql_connect("localhost", "mysql_user", "mysql_password") or
        die("Não pude conectar: " . mysql_error());
    printf ("MySQL host info: %s\n", mysql_get_host_info());
?>

O exemplo acima deve produzir a seguinte saída:

MySQL host info: Localhost via UNIX socket

Veja também: mysql_get_client_info(), mysql_get_proto_info() e mysql_get_server_info().

mysql_get_proto_info

(PHP 4 >= 4.0.5)

mysql_get_proto_info -- Retorna informação do protocolo do MySQL

Descrição

int mysql_get_proto_info ( [resource link_identifier])

mysql_get_proto_info() retorna a versão do protocolo usada pela conexão link_identifier. Se link_identifier é omitido, a última conexão aberta é usada.

Exemplo 1. Exemplo mysql_get_proto_info

<?php
    mysql_connect("localhost", "mysql_user", "mysql_password") or
        die("Não pude conectar: " . mysql_error());
    printf ("MySQL protocol version: %s\n", mysql_get_proto_info());
?>

O exemplo acima deve produzir a seguinte saída:

MySQL protocol version : 10

Veja também: mysql_get_client_info(), mysql_get_host_info() and mysql_get_server_info().

mysql_get_server_info

(PHP 4 >= 4.0.5)

mysql_get_server_info -- Retorna informação do servidor MySQL

Descrição

string mysql_get_server_info ( [resource link_identifier])

mysql_get_server_info() retorna a versão do servidor usado para a conexão link_identifier. Se link_identifier é omitido, a última conexão aberta é usada.

Exemplo 1. Exemplo mysql_get_server_info

<?php
    mysql_connect("localhost", "mysql_user", "mysql_password") or
        die("Não pude conectar: " . mysql_error());
    printf ("MySQL server version: %s\n", mysql_get_server_info());
?>

O exemplo acima deve produzir a seguinte saída:

MySQL server version: 4.0.1-alpha

Veja também: mysql_get_client_info(), mysql_get_host_info() e mysql_get_proto_info().

mysql_info

(PHP 4 >= 4.3.0)

mysql_info --  Retorna informação sobre a última query

Descrição

string mysql_info ( [resource link_identifier])

mysql_info() retorna informação detalhada sobre a última query usando o link_identifier dado. Se link_identifier não é especificado, a última conexão aberta é usada.

mysql_info() retorna uma string para todos os itens listados abaixo. Para todos os outros FALSE. O formato da string depende do comando dado.

Exemplo 1. Comandos Importantes do MySQL

INSERT INTO ... SELECT ...
String format: Records: 23 Duplicates: 0 Warnings: 0 
INSERT INTO ... VALUES (...),(...),(...)...
String format: Records: 37 Duplicates: 0 Warnings: 0 
LOAD DATA INFILE ...
String format: Records: 42 Deleted: 0 Skipped: 0 Warnings: 0 
ALTER TABLE
String format: Records: 60 Duplicates: 0 Warnings: 0 
UPDATE
String format: Rows matched: 65 Changed: 65 Warnings: 0
Os números são somente para fim de ilustração, os seus valores irão corresponder a query.

Nota: mysql_info() retorna um valor diferente de FALSE para os comandos INSERT ... VALUES somente se multiplas listas de valores são especificadas no comando.

Veja também: mysql_affected_rows()

mysql_insert_id

(PHP 3, PHP 4 )

mysql_insert_id --  Retorna o ID gerado da operação INSERT anterior

Descrição

int mysql_insert_id ( [resource link_identifier])

mysql_insert_id() returna o ID gerado para um campo AUTO_INCREMENT pela ultima query INSERT usando o link_identifier dado. Se link_identifier não é especificado, a ultima conexão aberta é usada.

mysql_insert_id() retorna 0 se a query anterior não gerou um valor AUTO_INCREMENT. Se você precisa salvar o valor para depois, tenha certeza de chamar mysql_insert_id() imediatamente depois da query que gerou o valor.

Nota: O valor da função SQL do MySQL LAST_INSERT_ID() sempre contém o mais recente valor AUTO_INCREMENT gerado, e não é reiniciado entre as query.

Atenção

mysql_insert_id() converte o tipo de retorno nativo do MySQL C API mysql_insert_id() para o tipo long (nomeado int no PHP). Se a sua coluna AUTO_INCREMENT tem um tipo BIGINT, o valor retornado por mysql_insert_id() será incorreto. Ao invés, use a função interna SQL do MySQL LAST_INSERT_ID() numa query SQL.

Exemplo 1. Exemplo mysql_insert_id

<?php
    mysql_connect("localhost", "mysql_user", "mysql_password") or
        die("Não pude conectar: " . mysql_error());
    mysql_select_db("mydb");

    mysql_query("INSERT INTO mytable (product) values ('kossu')");
    printf ("O ultimo registro incluído tem id %d\n", mysql_insert_id());
?>

Veja também: mysql_query().

mysql_list_dbs

(PHP 3, PHP 4 )

mysql_list_dbs --  Lista os bancos de dados disponiveis o servidor do MySQL

Descrição

resource mysql_list_dbs ( [resource link_identifier])

mysql_list_dbs() irá retorna um ponteiro de resultado contendo os bancos de dados disponiveis do servidor MySQL atual. Use a função mysql_tablename() para atravessar este ponteiro de resultado, ou qualquer função para o resultado das tabelas.

Exemplo 1. Exemplo mysql_list_dbs()

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$db_list = mysql_list_dbs($link);

while ($row = mysql_fetch_object($db_list)) {
    echo $row->Database . "\n";
}
?>

O exemplo acima deve produzir a seguinte saída:
database1
database2
database3
...

Nota: O codigo acima trabalha facil com mysql_fetch_row() ou outras funções similares.

Para compatibilidade com as versões anteriores mysql_listdbs() também pode ser usada. Esta função esta depreciada.

Veja também mysql_db_name().

mysql_list_fields

(PHP 3, PHP 4 )

mysql_list_fields -- Lista os campos de uma tabela

Descrição

resource mysql_list_fields ( string database_name, string table_name [, resource link_identifier])

mysql_list_fields() retorna informação sobre a tabela dada. Os argumentos são o nome do banco de dados e da tabela. Um ponteiro de resultado é retornado o qual pode ser usado com mysql_field_flags(), mysql_field_len(), mysql_field_name(), e mysql_field_type().

Exemplo 1. Exemplo mysql_list_fields()

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');

$fields = mysql_list_fields("database1", "table1", $link);
$columns = mysql_num_fields($fields);

for ($i = 0; $i < $columns; $i++) {
    echo mysql_field_name($fields, $i) . "\n";
}

O exemplo acima deve produzir a seguinte saída:
field1
field2
field3
...

Para compatibilidade com versões anteriores mysql_listfields() também pode ser usada. Esta função esta depreciada.

mysql_list_processes

(PHP 4 >= 4.3.0)

mysql_list_processes -- Lista os processos MySQL

Descrição

resource mysql_list_processes ( [resource link_identifier])

mysql_list_processes() retorna um ponteiro de resultado descrevendo as threads atuais do servidor.

Exemplo 1. Exemplo mysql_list_processes()

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');

$result = mysql_list_processes($link);
while ($row = mysql_fetch_row($result)){
    printf("%s %s %s %s %s\n", $row["Id"], $row["Host"], $row["db"],
       $row["Command"], $row["Time"]);
}
mysql_free_result ($result);
?>

O exemplo acima deve produzir a seguinte saída:
1 localhost test Processlist 0
4 localhost mysql sleep 5

Veja também: mysql_thread_id()

mysql_list_tables

(PHP 3, PHP 4 )

mysql_list_tables -- Lista as tabelas em um banco de dados MySQL

Descrição

resource mysql_list_tables ( string database [, resource link_identifier])

mysql_list_tables() leva o nome de um banco de dados e retorna um ponteiro de resultado muito parecido com a função mysql_query(). Você pode usar a função mysql_tablename() para extrair os nomes atuais das tabela do ponteiro do resultado, ou qualquer outra função com o resultado de tabela como mysql_fetch_assoc().

O parametro database é o nome do banco de dados de onde obter a lista de tabelas. Se a função mysql_list_tables() falhar, retorna FALSE.

Para compatibilidade com versões anteriores, o apelido chamado mysql_listtables() pode ser usado. Esta depreciada e seu uso não é recomendado.

Exemplo 1. Exemplo mysql_list_tables

<?php
    $dbname = 'mysql_dbname';

    if (!mysql_connect('mysql_host', 'mysql_user', 'mysql_password')) {
        print 'Não pude conectar com o MySQL';
        exit;
    }

    $result = mysql_list_tables($dbname);
    
    if (!$result) {
        print "DB Error, não pude listar as tabelas\n";
        print 'MySQL Error: ' . mysql_error();
        exit;
    }
    
    while ($row = mysql_fetch_row($result)) {
        print "Table: $row[0]\n";
    }

    mysql_free_result($result);
?>

Veja também: mysql_list_dbs(), e mysql_tablename().

mysql_num_fields

(PHP 3, PHP 4 )

mysql_num_fields -- Retorna o número de campos no resulatdo

Descrição

int mysql_num_fields ( resource result)

mysql_num_fields() retorna o número de campos em um conjunto de resultado.

Veja também: mysql_select_db(), mysql_query(), mysql_fetch_field(), mysql_num_rows().

Para compatibilidade com versões anteriores mysql_numfields() também pode ser usada. Esta função está depreciada.

mysql_num_rows

(PHP 3, PHP 4 )

mysql_num_rows -- Retorna o número de linhas em um resultado

Descrição

int mysql_num_rows ( resource result)

mysql_num_rows() retorna o número de linhas em um resultado. Este comando é valido apenas para o SELECT. Para obter o número de linhas afetadas por INSERT, UPDATE ou DELETE, use mysql_affected_rows().

Exemplo 1. Exemplo mysql_num_rows()

<?php

$link = mysql_connect("localhost", "mysql_user", "mysql_password");
mysql_select_db("database", $link);

$result = mysql_query("SELECT * FROM table1", $link);
$num_rows = mysql_num_rows($result);

echo "$num_rows Rows\n";

?>

Nota: Se você usar mysql_unbuffered_query(), mysql_num_rows() não irá retornar o valor correto até que todas as linhas do resultado sejam obtidas.

Veja também: mysql_affected_rows(), mysql_connect(), mysql_data_seek(), mysql_select_db(), e mysql_query().

Para compatibilidade com versões anteriores mysql_numrows() também pode ser usada. Esta função está depreciada.

mysql_pconnect

(PHP 3, PHP 4 )

mysql_pconnect --  Abre uma conexão persistente com um servidor MySQL

Descrição

resource mysql_pconnect ( [string server [, string username [, string password [, int client_flags]]]])

Retorna um identificador de link persistente ao MySQL em caso de sucesso, ou FALSE se houver erro.

mysql_pconnect() estabelece uma conexão com o servidor MySQL. Os seguintes padrões são assumidos para os parametros opcionais que estiverem faltando: server = 'localhost:3306', username = nome do usuário que for dono do processo do servidor e password = password vazio. O parametro client_flags pode ser uma combinação das constantes MYSQL_CLIENT_SSL, MYSQL_CLIENT_COMPRESS, MYSQL_CLIENT_IGNORE_SPACE ou MYSQL_CLIENT_INTERACTIVE.

O parametro server pode também incluir um numero de porta. Ex: "hostname:port" ou um caminho para um socket ex: ":/path/to/socket" para o localhost.

Nota: Suporte a ":port" foi adicionado em 3.0B4.

Suporte a ":/path/to/socket" foi adicionado em 3.0.10.

mysql_pconnect() aje muito parecido com mysql_connect() com duas maiores diferenças.

Primeira,ao conectar, a função primeiro irá tentar encontrar um conexão persistente que já esteja aberta com o mesmo servidor, nome de usuário e senha. Se uma é encontrada, um identificador para ela será retornada ao invés de abrir uma nova conexão.

Segundo, a conexão com o servidor SQL não será fechada quando termina a execução do script. Ao invés, a conexão continuará aberta para uso futuro(mysql_close() não irá fechar conexões abertas por mysql_pconnect()).

O parametro opcional client_flags tornou-se disponivel no PHP 4.3.0.

Este tipo de conexão é portanto chamada 'persistente'.

Nota: Note que este tipo de conexão funciona somente se você esta usando o PHP como módulo. Veja a seção Persistent Database Connections para maiores informações.

Atenção

Usar conexões persistentes pode requerer alguns ajustes na sua configuração do Apache e MySQL para assegurar que você não ultrapasse o limite de conexões permitidos pelo MySQL.

mysql_ping

(PHP 4 >= 4.3.0)

mysql_ping -- Pinga uma conexão ou reconecta se não houver conexão

Descrição

bool mysql_ping ( [resource link_identifier])

mysql_ping() confere se uma conexão com o servidor esta ou não funcionando. Se ela caiu, uma reconexão automatica é tentada. Esta função pode ser usada por scripts que permanecem ociosos por um grande tempo, para conferir uqando o servidor fechou ou não a conexão e reconectar se necessário. mysql_ping() returna TRUE se a conexão com o servidor esta funcionando, em outro caso FALSE.

Veja também: mysql_thread_id(), mysql_list_processes().

mysql_query

(PHP 3, PHP 4 )

mysql_query -- Realiza uma query MySQL

Descrição

resource mysql_query ( string query [, resource link_identifier [, int result_mode]])

mysql_query() envia uma query para o banco de dados ativo no servidor da conexão informada em link_identifier. Se o parâmetro link_identifier não é especificado, a ultima conexão aberta é usada. Se nenhuma conexão esta aberta, a função tenta estabelecer uma conexão como mysql_connect() seja chamada sem argumentos e usa-a.

O parâmetro opcional result_mode pode ser MYSQL_USE_RESULT e MYSQL_STORE_RESULT. O seu padrão MYSQL_STORE_RESULT, assim seu resultado é colocado no buffer. Veja também mysql_unbuffered_query() para a sua contrapartida.

Nota: A string da query não deve terminar com ponto e virgula(;).

Somente para os comandos SELECT, SHOW, EXPLAIN ou DESCRIBE mysql_query() retorna um identificador de recurso ou FALSE se a query não foi executada corretamente. Para outros tipos de comandos SQL, mysql_query() retorna TRUE em caso de sucesso e FALSE em erro. Um valor não FALSE indica que a query foi legal e pode ser executada pelo servidor. Não indica nada sobre o número de linhas afetadas ou retornadas. É perfeitamente possível para uma query ser bem sucedida, mas não afetar linhas ou retornar linhas.

A seguinte query é sintaticamente invalida, assim mysql_query() falha e retorna FALSE:

Exemplo 1. mysql_query()

<php
$result = mysql_query("SELECT * WHERE 1=1")
    or die("Query invalida: " . mysql_error());
?>

A seguinte query é semanticamente invalida se my_col não é uma coluna da tabela my_tbl, assim mysql_query() falha e retorna FALSE:

Exemplo 2. mysql_query()

<?php
$result = mysql_query("SELECT my_col FROM my_tbl")
    or die ("Query invalida: " . mysql_error());
?>

mysql_query() irá também falhar e retornar FALSE se você não tiver permissão para acessar a tabela(s) referida(s) pela query.

Assumindo que a query seja bem sucedida, você pode chamar mysql_num_rows() para achar quantas linhas foram retornadas para um comando SELECT ou mysql_affected_rows() para achar quantas linhas foram afetadas por um comando DELETE, INSERT, REPLACE, ou UPDATE.

Somente para os comandos SELECT,SHOW,DESCRIBE ou EXPLAIN, mysql_query() retorna um novo identificador de resultado que você pode passar para mysql_fetch_array() e outras funções que lidam com resultados de tabelas. Quando você terminou de usar o resultado você pode liberar os recursos usados chamando mysql_free_result(). Embora a memória será automaticamente liberada ao final da execução do script.

Veja também: mysql_num_rows(), mysql_affected_rows(), mysql_unbuffered_query(), mysql_free_result(), mysql_fetch_array(), mysql_fetch_row(), mysql_fetch_assoc(), mysql_result(), mysql_select_db(), and mysql_connect().

mysql_real_escape_string

(PHP 4 >= 4.3.0)

mysql_real_escape_string --  Escapa os caracteres especiais numa string para usar em um comando SQL, levando em conta o conjunto atual de caracteres.

Descrição

string mysql_real_escape_string ( string unescaped_string [, resource link_identifier])

Esta função irá escapar os caracteres especiais em unescaped_string, levando em conta o atual conjunto de caracteres da conexão, assim é seguro coloca-la em mysql_query().

Nota: mysql_real_escape_string() não escapa % e _.

Exemplo 1. Exemplo mysql_real_escape_string()

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$item = "Zak's and Derick's Laptop";
$escaped_item = mysql_real_escape_string($item);
printf ("Escaped string: %s\n", $escaped_item);
?>

O exemplo acima deve produzir a seguinte saída:
Escaped string: Zak\'s and Derick\'s Laptop

Veja também: mysql_escape_string(), mysql_character_set_name().

mysql_result

(PHP 3, PHP 4 )

mysql_result -- Retorna dados do resultado

Descrição

mixed mysql_result ( resource result, int row [, mixed field])

mysql_result() retorna o conteúdo de uma célula do resultado MySQL. O argumento field(campo) pode ser o índice do campo, o nome do campo, o a tabela ponto o nome do campo(tabela.campo). Se o nome da coluna usa apelido ('select foo as bar from...'), use o apelido ao invés do nome da coluna.

Quando trabalhando com um grande conjunto de resultado, você deve considerar o uso de uma das funções que retornam toda a linha(especificadas abaixo). Estas funções retornam o conteúdo de multiplas células em uma chamada de função, elas são MUITO mais rapidas do que mysql_result(). Também note que especificar um índice do campo é muito mais rapido do que especificar o nome do campo ou tabela.campo.

Chamadas a mysql_result() não devem ser misturadas com chamadas a outras funções que lidam com o conjunto de resultados.

Alternativas de alta performance recomendadas: mysql_fetch_row(), mysql_fetch_array(), e mysql_fetch_object().

mysql_select_db

(PHP 3, PHP 4 )

mysql_select_db -- Seleciona um banco de dados MySQL

Descrição

bool mysql_select_db ( string database_name [, resource link_identifier])

Retorna TRUE em caso de sucesso ou FALSE em falhas.

mysql_select_db() define o banco de dados ativo no servidor que é associado ao identificador de conexão(link_identifier) especificado. Se nenhum identificador de conexão é especificado, a ultima conexão aberta é assumida. Se nenhuma conexão esta aberta, a função irá tentar abrir uma conexão como se mysql_connect() fosse chamada sem argumentos e usa-la.

todas as próximas chamadas a mysql_query() serão feitas no banco de dados ativo.

Veja também: mysql_connect(), mysql_pconnect(), e mysql_query().

Para compatibilidade com versões anteriores mysql_selectdb() também pode ser usada. Esta função esta depreciada.

mysql_stat

(PHP 4 >= 4.3.0)

mysql_stat -- Retorna o status atual do sistema

Descrição

string mysql_stat ( [resource link_identifier])

mysql_stat() returna o status atual do servidor.

Nota: mysql_stat() atualmente retorna somente o satus para uptime, threads, queries, open tables, flush tables e queries por segundos. Para uma lista completa de outras variáveis de staus você tem que usar o comando SQL SHOW STATUS.

Exemplo 1. Exemplo mysql_stat()

<?php
$link = mysql_connect('localhost', "mysql_user", "mysql_password");
$status = explode('  ',mysql_stat($link));
print_r($status);
?>

O exemplo acima deve produzir a seguinte saída:
Array
(
    [0] => Uptime: 5380
    [1] => Threads: 2
    [2] => Questions: 1321299
    [3] => Slow queries: 0
    [4] => Opens: 26
    [5] => Flush tables: 1
    [6] => Open tables: 17
    [7] => Queries per second avg: 245.595
)

mysql_tablename

(PHP 3, PHP 4 )

mysql_tablename -- Retorna o nome da tabela do campo

Descrição

string mysql_tablename ( resource result, int i)

mysql_tablename() usa um ponteiro de resultado retornado por mysql_list_tables() ou um índice inteiro e retorna o nome da tabela A função mysql_num_rows() pode ser usada para determinar o número de tabelas no ponteiro do resultado.

Exemplo 1. Exemplo mysql_tablename()

<?php
    mysql_connect("localhost", "mysql_user", "mysql_password");
    $result = mysql_list_tables("mydb");

    for ($i = 0; $i < mysql_num_rows($result); $i++)
        printf ("Table: %s\n", mysql_tablename($result, $i));

    mysql_free_result($result);
?>

Veja também: mysql_list_tables().

mysql_thread_id

(PHP 4 >= 4.3.0)

mysql_thread_id -- Returna o ID da thread atual

Descrição

int mysql_thread_id ( [resource link_identifier])

mysql_thread_id() retorna o ID da thread atual. Se a conexão for perdida e você reconectar com mysql_ping(), o ID da thread irá muda. Isto indica que você não deve guardar o pegar ID e guarda-lo para depois. Você deve pega-lo quando você precisar dele.

Exemplo 1. Exemplo mysql_thread_id()

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$thread_id = mysql_thread_id($link);
if ($thread_id){
    printf ("current thread id is %d\n", $thread_id);
}
?>

O exemplo acima deve produzir a seguinte saída:
current thread id is 73

Veja também: mysql_ping(), mysql_list_processes().

mysql_unbuffered_query

(PHP 4 >= 4.0.6)

mysql_unbuffered_query --  Envia uma query para o MySQL, sem retornar e colocar em buffer as linhas do resultado

Descrição

resource mysql_unbuffered_query ( string query [, resource link_identifier [, int result_mode]])

mysql_unbuffered_query() envia uma query SQL para MySQL, sem retornar e colocar em buffer as linhas do resultado automaticamente, como mysql_query() faz. por um lado, isto salva uma quantidade considerável de memória em query que produzem um resultado grandes. por outro lado, você pode começãr a trbalhar com o resultado imediatamente após a primeira linha ser retornada: você não tem que esperar que toda a query SQL seja realizada. Quando usar multiplas conexões com o banco de dados, você deve especificar o parametro opcional link_identifier.

O parametro opcional result_mode pode ser MYSQL_USE_RESULT e MYSQL_STORE_RESULT. O padrão é MYSQL_USE_RESULT, assim o resultado não é colocado no buffer. Veja também mysql_query() para a contraparte desta função.

Nota: Os beneficios de mysql_unbuffered_query() vem com um custo: você não pode usar mysql_num_rows() no resultado retornado por mysql_unbuffered_query(). Você tmbém tem que pegar todas as linhas de uma query SQL sem buffer antes de poder enviar uma nova query SQL para o MySQL.

Veja também: mysql_query().

LXIV. Mohawk Software session handler functions

Introdução

msession is an interface to a high speed session daemon 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 server software itself can be found at http://www.mohawksoft.com/phoenix/.

Nota: This extension is not available on Windows platforms.


Requisitos


Instalação

To enable Msession support configure PHP --with-msession[=DIR], where DIR is the Msession install directory.


Configuração durante execução


Tipos Resource


Constantes Predefinidas

Índice
msession_connect -- Connect to msession server
msession_count -- Get session count
msession_create -- Create a session
msession_destroy -- Destroy a session
msession_disconnect -- Close connection to msession server
msession_find -- Find value
msession_get_array -- Get array of ... ?
msession_get -- Get value from session
msession_getdata -- Get data ... ?
msession_inc -- Increment value in session
msession_list -- List ... ?
msession_listvar -- List sessions with variable
msession_lock -- Lock a session
msession_plugin -- Call an escape function within the msession personality plugin
msession_randstr -- Get random string
msession_set_array -- Set array of ...
msession_set -- Set value in session
msession_setdata -- Set data ... ?
msession_timeout -- Set/get session timeout
msession_uniq -- Get uniq id
msession_unlock -- Unlock a session

msession_connect

(PHP 4 >= 4.2.0)

msession_connect -- Connect to msession server

Description

bool msession_connect ( string host, string port)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

msession_count

(PHP 4 >= 4.2.0)

msession_count -- Get session count

Description

int msession_count ( void)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

msession_create

(PHP 4 >= 4.2.0)

msession_create -- Create a session

Description

bool msession_create ( string session)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

msession_destroy

(PHP 4 >= 4.2.0)

msession_destroy -- Destroy a session

Description

bool msession_destroy ( string name)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

msession_disconnect

(PHP 4 >= 4.2.0)

msession_disconnect -- Close connection to msession server

Description

void msession_disconnect ( void)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

msession_find

(PHP 4 >= 4.2.0)

msession_find -- Find value

Description

array msession_find ( string name, string value)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

msession_get_array

(PHP 4 >= 4.2.0)

msession_get_array -- Get array of ... ?

Description

array msession_get_array ( string session)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

msession_get

(PHP 4 >= 4.2.0)

msession_get -- Get value from session

Description

string msession_get ( string session, string name, string value)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

msession_getdata

(no version information, might be only in CVS)

msession_getdata -- Get data ... ?

Description

string msession_getdata ( string session)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

msession_inc

(PHP 4 >= 4.2.0)

msession_inc -- Increment value in session

Description

string msession_inc ( string session, string name)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

msession_list

(PHP 4 >= 4.2.0)

msession_list -- List ... ?

Description

array msession_list ( void)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

msession_listvar

(PHP 4 >= 4.2.0)

msession_listvar -- List sessions with variable

Description

array msession_listvar ( string name)

Returns an associative array of value, session for all sessions with a variable named name.

Used for searching sessions with common attributes.

msession_lock

(PHP 4 >= 4.2.0)

msession_lock -- Lock a session

Description

int msession_lock ( string name)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

msession_plugin

(PHP 4 >= 4.2.0)

msession_plugin -- Call an escape function within the msession personality plugin

Description

string msession_plugin ( string session, string val [, string param])

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

msession_randstr

(PHP 4 >= 4.2.0)

msession_randstr -- Get random string

Description

string msession_randstr ( int param)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

msession_set_array

(PHP 4 >= 4.2.0)

msession_set_array -- Set array of ...

Description

bool msession_set_array ( string session, array tuples)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

msession_set

(PHP 4 >= 4.2.0)

msession_set -- Set value in session

Description

bool msession_set ( string session, string name, string value)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

msession_setdata

(no version information, might be only in CVS)

msession_setdata -- Set data ... ?

Description

bool msession_setdata ( string session, string value)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

msession_timeout

(PHP 4 >= 4.2.0)

msession_timeout -- Set/get session timeout

Description

int msession_timeout ( string session [, int param])

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

msession_uniq

(PHP 4 >= 4.2.0)

msession_uniq -- Get uniq id

Description

string msession_uniq ( int param)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

msession_unlock

(PHP 4 >= 4.2.0)

msession_unlock -- Unlock a session

Description

int msession_unlock ( string session, int key)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

LXV. muscat functions

Introdução

Atenção

Este módulo é EXPERIMENTAL. Isso quer dizer que o comportamento neste módulo --- incluindo suas funções e seus nomes, e TUDO mais que está documentado sobre esse módulo --- poderá mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use este módulo por sua própria conta e risco.

Índice
muscat_close -- Shuts down the muscat session and releases any memory back to PHP.
muscat_get -- Gets a line back from the core muscat API.
muscat_give -- Sends string to the core muscat API
muscat_setup_net -- Creates a new muscat session and returns the handle.
muscat_setup -- Creates a new muscat session and returns the handle.

muscat_close

(4.0.5 - 4.2.3 only)

muscat_close -- Shuts down the muscat session and releases any memory back to PHP.

Description

int muscat_close ( resource muscat_handle)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

[Not back to the system, note!]

muscat_get

(4.0.5 - 4.2.3 only)

muscat_get -- Gets a line back from the core muscat API.

Description

string muscat_get ( resource muscat_handle)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

Returns a literal FALSE when there is no more to get (as opposed to ""). Use === FALSE or !== FALSE to check for this.

muscat_give

(4.0.5 - 4.2.3 only)

muscat_give -- Sends string to the core muscat API

Description

int muscat_give ( resource muscat_handle, string string)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

muscat_setup_net

(4.0.5 - 4.2.3 only)

muscat_setup_net -- Creates a new muscat session and returns the handle.

Description

resource muscat_setup_net ( string muscat_host, int port)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

muscat_host is the hostname to connect to port is the port number to connect to - actually takes exactly the same args as fsockopen

muscat_setup

(4.0.5 - 4.2.3 only)

muscat_setup -- Creates a new muscat session and returns the handle.

Description

resource muscat_setup ( int size [, string muscat_dir])

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

Size is the ammount of memory in bytes to allocate for muscat muscat_dir is the muscat installation dir e.g. "/usr/local/empower", it defaults to the compile time muscat directory

LXVI. Network Functions

Introdução


Requisitos

Nenhuma biblioteca externa é necessária para compilar esta extensão.


Instalação

Não há nenhuma instalação nescessária para utilizar estas funções, elas fazem parte do núcleo do PHP.


Configuração durante execução

O comportamento dessas funções podem ser modificado pelas configurações do php.ini.

Tabela 1. Network Configuration Options

Name Default Changeable
define_syslog_variables "0" PHP_INI_ALL
For further details and definition of the PHP_INI_* constants see ini_set().

Here is a short explanation of the configuration directives.

define_syslog_variables boolean

Whether or not to define the various syslog variables (e.g. $LOG_PID, $LOG_CRON, etc.). Turning it off is a good idea performance-wise. At runtime, you can define these variables by calling define_syslog_variables().


Tipos Resource

Esta extensão não possui nenhum tipo resource.


Constantes Predefinidas

As constantes listadas abaixo estão sempre disponíveis como parte do núcleo do PHP.

Tabela 2. openlog() Options

Constant Description
LOG_CONS if there is an error while sending data to the system logger, write directly to the system console
LOG_NDELAY open the connection to the logger immediately
LOG_ODELAY (default) delay opening the connection until the first message is logged
LOG_PERROR print log message also to standard error
LOG_PID include PID with each message

Tabela 3. syslog() Priorities (in descending order)

Constant Description
LOG_EMERG system is unusable
LOG_ALERT action must be taken immediately
LOG_CRIT critical conditions
LOG_ERR error conditions
LOG_WARNING warning conditions
LOG_NOTICE normal, but significant, condition
LOG_INFO informational message
LOG_DEBUG debug-level message

Tabela 4. dns_get_record() Options

Constant Description
DNS_A IPv4 Address Resource
DNS_MX Mail Exchanger Resource
DNS_CNAME Alias (Canonical Name) Resource
DNS_NS Authoritative Name Server Resource
DNS_PTR Pointer Resource
DNS_HINFO Host Info Resource (See RFC 1010 for the meaning of these values)
DNS_SOA Start of Authority Resource
DNS_TXT Text Resource
DNS_ANY Any Resource Record. On most systems this returns all resource records, however it should not be counted upon for critical uses. Try DNS_ALL instead.
DNS_AAAA IPv6 Address Resource
DNS_ALL Itteratively query the name server for each available record type.
Índice
checkdnsrr --  Check DNS records corresponding to a given Internet host name or IP address
closelog -- Close connection to system logger
debugger_off -- Disable internal PHP debugger (PHP 3)
debugger_on -- Enable internal PHP debugger (PHP 3)
define_syslog_variables -- Initializes all syslog related constants
dns_check_record -- Synonym for checkdnsrr()
dns_get_mx -- Synonym for getmxrr()
dns_get_record --  Fetch DNS Resource Records associated with a hostname
fsockopen --  Open Internet or Unix domain socket connection
gethostbyaddr --  Get the Internet host name corresponding to a given IP address
gethostbyname --  Get the IP address corresponding to a given Internet host name
gethostbynamel --  Get a list of IP addresses corresponding to a given Internet host name
getmxrr --  Get MX records corresponding to a given Internet host name
getprotobyname --  Get protocol number associated with protocol name
getprotobynumber --  Get protocol name associated with protocol number
getservbyname --  Get port number associated with an Internet service and protocol
getservbyport --  Get Internet service which corresponds to port and protocol
ip2long --  Converts a string containing an (IPv4) Internet Protocol dotted address into a proper address.
long2ip --  Converts an (IPv4) Internet network address into a string in Internet standard dotted format
openlog -- Open connection to system logger
pfsockopen --  Open persistent Internet or Unix domain socket connection
socket_get_status --  Alias of stream_get_meta_data().
socket_set_blocking -- Alias for stream_set_blocking()
socket_set_timeout -- Alias for stream_set_timeout()
syslog -- Generate a system log message

checkdnsrr

(PHP 3, PHP 4 )

checkdnsrr --  Check DNS records corresponding to a given Internet host name or IP address

Description

int checkdnsrr ( string host [, string type])

Searches DNS for records of type type corresponding to host. Returns TRUE if any records are found; returns FALSE if no records were found or if an error occurred.

type may be any one of: A, MX, NS, SOA, PTR, CNAME, AAAA, or ANY. The default is MX.

Host may either be the IP address in dotted-quad notation or the host name.

Nota: AAAA type added with PHP 4.3.0

Nota: This function is not implemented on Windows platforms. Try the PEAR class Net_DNS.

See also getmxrr(), gethostbyaddr(), gethostbyname(), gethostbynamel(), and the named(8) manual page.

closelog

(PHP 3, PHP 4 )

closelog -- Close connection to system logger

Description

int closelog ( void)

closelog() closes the descriptor being used to write to the system logger. The use of closelog() is optional.

See also define_syslog_variables(), syslog() and openlog().

debugger_off

(PHP 3)

debugger_off -- Disable internal PHP debugger (PHP 3)

Description

int debugger_off ( void)

Disables the internal PHP debugger. This function is only available in PHP 3.

For more information see the appendix on Debugging PHP.

debugger_on

(PHP 3)

debugger_on -- Enable internal PHP debugger (PHP 3)

Description

int debugger_on ( string address)

Enables the internal PHP debugger, connecting it to address. This function is only available in PHP 3.

For more information see the appendix on Debugging PHP.

define_syslog_variables

(PHP 3, PHP 4 )

define_syslog_variables -- Initializes all syslog related constants

Description

void define_syslog_variables ( void)

Initializes all constants used in the syslog functions.

See also openlog(), syslog() and closelog().

dns_check_record

(PHP 5 CVS only)

dns_check_record -- Synonym for checkdnsrr()

Description

int dns_check_record ( string host [, string type])

Check DNS records corresponding to a given Internet host name or IP address

dns_get_mx

(PHP 5 CVS only)

dns_get_mx -- Synonym for getmxrr()

Description

int getmxrr ( string hostname, array mxhosts [, array &weight])

Get MX records corresponding to a given Internet host name.

dns_get_record

(PHP 5 CVS only)

dns_get_record --  Fetch DNS Resource Records associated with a hostname

Description

array dns_get_record ( string hostname [, int type [, array &authns, array &addtl]])

Nota: This function is not implemented on Windows platforms. Try the PEAR class Net_DNS.

This function returns an array of associative arrays. Each associative array contains at minimum the following keys:

Tabela 1. Basic DNS attributes

Attribute Meaning
host The record in the DNS namespace to which the rest of the associated data refers.
class dns_get_record() only returns Internet class records and as such this parameter will always return IN.
type String containing the record type. Additional attributes will also be contained in the resulting array dependant on the value of type. See table below.
ttl Time To Live remaining for this record. This will not equal the record's original ttl, but will rather equal the original ttl minus whatever length of time has passed since the authoritative name server was queried.

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 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 query, specify the optional type parameter. type may be any one of the following: DNS_A, DNS_CNAME, DNS_HINFO, DNS_MX, DNS_NS, DNS_PTR, DNS_SOA, DNS_TXT, DNS_AAAA, DNS_ALL or DNS_ANY. The default is DNS_ANY.

Nota: Because of excentricities in the performance of libresolv between platforms, DNS_ANY will not always return every record, the slower DNS_ALL will collect all records more reliably.

The optional third and fourth arguments to this function, authns and addtl are passed by reference and, if given, will be populated with Resource Records for the Authoritative Name Servers, and any Additional Records respectively. See the example below.

Tabela 2. Other keys in associative arrays dependant on 'type'

Type Extra Columns
A ip: An IPv4 addresses in dotted decimal notation.
MX pri: Priority of mail exchanger. Lower numbers indicate greater priority. target: FQDN of the mail exchanger. See also dns_get_mx().
CNAME target: FQDN of location in DNS namespace to which the record is aliased.
NS target: FQDN of the name server which is authoritative for this hostname.
PTR target: Location within the DNS namespace to which this record points.
TXT txt: Arbitrary string data associated with this record.
HINFO cpu: IANA number designating the CPU of the machine referenced by this record. os: IANA number designating the Operating System on the machine referenced by this record. See RFC 1010 for the meaning of these values.
SOA mname: FQDN of the machine from which the resource records orignated. rname: Email address of the administrative contain for this domain. serial: Serial # of this revision of the requested domain. refresh: Refresh interval (seconds) secondary name servers should use when updating remote copies of this domain. retry: Length of time (seconds) to wait after a failed refresh before making a second attempt. expire: Maximum length of time (seconds) a secondary DNS server should retain remote copies of the zone data without a successful refresh before discarding. minimum-ttl: Minimum length of time (seconds) a client can continue to use a DNS resolution before it should request a new resolution from the server. Can be overridden by individual resource records.
AAAA ipv6: IPv6 address

Nota: Per DNS standards, email addresses are given in user.host format (for example: hostmaster.example.com as opposed to hostmaster@example.com), be sure to check this value and modify if necessary before using it with a functions such as mail().

Exemplo 1. Using dns_get_record()

<?php
$result = dns_get_record("php.net");
print_r($result);
?>

/*
Produces ouput similar to the following:
----------------------------------------

Array
(
    [0] => Array
        (
            [host] => php.net
            [type] => MX
            [pri] => 5
            [target] => pair2.php.net
            [class] => IN
            [ttl] => 6765
        )

    [1] => Array
        (
            [host] => php.net
            [type] => A
            [ip] => 64.246.30.37
            [class] => IN
            [ttl] => 8125
        )

)
*/

Since it's very common to want the IP address of a mail server once the MX record has been resolved, dns_get_record() also returns an array in addtl which contains associate records. authns is returned as well conatining a list of authoritative name servers.

Exemplo 2. Using dns_get_record() and DNS_ANY

<?php
/* Request "ANY" record for php.net, 
   and create $authns and $addtl arrays
   containing list of name servers and
   any additional records which go with
   them */
$result = dns_get_record("php.net",DNS_ANY,$authns,$addtl);
print "Result = ";
print_r($result);
print "Auth NS = ";
print_r($authns);
print "Additional = ";
print_r($addtl);
?>

/*
Produces output similar to the following:
-----------------------------------------

Result = Array
(
    [0] => Array
        (
            [host] => php.net
            [type] => MX
            [pri] => 5
            [target] => pair2.php.net
            [class] => IN
            [ttl] => 6765
        )

    [1] => Array
        (
            [host] => php.net
            [type] => A
            [ip] => 64.246.30.37
            [class] => IN
            [ttl] => 8125
        )

)
Auth NS = Array
(
    [0] => Array
        (
            [host] => php.net
            [type] => NS
            [target] => remote1.easydns.com
            [class] => IN
            [ttl] => 10722
        )

    [1] => Array
        (
            [host] => php.net
            [type] => NS
            [target] => remote2.easydns.com
            [class] => IN
            [ttl] => 10722
        )

    [2] => Array
        (
            [host] => php.net
            [type] => NS
            [target] => ns1.easydns.com
            [class] => IN
            [ttl] => 10722
        )

    [3] => Array
        (
            [host] => php.net
            [type] => NS
            [target] => ns2.easydns.com
            [class] => IN
            [ttl] => 10722
        )

)
Additional = Array
(
    [0] => Array
        (
            [host] => pair2.php.net
            [type] => A
            [ip] => 216.92.131.5
            [class] => IN
            [ttl] => 6766
        )

    [1] => Array
        (
            [host] => remote1.easydns.com
            [type] => A
            [ip] => 64.39.29.212
            [class] => IN
            [ttl] => 100384
        )

    [2] => Array
        (
            [host] => remote2.easydns.com
            [type] => A
            [ip] => 212.100.224.80
            [class] => IN
            [ttl] => 81241
        )

    [3] => Array
        (
            [host] => ns1.easydns.com
            [type] => A
            [ip] => 216.220.40.243
            [class] => IN
            [ttl] => 81241
        )

    [4] => Array
        (
            [host] => ns2.easydns.com
            [type] => A
            [ip] => 216.220.40.244
            [class] => IN
            [ttl] => 81241
        )

)
*/

See also dns_get_mx(), and dns_check_record()

fsockopen

(PHP 3, PHP 4 )

fsockopen --  Open Internet or Unix domain socket connection

Description

int fsockopen ( string hostname, int port [, int errno [, string errstr [, float timeout]]])

Initiates a stream connection in the Internet (AF_INET, using TCP or UDP) or Unix (AF_UNIX) domain. For the Internet domain, it will open a TCP socket connection to hostname on port port. hostname may in this case be either a fully qualified domain name or an IP address. For UDP connections, you need to explicitly specify the protocol by prefixing hostname with 'udp://'. For the Unix domain, hostname will be used as the path to the socket, port must be set to 0 in this case. The optional timeout can be used to set a timeout in seconds for the connect system call.

Nota: If you need to set a timeout for reading/writing data over the socket, use socket_set_timeout(), as the timeout parameter to fsockopen() only applies while connecting the socket.

As of PHP 4.3.0, if you have compiled in OpenSSL support, you may prefix the hostname with either 'ssl://' or 'tls://' to use an SSL or TLS client connection over TCP/IP to connect to the remote host.

fsockopen() returns a file pointer which may be used together with the other file functions (such as fgets(), fgetss(), fputs(), fclose(), and feof()).

If the call fails, it will return FALSE and if the optional errno and errstr arguments are present they will be set to indicate the actual system level error that occurred in the system-level connect() call. If the value returned in errno is 0 and the function returned FALSE, it is an indication that the error occurred before the connect() call. This is most likely due to a problem initializing the socket. Note that the errno and errstr arguments will always be passed by reference.

Depending on the environment, the Unix domain or the optional connect timeout may not be available.

The socket will by default be opened in blocking mode. You can switch it to non-blocking mode by using socket_set_blocking().

Exemplo 1. fsockopen() Example

<?php
$fp = fsockopen ("www.example.com", 80, $errno, $errstr, 30);
if (!$fp) {
    echo "$errstr ($errno)<br>\n";
} else {
    fputs ($fp, "GET / HTTP/1.0\r\nHost: www.example.com\r\n\r\n");
    while (!feof($fp)) {
        echo fgets ($fp,128);
    }
    fclose ($fp);
}
?>
The example below shows how to retrieve the day and time from the UDP service "daytime" (port 13) in your own machine.

Exemplo 2. Using UDP connection

<?php
$fp = fsockopen("udp://127.0.0.1", 13, $errno, $errstr);
if (!$fp) {
    echo "ERROR: $errno - $errstr<br>\n";
} else {
    fwrite($fp,"\n");
    echo fread($fp, 26);
    fclose($fp);
}
?>

Atenção

UDP sockets will sometimes appear to have opened without an error, even if the remote host is unreachable. The error will only become apparent when you read or write data to/from the socket. The reason for this is because UDP is a "connectionless" protocol, which means that the operating system does not try to establish a link for the socket until it actually needs to send or receive data.

Nota: The timeout parameter was introduced in PHP 3.0.9 and UDP support was added in PHP 4.

See also pfsockopen(), socket_set_blocking(), socket_set_timeout(), fgets(), fgetss(), fputs(), fclose(), feof(), and the Curl extension.

gethostbyaddr

(PHP 3, PHP 4 )

gethostbyaddr --  Get the Internet host name corresponding to a given IP address

Description

string gethostbyaddr ( string ip_address)

Returns the host name of the Internet host specified by ip_address or a string containing the unmodified ip_address on failure.

See also gethostbyname().

gethostbyname

(PHP 3, PHP 4 )

gethostbyname --  Get the IP address corresponding to a given Internet host name

Description

string gethostbyname ( string hostname)

Returns the IP address of the Internet host specified by hostname or a string containing the unmodified hostname on failure.

See also gethostbyaddr().

gethostbynamel

(PHP 3, PHP 4 )

gethostbynamel --  Get a list of IP addresses corresponding to a given Internet host name

Description

array gethostbynamel ( string hostname)

Returns a list of IP addresses to which the Internet host specified by hostname resolves.

See also gethostbyname(), gethostbyaddr(), checkdnsrr(), getmxrr(), and the named(8) manual page.

getmxrr

(PHP 3, PHP 4 )

getmxrr --  Get MX records corresponding to a given Internet host name

Description

int getmxrr ( string hostname, array mxhosts [, array weight])

Searches DNS for MX records corresponding to hostname. Returns TRUE if any records are found; returns FALSE if no records were found or if an error occurred.

A list of the MX records found is placed into the array mxhosts. If the weight array is given, it will be filled with the weight information gathered.

Nota: This function is not implemented on Windows platforms. Try the PEAR class Net_DNS.

See also checkdnsrr(), gethostbyname(), gethostbynamel(), gethostbyaddr(), and the named(8) manual page.

getprotobyname

(PHP 4 )

getprotobyname --  Get protocol number associated with protocol name

Description

int getprotobyname ( string name)

getprotobyname() returns the protocol number associated with the protocol name as per /etc/protocols.

See also: getprotobynumber().

getprotobynumber

(PHP 4 )

getprotobynumber --  Get protocol name associated with protocol number

Description

string getprotobynumber ( int number)

getprotobynumber() returns the protocol name associated with protocol number as per /etc/protocols.

See also: getprotobyname().

getservbyname

(PHP 4 )

getservbyname --  Get port number associated with an Internet service and protocol

Description

int getservbyname ( string service, string protocol)

getservbyname() returns the Internet port which corresponds to service for the specified protocol as per /etc/services. protocol is either "tcp" or "udp" (in lowercase).

See also: getservbyport().

getservbyport

(PHP 4 )

getservbyport --  Get Internet service which corresponds to port and protocol

Description

string getservbyport ( int port, string protocol)

getservbyport() returns the Internet service associated with port for the specified protocol as per /etc/services. protocol is either "tcp" or "udp" (in lowercase).

See also: getservbyname().

ip2long

(PHP 4 )

ip2long --  Converts a string containing an (IPv4) Internet Protocol dotted address into a proper address.

Description

int ip2long ( string ip_address)

The function ip2long() generates an IPv4 Internet network address from its Internet standard format (dotted string) representation.

Exemplo 1. ip2long() Example

<?php
$ip = gethostbyname("www.example.com");
$out = "The following URLs are equivalent:<br>\n";
$out .= "http://www.example.com/, http://".$ip."/, and http://".sprintf("%u",ip2long($ip))."/<br>\n";
echo $out;
?>

Nota: Because PHP's integer type is signed, and many IP addresses will result in negative integers, you need to use the "%u" formatter of sprintf() or printf() to get the string representation of the unsigned IP address.

This second example shows how to print a converted address with the printf() function :

Exemplo 2. Displaying an IP address

<?php
$ip = gethostbyname("www.example.com");
printf("%u\n", ip2long($ip));
echo $out;
?>

See also: long2ip()

long2ip

(PHP 4 )

long2ip --  Converts an (IPv4) Internet network address into a string in Internet standard dotted format

Description

string long2ip ( int proper_address)

The function long2ip() generates an Internet address in dotted format (i.e.: aaa.bbb.ccc.ddd) from the proper address representation.

See also: ip2long()

openlog

(PHP 3, PHP 4 )

openlog -- Open connection to system logger

Description

int openlog ( string ident, int option, int facility)

openlog() opens a connection to the system logger for a program. The string ident is added to each message. Values for option and facility are given below. The option argument is used to indicate what logging options will be used when generating a log message. The facility argument is used to specify what type of program is logging the message. This allows you to specify (in your machine's syslog configuration) how messages coming from different facilities will be handled. The use of openlog() is optional. It will automatically be called by syslog() if necessary, in which case ident will default to FALSE.

Tabela 1. openlog() Options

Constant Description
LOG_CONS if there is an error while sending data to the system logger, write directly to the system console
LOG_NDELAY open the connection to the logger immediately
LOG_ODELAY (default) delay opening the connection until the first message is logged
LOG_PERROR print log message also to standard error
LOG_PID include PID with each message
You can use one or more of this options. When using multiple options you need to OR them, i.e. to open the connection immediately, write to the console and include the PID in each message, you will use: LOG_CONS | LOG_NDELAY | LOG_PID

Tabela 2. openlog() Facilities

Constant Description
LOG_AUTH security/authorization messages (use LOG_AUTHPRIV instead in systems where that constant is defined)
LOG_AUTHPRIV security/authorization messages (private)
LOG_CRON clock daemon (cron and at)
LOG_DAEMON other system daemons
LOG_KERN kernel messages
LOG_LOCAL0 ... LOG_LOCAL7 reserved for local use, these are not available in Windows
LOG_LPR line printer subsystem
LOG_MAIL mail subsystem
LOG_NEWS USENET news subsystem
LOG_SYSLOG messages generated internally by syslogd
LOG_USER generic user-level messages
LOG_UUCP UUCP subsystem

See also define_syslog_variables(), syslog() and closelog().

pfsockopen

(PHP 3>= 3.0.7, PHP 4 )

pfsockopen --  Open persistent Internet or Unix domain socket connection

Description

int pfsockopen ( string hostname, int port [, int errno [, string errstr [, int timeout]]])

This function behaves exactly as fsockopen() with the difference that the connection is not closed after the script finishes. It is the persistent version of fsockopen().

socket_get_status

socket_get_status --  Alias of stream_get_meta_data().

Description

This function is an alias of stream_get_meta_data().

socket_set_blocking

socket_set_blocking -- Alias for stream_set_blocking()

Description

This function is an alias for stream_set_blocking().

socket_set_timeout

socket_set_timeout -- Alias for stream_set_timeout()

Description

This is an alias for stream_set_timeout().

syslog

(PHP 3, PHP 4 )

syslog -- Generate a system log message

Description

int syslog ( int priority, string message)

syslog() generates a log message that will be distributed by the system logger. priority is a combination of the facility and the level, values for which are given in the next section. The remaining argument is the message to send, except that the two characters %m will be replaced by the error message string (strerror) corresponding to the present value of errno.

Tabela 1. syslog() Priorities (in descending order)

Constant Description
LOG_EMERG system is unusable
LOG_ALERT action must be taken immediately
LOG_CRIT critical conditions
LOG_ERR error conditions
LOG_WARNING warning conditions
LOG_NOTICE normal, but significant, condition
LOG_INFO informational message
LOG_DEBUG debug-level message

Exemplo 1. Using syslog()

<?php
define_syslog_variables();
// open syslog, include the process ID and also send
// the log to standard error, and use a user defined
// logging mechanism
openlog("myScripLog", LOG_PID | LOG_PERROR, LOG_LOCAL0);

// some code

if (authorized_client()) {
    // do something
} else {
    // unauthorized client!
    // log the attempt
    $access = date("Y/m/d H:i:s");
    syslog(LOG_WARNING,"Unauthorized client: $access $REMOTE_ADDR ($HTTP_USER_AGENT)");
}

closelog();
?>
For information on setting up a user defined log handler, see the syslog.conf(5) Unix manual page. More information on the syslog facilities and option can be found in the man pages for syslog(3) on Unix machines.

On Windows NT, the syslog service is emulated using the Event Log.

Nota: Use of LOG_LOCAL0 through LOG_LOCAL7 for the facility parameter of openlog() is not available in Windows.

See also define_syslog_variables(), openlog() and closelog().

LXVII. Ncurses terminal screen control functions

Introdução

ncurses (new curses) is a free software emulation of curses in System V Rel 4.0 (and above). It uses terminfo format, supports pads, colors, multiple highlights, form characters and function key mapping. Because of the 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.

Atenção

Este módulo é EXPERIMENTAL. Isso quer dizer que o comportamento neste módulo --- incluindo suas funções e seus nomes, e TUDO mais que está documentado sobre esse módulo --- poderá mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use este módulo por sua própria conta e risco.

Ncurses is available for the following platforms:

  • AIX

  • BeOS

  • Cygwin

  • Digital Unix (aka OSF1)

  • FreeBSD

  • GNU/Linux

  • HPUX

  • IRIX

  • OS/2

  • SCO OpenServer

  • Solaris

  • SunOS


Requisitos

You need the ncurses libraries and headerfiles. Download the latest version from the ftp://ftp.gnu.org/pub/gnu/ncurses/ or from an other GNU-Mirror.


Instalação

To get these functions to work, you have to compile the CGI or CLI version of PHP with --with-ncurses[=DIR].


Configuração durante execução

O comportamento dessas funções podem ser modificado pelas configurações do php.ini.

Tabela 1. Ncurses configuration options

Name Default Changeable
ncurses.value "42" PHP_INI_ALL
ncurses.string "foobar" PHP_INI_ALL
For further details and definition of the PHP_INI_* constants see ini_set().


Tipos Resource

Esta extensão não possui nenhum tipo resource.


Constantes Predefinidas

As contantes abaixo são definidas por esta extensão e somente estarão disponíveis quando a extensão foi compilada com o PHP ou carregada dinamicamente durante a execução.


Error codes

On error ncurses functions return NCURSES_ERR.


Colors

Tabela 2. ncurses color constants

constant meaning
NCURSES_COLOR_BLACK no color (black)
NCURSES_COLOR_WHITE white
NCURSES_COLOR_RED red - supported when terminal is in color mode
NCURSES_COLOR_GREEN green - supported when terminal is in color mod
NCURSES_COLOR_YELLOW yellow - supported when terminal is in color mod
NCURSES_COLOR_BLUE blue - supported when terminal is in color mod
NCURSES_COLOR_CYAN cyan - supported when terminal is in color mod
NCURSES_COLOR_MAGENTA magenta - supported when terminal is in color mod

Keys

Tabela 3. ncurses key constants

constant meaning
NCURSES_KEY_F0 - NCURSES_KEY_F64 function keys F1 - F64
NCURSES_KEY_DOWN down arrow
NCURSES_KEY_UP up arrow
NCURSES_KEY_LEFT left arrow
NCURSES_KEY_RIGHT right arrow
NCURSES_KEY_HOME home key (upward+left arrow)
NCURSES_KEY_BACKSPACE backspace
NCURSES_KEY_DL delete line
NCURSES_KEY_IL insert line
NCURSES_KEY_DC delete character
NCURSES_KEY_IC insert char or enter insert mode
NCURSES_KEY_EIC exit insert char mode
NCURSES_KEY_CLEAR clear screen
NCURSES_KEY_EOS clear to end of screen
NCURSES_KEY_EOL clear to end of line
NCURSES_KEY_SF scroll one line forward
NCURSES_KEY_SR scroll one line backward
NCURSES_KEY_NPAGE next page
NCURSES_KEY_PPAGE previous page
NCURSES_KEY_STAB set tab
NCURSES_KEY_CTAB clear tab
NCURSES_KEY_CATAB clear all tabs
NCURSES_KEY_SRESET soft (partial) reset
NCURSES_KEY_RESET reset or hard reset
NCURSES_KEY_PRINT print
NCURSES_KEY_LL lower left
NCURSES_KEY_A1 upper left of keypad
NCURSES_KEY_A3 upper right of keypad
NCURSES_KEY_B2 center of keypad
NCURSES_KEY_C1 lower left of keypad
NCURSES_KEY_C3 lower right of keypad
NCURSES_KEY_BTAB back tab
NCURSES_KEY_BEG beginning
NCURSES_KEY_CANCEL cancel
NCURSES_KEY_CLOSE close
NCURSES_KEY_COMMAND cmd (command)
NCURSES_KEY_COPY copy
NCURSES_KEY_CREATE create
NCURSES_KEY_END end
NCURSES_KEY_EXIT exit
NCURSES_KEY_FIND find
NCURSES_KEY_HELP help
NCURSES_KEY_MARK mark
NCURSES_KEY_MESSAGE message
NCURSES_KEY_MOVE move
NCURSES_KEY_NEXT next
NCURSES_KEY_OPEN open
NCURSES_KEY_OPTIONS options
NCURSES_KEY_PREVIOUS previous
NCURSES_KEY_REDO redo
NCURSES_KEY_REFERENCE ref (reference)
NCURSES_KEY_REFRESH refresh
NCURSES_KEY_REPLACE replace
NCURSES_KEY_RESTART restart
NCURSES_KEY_RESUME resume
NCURSES_KEY_SAVE save
NCURSES_KEY_SBEG shiftet beg (beginning)
NCURSES_KEY_SCANCEL shifted cancel
NCURSES_KEY_SCOMMAND shifted command
NCURSES_KEY_SCOPY shifted copy
NCURSES_KEY_SCREATE shifted create
NCURSES_KEY_SDC shifted delete char
NCURSES_KEY_SDL shifted delete line
NCURSES_KEY_SELECT select
NCURSES_KEY_SEND shifted end
NCURSES_KEY_SEOL shifted end of line
NCURSES_KEY_SEXIT shifted exit
NCURSES_KEY_SFIND shifted find
NCURSES_KEY_SHELP shifted help
NCURSES_KEY_SHOME shifted home
NCURSES_KEY_SIC shifted input
NCURSES_KEY_SLEFT shifted left arrow
NCURSES_KEY_SMESSAGE shifted message
NCURSES_KEY_SMOVE shifted move
NCURSES_KEY_SNEXT shifted next
NCURSES_KEY_SOPTIONS shifted options
NCURSES_KEY_SPREVIOUS shifted previous
NCURSES_KEY_SPRINT shifted print
NCURSES_KEY_SREDO shifted redo
NCURSES_KEY_SREPLACE shifted replace
NCURSES_KEY_SRIGHT shifted right arrow
NCURSES_KEY_SRSUME shifted resume
NCURSES_KEY_SSAVE shifted save
NCURSES_KEY_SSUSPEND shifted suspend
NCURSES_KEY_UNDO undo
NCURSES_KEY_MOUSE mouse event has occured
NCURSES_KEY_MAX maximum key value

Mouse

Tabela 4. mouse constants

Constant meaning
NCURSES_BUTTON1_RELEASED - NCURSES_BUTTON4_RELEASED button (1-4) released
NCURSES_BUTTON1_PRESSED - NCURSES_BUTTON4_PRESSED button (1-4) pressed
NCURSES_BUTTON1_CLICKED - NCURSES_BUTTON4_CLICKED button (1-4) clicked
NCURSES_BUTTON1_DOUBLE_CLICKED - NCURSES_BUTTON4_DOUBLE_CLICKED button (1-4) double clicked
NCURSES_BUTTON1_TRIPLE_CLICKED - NCURSES_BUTTON4_TRIPLE_CLICKED button (1-4) triple clicked
NCURSES_BUTTON_CTRL ctrl pressed during click
NCURSES_BUTTON_SHIFT shift pressed during click
NCURSES_BUTTON_ALT alt pressed during click
NCURSES_ALL_MOUSE_EVENTS report all mouse events
NCURSES_REPORT_MOUSE_POSITION report mouse position
Índice
ncurses_addch -- Add character at current position and advance cursor
ncurses_addchnstr -- Add attributed string with specified length at current position
ncurses_addchstr -- Add attributed string at current position
ncurses_addnstr -- Add string with specified length at current position
ncurses_addstr -- Output text at current position
ncurses_assume_default_colors -- Define default colors for color 0
ncurses_attroff -- Turn off the given attributes
ncurses_attron -- Turn on the given attributes
ncurses_attrset -- Set given attributes
ncurses_baudrate -- Returns baudrate of terminal
ncurses_beep -- Let the terminal beep
ncurses_bkgd -- Set background property for terminal screen
ncurses_bkgdset -- Control screen background
ncurses_border -- Draw a border around the screen using attributed characters
ncurses_can_change_color -- Check if we can change terminals colors
ncurses_cbreak -- Switch of input buffering
ncurses_clear -- Clear screen
ncurses_clrtobot -- Clear screen from current position to bottom
ncurses_clrtoeol -- Clear screen from current position to end of line
ncurses_color_set -- Set fore- and background color
ncurses_curs_set -- Set cursor state
ncurses_def_prog_mode -- Saves terminals (program) mode
ncurses_def_shell_mode -- Saves terminals (shell) mode
ncurses_define_key -- Define a keycode
ncurses_delay_output -- Delay output on terminal using padding characters
ncurses_delch -- Delete character at current position, move rest of line left
ncurses_deleteln -- Delete line at current position, move rest of screen up
ncurses_delwin -- Delete a ncurses window
ncurses_doupdate -- Write all prepared refreshes to terminal
ncurses_echo -- Activate keyboard input echo
ncurses_echochar -- Single character output including refresh
ncurses_end -- Stop using ncurses, clean up the screen
ncurses_erase -- Erase terminal screen
ncurses_erasechar -- Returns current erase character
ncurses_filter -- 
ncurses_flash -- Flash terminal screen (visual bell)
ncurses_flushinp -- Flush keyboard input buffer
ncurses_getch -- Read a character from keyboard
ncurses_getmouse -- Reads mouse event
ncurses_halfdelay -- Put terminal into halfdelay mode
ncurses_has_colors -- Check if terminal has colors
ncurses_has_ic -- Check for insert- and delete-capabilities
ncurses_has_il -- Check for line insert- and delete-capabilities
ncurses_has_key -- Check for presence of a function key on terminal keyboard
ncurses_hline -- Draw a horizontal line at current position using an attributed character and max. n characters long
ncurses_inch -- Get character and attribute at current position
ncurses_init_color -- Set new RGB value for color
ncurses_init_pair -- Allocate a color pair
ncurses_init -- Initialize ncurses
ncurses_insch -- Insert character moving rest of line including character at current position
ncurses_insdelln -- Insert lines before current line scrolling down (negative numbers delete and scroll up)
ncurses_insertln -- Insert a line, move rest of screen down
ncurses_insstr -- Insert string at current position, moving rest of line right
ncurses_instr -- Reads string from terminal screen
ncurses_isendwin -- Ncurses is in endwin mode, normal screen output may be performed
ncurses_keyok -- Enable or disable a keycode
ncurses_killchar -- Returns current line kill character
ncurses_longname -- Returns terminals description
ncurses_mouseinterval -- Set timeout for mouse button clicks
ncurses_mousemask -- Sets mouse options
ncurses_move -- Move output position
ncurses_mvaddch -- Move current position and add character
ncurses_mvaddchnstr -- Move position and add attrributed string with specified length
ncurses_mvaddchstr -- Move position and add attributed string
ncurses_mvaddnstr -- Move position and add string with specified length
ncurses_mvaddstr -- Move position and add string
ncurses_mvcur -- Move cursor immediately
ncurses_mvdelch -- Move position and delete character, shift rest of line left
ncurses_mvgetch -- Move position and get character at new position
ncurses_mvhline -- Set new position and draw a horizontal line using an attributed character and max. n characters long
ncurses_mvinch -- Move position and get attributed character at new position
ncurses_mvvline -- Set new position and draw a vertical line using an attributed character and max. n characters long
ncurses_mvwaddstr -- Add string at new position in window
ncurses_napms -- Sleep
ncurses_newwin -- Create a new window
ncurses_nl -- Translate newline and carriage return / line feed
ncurses_nocbreak -- Switch terminal to cooked mode
ncurses_noecho -- Switch off keyboard input echo
ncurses_nonl -- Do not translate newline and carriage return / line feed
ncurses_noqiflush -- Do not flush on signal characters
ncurses_noraw -- Switch terminal out of raw mode
ncurses_putp -- 
ncurses_qiflush -- Flush on signal characters
ncurses_raw -- Switch terminal into raw mode
ncurses_refresh -- Refresh screen
ncurses_resetty -- Restores saved terminal state
ncurses_savetty -- Saves terminal state
ncurses_scr_dump -- Dump screen content to file
ncurses_scr_init -- Initialize screen from file dump
ncurses_scr_restore -- Restore screen from file dump
ncurses_scr_set -- Inherit screen from file dump
ncurses_scrl -- Scroll window content up or down without changing current position
ncurses_slk_attr -- Returns current soft label key attribute
ncurses_slk_attroff -- 
ncurses_slk_attron -- 
ncurses_slk_attrset -- 
ncurses_slk_clear -- Clears soft labels from screen
ncurses_slk_color -- Sets color for soft label keys
ncurses_slk_init -- Initializes soft label key functions
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_slk_touch -- Fources output when ncurses_slk_noutrefresh is performed
ncurses_standend -- Stop using 'standout' attribute
ncurses_standout -- Start using 'standout' attribute
ncurses_start_color -- Start using colors
ncurses_termattrs -- Returns a logical OR of all attribute flags supported by terminal
ncurses_termname -- Returns terminals (short)-name
ncurses_timeout -- Set timeout for special key sequences
ncurses_typeahead -- Specify different filedescriptor for typeahead checking
ncurses_ungetch -- Put a character back into the input stream
ncurses_ungetmouse -- Pushes mouse event to queue
ncurses_use_default_colors -- Assign terminal default colors to color id -1
ncurses_use_env -- Control use of environment information about terminal size
ncurses_use_extended_names -- Control use of extended names in terminfo descriptions
ncurses_vidattr -- 
ncurses_vline -- Draw a vertical line at current position using an attributed character and max. n characters long
ncurses_wrefresh -- Refresh window on terminal screen

ncurses_addch

(PHP 4 >= 4.1.0)

ncurses_addch -- Add character at current position and advance cursor

Description

int ncurses_addch ( int ch)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_addchnstr

(PHP 4 >= 4.2.0)

ncurses_addchnstr -- Add attributed string with specified length at current position

Description

int ncurses_addchnstr ( string s, int n)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_addchstr

(PHP 4 >= 4.2.0)

ncurses_addchstr -- Add attributed string at current position

Description

int ncurses_addchstr ( string s)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_addnstr

(PHP 4 >= 4.2.0)

ncurses_addnstr -- Add string with specified length at current position

Description

int ncurses_addnstr ( string s, int n)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_addstr

(PHP 4 >= 4.2.0)

ncurses_addstr -- Output text at current position

Description

int ncurses_addstr ( string text)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_assume_default_colors

(PHP 4 >= 4.2.0)

ncurses_assume_default_colors -- Define default colors for color 0

Description

int ncurses_assume_default_colors ( int fg, int bg)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_attroff

(PHP 4 >= 4.1.0)

ncurses_attroff -- Turn off the given attributes

Description

int ncurses_attroff ( int attributes)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_attron

(PHP 4 >= 4.1.0)

ncurses_attron -- Turn on the given attributes

Description

int ncurses_attron ( int attributes)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_attrset

(PHP 4 >= 4.1.0)

ncurses_attrset -- Set given attributes

Description

int ncurses_attrset ( int attributes)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_baudrate

(PHP 4 >= 4.1.0)

ncurses_baudrate -- Returns baudrate of terminal

Description

int ncurses_baudrate ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_beep

(PHP 4 >= 4.1.0)

ncurses_beep -- Let the terminal beep

Description

int ncurses_beep ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

ncurses_beep() sends an audlible alert (bell) and if its not possible flashes the screen. Returns FALSE on success, otherwise TRUE.

See also: ncurses_flash()

ncurses_bkgd

(PHP 4 >= 4.1.0)

ncurses_bkgd -- Set background property for terminal screen

Description

int ncurses_bkgd ( int attrchar)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_bkgdset

(PHP 4 >= 4.1.0)

ncurses_bkgdset -- Control screen background

Description

void ncurses_bkgdset ( int attrchar)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_border

(PHP 4 >= 4.2.0)

ncurses_border -- Draw a border around the screen using attributed characters

Description

int ncurses_border ( int left, int right, int top, int bottom, int tl_corner, int tr_corner, int bl_corner, int br_corner)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_can_change_color

(PHP 4 >= 4.1.0)

ncurses_can_change_color -- Check if we can change terminals colors

Description

bool ncurses_can_change_color ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

The function ncurses_can_change_color() returns TRUE or FALSE, depending on whether the terminal has color capabilities and whether the programmer can change the colors.

ncurses_cbreak

(PHP 4 >= 4.1.0)

ncurses_cbreak -- Switch of input buffering

Description

bool ncurses_cbreak ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

ncurses_cbreak() disables line buffering and character processing (interrupt and flow control characters are unaffected), making characters typed by the user immediately available to the program.

ncurses_cbreak() returns TRUE or NCURSES_ERR if any error occured.

See also: ncurses_nocbreak()

ncurses_clear

(PHP 4 >= 4.1.0)

ncurses_clear -- Clear screen

Description

bool ncurses_clear ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

ncurses_clear() clears the screen completely without setting blanks. Returns FALSE on success, otherwise TRUE.

Note: ncurses_clear() clears the screen without setting blanks, which have the current background rendition. To clear screen with blanks, use ncurses_erase().

See also: ncurses_erase()

ncurses_clrtobot

(PHP 4 >= 4.1.0)

ncurses_clrtobot -- Clear screen from current position to bottom

Description

bool ncurses_clrtobot ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

ncurses_clrtobot() erases all lines from cursor to end of screen and creates blanks. Blanks created by ncurses_clrtobot() have the current background rendition. Returns TRUE if any error occured, otherwise FALSE.

See also: ncurses_clear(), ncurses_clrtoeol()

ncurses_clrtoeol

(PHP 4 >= 4.1.0)

ncurses_clrtoeol -- Clear screen from current position to end of line

Description

bool ncurses_clrtoeol ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

ncurses_clrtoeol() erases the current line from cursor position to the end. Blanks created by ncurses_clrtoeol() have the current background rendition. Returns TRUE if any error occured, otherwise FALSE.

See also: ncurses_clear(), ncurses_clrtobot()

ncurses_color_set

(PHP 4 >= 4.1.0)

ncurses_color_set -- Set fore- and background color

Description

int ncurses_color_set ( int pair)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_curs_set

(PHP 4 >= 4.1.0)

ncurses_curs_set -- Set cursor state

Description

int ncurses_curs_set ( int visibility)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_def_prog_mode

(PHP 4 >= 4.1.0)

ncurses_def_prog_mode -- Saves terminals (program) mode

Description

bool ncurses_def_prog_mode ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

ncurses_def_prog_mode() saves the current terminal modes for program (in curses) for use by ncurses_reset_prog_mode(). Returns FALSE on success, otherwise TRUE.

See also: ncurses_reset_prog_mode()

ncurses_def_shell_mode

(PHP 4 >= 4.1.0)

ncurses_def_shell_mode -- Saves terminals (shell) mode

Description

bool ncurses_def_shell_mode ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

ncurses_def_shell_mode() saves the current terminal modes for shell (not in curses) for use by ncurses_reset_shell_mode(). Returns FALSE on success, otherwise TRUE.

See also: ncurses_reset_shell_mode()

ncurses_define_key

(PHP 4 >= 4.2.0)

ncurses_define_key -- Define a keycode

Description

int ncurses_define_key ( string definition, int keycode)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_delay_output

(PHP 4 >= 4.1.0)

ncurses_delay_output -- Delay output on terminal using padding characters

Description

int ncurses_delay_output ( int milliseconds)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_delch

(PHP 4 >= 4.1.0)

ncurses_delch -- Delete character at current position, move rest of line left

Description

bool ncurses_delch ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

ncurses_delch() deletes the character under the cursor. All characters to the right of the cursor on the same line are moved to the left one position and the last character on the line is filled with a blank. The cursor position does not change. Returns FALSE on success, otherwise TRUE.

See also: ncurses_deleteln()

ncurses_deleteln

(PHP 4 >= 4.1.0)

ncurses_deleteln -- Delete line at current position, move rest of screen up

Description

bool ncurses_deleteln ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

ncurses_deleteln() deletes the current line under cursorposition. All lines below the current line are moved up one line. The bottom line of window is cleared. Cursor position does not change. Returns FALSE on success, otherwise TRUE.

See also: ncurses_delch()

ncurses_delwin

(PHP 4 >= 4.1.0)

ncurses_delwin -- Delete a ncurses window

Description

int ncurses_delwin ( resource window)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_doupdate

(PHP 4 >= 4.1.0)

ncurses_doupdate -- Write all prepared refreshes to terminal

Description

bool ncurses_doupdate ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

ncurses_doupdate()() compares the virtual screen to the physical screen and updates the physical screen. This way is more effective than using multiple refresh calls. Returns FALSE on success, TRUE if any error occured.

ncurses_echo

(PHP 4 >= 4.1.0)

ncurses_echo -- Activate keyboard input echo

Description

bool ncurses_echo ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

ncurses_echo() enables echo mode. All characters typed by user are echoed by ncurses_getch(). Returns FALSE on success, TRUE if any error occured.

To disable echo mode use ncurses_noecho().

ncurses_echochar

(PHP 4 >= 4.1.0)

ncurses_echochar -- Single character output including refresh

Description

int ncurses_echochar ( int character)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_end

(PHP 4 >= 4.1.0)

ncurses_end -- Stop using ncurses, clean up the screen

Description

int ncurses_end ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_erase

(PHP 4 >= 4.1.0)

ncurses_erase -- Erase terminal screen

Description

bool ncurses_erase ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

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_erasechar

(PHP 4 >= 4.1.0)

ncurses_erasechar -- Returns current erase character

Description

string ncurses_erasechar ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

ncurses_erasechar() returns the current erase char character.

See also: ncurses_killchar()

ncurses_filter

(PHP 4 >= 4.1.0)

ncurses_filter -- 

Description

int ncurses_filter ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_flash

(PHP 4 >= 4.1.0)

ncurses_flash -- Flash terminal screen (visual bell)

Description

bool ncurses_flash ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

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

ncurses_flushinp

(PHP 4 >= 4.1.0)

ncurses_flushinp -- Flush keyboard input buffer

Description

bool ncurses_flushinp ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

The ncurses_flushinp() throws away any typeahead that has been typed and has not yet been read by your program. Returns FALSE on success, otherwise TRUE.

ncurses_getch

(PHP 4 >= 4.1.0)

ncurses_getch -- Read a character from keyboard

Description

int ncurses_getch ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_getmouse

(PHP 4 >= 4.2.0)

ncurses_getmouse -- Reads mouse event

Description

bool ncurses_getmouse ( array mevent)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

ncurses_getmouse() reads mouse event out of queue. Function ncurses_getmouse() will return ;FALSE if a mouse event is actually visible in the given window, otherwise it will return TRUE. Event options will be delivered in parameter mevent, which has to be an array, passed by reference (see example below). On success an associative array with following keys will be delivered:

  • "id" : Id to distinguish multiple devices

  • "x" : screen relative x-position in character cells

  • "y" : screen relative y-position in character cells

  • "z" : currently not supported

  • "mmask" : Mouse action

Exemplo 1. ncurses_getmouse() example

switch (ncurses_getch){
  case NCURSES_KEY_MOUSE:
    if (!ncurses_getmouse(&$mevent)){
      if ($mevent["mmask"] & NCURSES_MOUSE_BUTTON1_PRESSED){
        $mouse_x = $mevent["x"]; // Save mouse position
        $mouse_y = $mevent["y"];
      }
    }
  break;

  default:
    ....
}

See also: ncurses_ungetmouse()

ncurses_halfdelay

(PHP 4 >= 4.1.0)

ncurses_halfdelay -- Put terminal into halfdelay mode

Description

int ncurses_halfdelay ( int tenth)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_has_colors

(PHP 4 >= 4.1.0)

ncurses_has_colors -- Check if terminal has colors

Description

bool ncurses_has_colors ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

ncurses_has_colors() returns TRUE or FALSE depending on whether the terminal has color capacitites.

See also: ncurses_can_change_color()

ncurses_has_ic

(PHP 4 >= 4.1.0)

ncurses_has_ic -- Check for insert- and delete-capabilities

Description

bool ncurses_has_ic ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

ncurses_has_ic() checks terminals insert- and delete capabilitites. It returns TRUE when terminal has insert/delete-capabilities, otherwise FALSE.

See also: ncurses_has_il()

ncurses_has_il

(PHP 4 >= 4.1.0)

ncurses_has_il -- Check for line insert- and delete-capabilities

Description

bool ncurses_has_il ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

ncurses_has_il() checks terminals insert- and delete-line-capabilities. It returns TRUE when terminal has insert/delete-line capabilities, otherwise FALSE

See also: ncurses_has_ic()

ncurses_has_key

(PHP 4 >= 4.1.0)

ncurses_has_key -- Check for presence of a function key on terminal keyboard

Description

int ncurses_has_key ( int keycode)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_hline

(PHP 4 >= 4.2.0)

ncurses_hline -- Draw a horizontal line at current position using an attributed character and max. n characters long

Description

int ncurses_hline ( int charattr, int n)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_inch

(PHP 4 >= 4.1.0)

ncurses_inch -- Get character and attribute at current position

Description

string ncurses_inch ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

ncurses_inch() returns the character from the current position.

ncurses_init_color

(PHP 4 >= 4.2.0)

ncurses_init_color -- Set new RGB value for color

Description

int ncurses_init_color ( int color, int r, int g, int b)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_init_pair

(PHP 4 >= 4.1.0)

ncurses_init_pair -- Allocate a color pair

Description

int ncurses_init_pair ( int pair, int fg, int bg)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_init

(PHP 4 >= 4.1.0)

ncurses_init -- Initialize ncurses

Description

int ncurses_init ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_insch

(PHP 4 >= 4.1.0)

ncurses_insch -- Insert character moving rest of line including character at current position

Description

int ncurses_insch ( int character)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_insdelln

(PHP 4 >= 4.1.0)

ncurses_insdelln -- Insert lines before current line scrolling down (negative numbers delete and scroll up)

Description

int ncurses_insdelln ( int count)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_insertln

(PHP 4 >= 4.1.0)

ncurses_insertln -- Insert a line, move rest of screen down

Description

bool ncurses_insertln ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

ncurses_insertln() inserts a new line above the current line. The bottom line will be lost.

ncurses_insstr

(PHP 4 >= 4.2.0)

ncurses_insstr -- Insert string at current position, moving rest of line right

Description

int ncurses_insstr ( string text)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_instr

(PHP 4 >= 4.2.0)

ncurses_instr -- Reads string from terminal screen

Description

int ncurses_instr ( string buffer)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

ncurses_instr() returns the number of charaters read from the current character position until end of line. buffer contains the characters. Atrributes are stripped from the characters.

ncurses_isendwin

(PHP 4 >= 4.1.0)

ncurses_isendwin -- Ncurses is in endwin mode, normal screen output may be performed

Description

bool ncurses_isendwin ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

ncurses_isendwin() returns TRUE, if ncurses_endwin() has been called without any subsequent calls to ncurses_wrefresh(), otherwise FALSE.

See also: ncurses_endwin() ncurses_wrefresh()()

ncurses_keyok

(PHP 4 >= 4.2.0)

ncurses_keyok -- Enable or disable a keycode

Description

int ncurses_keyok ( int keycode, bool enable)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_killchar

(PHP 4 >= 4.1.0)

ncurses_killchar -- Returns current line kill character

Description

bool ncurses_killchar ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

ncurses_killchar() returns the current line kill character.

See also: ncurses_erasechar()

ncurses_longname

(PHP 4 >= 4.2.0)

ncurses_longname -- Returns terminals description

Description

string ncurses_longname ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

ncurses_longname() returns a verbose description of the terminal. The descritpion is truncated to 128 characters. On Error ncurses_longname() returns NULL.

See also: ncurses_termname()

ncurses_mouseinterval

(PHP 4 >= 4.1.0)

ncurses_mouseinterval -- Set timeout for mouse button clicks

Description

int ncurses_mouseinterval ( int milliseconds)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_mousemask

(PHP 4 >= 4.2.0)

ncurses_mousemask -- Sets mouse options

Description

int ncurses_mousemask ( int newmask, int oldmask)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Function ncurses_mousemask() will set mouse events 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 newmask specified mouse events can be reported. On complete failure, it returns 0. In parameter oldmask, which is passed by reference ncurses_mousemask() returns the previous value of mouse event mask. Mouse events are represented bei NCURSES_KEY_MOUSE in the ncurses_wgetch() input stream. To read the event data and pop the event of of queue, call ncurses_getmouse().

As a side effect, setting a zero mousemask in newmask turns off the mouse pointer. Setting a non zero value turns mouse pointer on.

mouse mask options can be set with the following predefined constants:

  • NCURSES_BUTTON1_PRESSED

  • NCURSES_BUTTON1_RELEASED

  • NCURSES_BUTTON1_CLICKED

  • NCURSES_BUTTON1_DOUBLE_CLICKED

  • NCURSES_BUTTON1_TRIPLE_CLICKED

  • NCURSES_BUTTON2_PRESSED

  • NCURSES_BUTTON2_RELEASED

  • NCURSES_BUTTON2_CLICKED

  • NCURSES_BUTTON2_DOUBLE_CLICKED

  • NCURSES_BUTTON2_TRIPLE_CLICKED

  • NCURSES_BUTTON3_PRESSED

  • NCURSES_BUTTON3_RELEASED

  • NCURSES_BUTTON3_CLICKED

  • NCURSES_BUTTON3_DOUBLE_CLICKED

  • NCURSES_BUTTON3_TRIPLE_CLICKED

  • NCURSES_BUTTON4_PRESSED

  • NCURSES_BUTTON4_RELEASED

  • NCURSES_BUTTON4_CLICKED

  • NCURSES_BUTTON4_DOUBLE_CLICKED

  • NCURSES_BUTTON4_TRIPLE_CLICKED

  • NCURSES_BUTTON_SHIFT>

  • NCURSES_BUTTON_CTRL

  • NCURSES_BUTTON_ALT

  • NCURSES_ALL_MOUSE_EVENTS

  • NCURSES_REPORT_MOUSE_POSITION

See also: ncurses_getmouse(), ncurses_ungetmouse() ncurese_getch()

Exemplo 1. ncurses_mousemask() example

$newmask = NCURSES_BUTTON1_CLICKED + NCURSES_BUTTON1_RELEASED;
$mask = ncurses_mousemask($newmask, &$oldmask);
if ($mask & $newmask){
  printf ("All specified mouse options will be supported\n");
}

ncurses_move

(PHP 4 >= 4.1.0)

ncurses_move -- Move output position

Description

int ncurses_move ( int y, int x)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_mvaddch

(PHP 4 >= 4.2.0)

ncurses_mvaddch -- Move current position and add character

Description

int ncurses_mvaddch ( int y, int x, int c)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_mvaddchnstr

(PHP 4 >= 4.2.0)

ncurses_mvaddchnstr -- Move position and add attrributed string with specified length

Description

int ncurses_mvaddchnstr ( int y, int x, string s, int n)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_mvaddchstr

(PHP 4 >= 4.2.0)

ncurses_mvaddchstr -- Move position and add attributed string

Description

int ncurses_mvaddchstr ( int y, int x, string s)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_mvaddnstr

(PHP 4 >= 4.2.0)

ncurses_mvaddnstr -- Move position and add string with specified length

Description

int ncurses_mvaddnstr ( int y, int x, string s, int n)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_mvaddstr

(PHP 4 >= 4.2.0)

ncurses_mvaddstr -- Move position and add string

Description

int ncurses_mvaddstr ( int y, int x, string s)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_mvcur

(PHP 4 >= 4.2.0)

ncurses_mvcur -- Move cursor immediately

Description

int ncurses_mvcur ( int old_y, int old_x, int new_y, int new_x)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_mvdelch

(PHP 4 >= 4.2.0)

ncurses_mvdelch -- Move position and delete character, shift rest of line left

Description

int ncurses_mvdelch ( int y, int x)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_mvgetch

(PHP 4 >= 4.2.0)

ncurses_mvgetch -- Move position and get character at new position

Description

int ncurses_mvgetch ( int y, int x)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_mvhline

(PHP 4 >= 4.2.0)

ncurses_mvhline -- Set new position and draw a horizontal line using an attributed character and max. n characters long

Description

int ncurses_mvhline ( int y, int x, int attrchar, int n)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_mvinch

(PHP 4 >= 4.2.0)

ncurses_mvinch -- Move position and get attributed character at new position

Description

int ncurses_mvinch ( int y, int x)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_mvvline

(no version information, might be only in CVS)

ncurses_mvvline -- Set new position and draw a vertical line using an attributed character and max. n characters long

Description

int ncurses_mvvline ( int y, int x, int attrchar, int n)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_mvwaddstr

(PHP 4 >= 4.2.0)

ncurses_mvwaddstr -- Add string at new position in window

Description

int ncurses_mvwaddstr ( resource window, int y, int x, string text)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_napms

(PHP 4 >= 4.1.0)

ncurses_napms -- Sleep

Description

int ncurses_napms ( int milliseconds)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_newwin

(PHP 4 >= 4.1.0)

ncurses_newwin -- Create a new window

Description

int ncurses_newwin ( int rows, int cols, int y, int x)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_nl

(PHP 4 >= 4.1.0)

ncurses_nl -- Translate newline and carriage return / line feed

Description

bool ncurses_nl ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_nocbreak

(PHP 4 >= 4.1.0)

ncurses_nocbreak -- Switch terminal to cooked mode

Description

bool ncurses_nocbreak ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

ncurses_nocbreak() routine returns terminal to normal (cooked) mode. Initially the terminal may or may not in cbreak mode as the mode is inherited. Therefore a program should call ncurses_cbreak() and ncurses_nocbreak() explicitly. Returns TRUE if any error occured, otherwise FALSE.

See also: ncurses_cbreak()

ncurses_noecho

(PHP 4 >= 4.1.0)

ncurses_noecho -- Switch off keyboard input echo

Description

bool ncurses_noecho ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

ncurses_noecho() prevents echoing of user typed characters. Returns TRUE if any error occured, otherwise FALSE.

See also: ncurses_echo(), ncurses_getch()

ncurses_nonl

(PHP 4 >= 4.1.0)

ncurses_nonl -- Do not translate newline and carriage return / line feed

Description

bool ncurses_nonl ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_noqiflush

(PHP 4 >= 4.1.0)

ncurses_noqiflush -- Do not flush on signal characters

Description

int ncurses_noqiflush ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_noraw

(PHP 4 >= 4.1.0)

ncurses_noraw -- Switch terminal out of raw mode

Description

bool ncurses_noraw ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

ncurses_noraw() switches the terminal out of raw mode. Raw mode is similar to cbreak mode, in that characters typed are immediately passed through to the user program. The differences that are that in raw mode, the interrupt, quit, suspend and flow control characters are all passed through uninterpreted, instead of generating a signal. Returns TRUE if any error occured, otherwise FALSE.

See also: ncurses_raw(), ncurses_cbreak(), ncurses_nocbreak()

ncurses_putp

(PHP 4 >= 4.2.0)

ncurses_putp -- 

Description

int ncurses_putp ( string text)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_qiflush

(PHP 4 >= 4.1.0)

ncurses_qiflush -- Flush on signal characters

Description

int ncurses_qiflush ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_raw

(PHP 4 >= 4.1.0)

ncurses_raw -- Switch terminal into raw mode

Description

bool ncurses_raw ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

ncurses_raw() places the terminal in raw mode. Raw mode is similar to cbreak mode, in that characters typed are immediately passed through to the user program. The differences that are that in raw mode, the interrupt, quit, suspend and flow control characters are all passed through uninterpreted, instead of generating a signal. Returns TRUE if any error occured, otherwise FALSE.

See also: ncurses_noraw(), ncurses_cbreak(), ncurses_nocbreak()

ncurses_refresh

(PHP 4 >= 4.1.0)

ncurses_refresh -- Refresh screen

Description

int ncurses_refresh ( int ch)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_resetty

(PHP 4 >= 4.1.0)

ncurses_resetty -- Restores saved terminal state

Description

bool ncurses_resetty ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Function ncurses_resetty() restores the terminal state, which was previously saved by calling ncurses_savetty(). This function always returns FALSE.

See also: ncurses_savetty()

ncurses_savetty

(PHP 4 >= 4.1.0)

ncurses_savetty -- Saves terminal state

Description

bool ncurses_savetty ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Function ncurses_savetty() saves the current terminal state. The saved terminal state can be restored with function ncurses_resetty(). ncurses_savetty() always returns FALSE.

See also: ncurses_resetty()

ncurses_scr_dump

(PHP 4 >= 4.2.0)

ncurses_scr_dump -- Dump screen content to file

Description

int ncurses_scr_dump ( string filename)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_scr_init

(PHP 4 >= 4.2.0)

ncurses_scr_init -- Initialize screen from file dump

Description

int ncurses_scr_init ( string filename)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_scr_restore

(PHP 4 >= 4.2.0)

ncurses_scr_restore -- Restore screen from file dump

Description

int ncurses_scr_restore ( string filename)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_scr_set

(PHP 4 >= 4.2.0)

ncurses_scr_set -- Inherit screen from file dump

Description

int ncurses_scr_set ( string filename)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_scrl

(PHP 4 >= 4.1.0)

ncurses_scrl -- Scroll window content up or down without changing current position

Description

int ncurses_scrl ( int count)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_slk_attr

(PHP 4 >= 4.1.0)

ncurses_slk_attr -- Returns current soft label key attribute

Description

bool ncurses_slk_attr ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

ncurses_slk_attr() returns the current soft label key attribute. On error returns TRUE, otherwise FALSE.

ncurses_slk_attroff

(PHP 4 >= 4.1.0)

ncurses_slk_attroff -- 

Description

int ncurses_slk_attroff ( int intarg)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_slk_attron

(PHP 4 >= 4.1.0)

ncurses_slk_attron -- 

Description

int ncurses_slk_attron ( int intarg)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_slk_attrset

(PHP 4 >= 4.1.0)

ncurses_slk_attrset -- 

Description

int ncurses_slk_attrset ( int intarg)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_slk_clear

(PHP 4 >= 4.1.0)

ncurses_slk_clear -- Clears soft labels from screen

Description

bool ncurses_slk_clear ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

The function ncurses_slk_clear() clears soft label keys from screen. Returns TRUE on error, otherwise FALSE.

ncurses_slk_color

(PHP 4 >= 4.1.0)

ncurses_slk_color -- Sets color for soft label keys

Description

int ncurses_slk_color ( int intarg)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_slk_init

(PHP 4 >= 4.1.0)

ncurses_slk_init -- Initializes soft label key functions

Description

bool ncurses_slk_init ( int format)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Funtion ncurses_slk_init() must be called before ncurses_initscr() or ncurses_newterm() is called. If ncurses_initscr() eventually uses a line from stdscr to emulate the soft labels, then format determines how the labels are arranged of the screen. Setting format to 0 indicates a 3-2-3 arrangement of the labels, 1 indicates a 4-4 arrangement and 2 indicates the PC like 4-4-4 mode, but in addition an index line will be created.

ncurses_slk_noutrefresh

(PHP 4 >= 4.1.0)

ncurses_slk_noutrefresh -- Copies soft label keys to virtual screen

Description

bool ncurses_slk_noutrefresh ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_slk_refresh

(PHP 4 >= 4.1.0)

ncurses_slk_refresh -- Copies soft label keys to screen

Description

bool ncurses_slk_refresh ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

ncurses_slk_refresh() copies soft label keys from virtual screen to physical screen. Returns TRUE on error, otherwise FALSE.

ncurses_slk_restore

(PHP 4 >= 4.1.0)

ncurses_slk_restore -- Restores soft label keys

Description

bool ncurses_slk_restore ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

The function ncurses_slk_restore() restores the soft label keys after ncurses_slk_clear() has been performed.

ncurses_slk_touch

(PHP 4 >= 4.1.0)

ncurses_slk_touch -- Fources output when ncurses_slk_noutrefresh is performed

Description

bool ncurses_slk_touch ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

The ncurses_slk_touch() function forces all the soft labels to be output the next time a ncurses_slk_noutrefresh() is performed.

ncurses_standend

(PHP 4 >= 4.1.0)

ncurses_standend -- Stop using 'standout' attribute

Description

int ncurses_standend ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_standout

(PHP 4 >= 4.1.0)

ncurses_standout -- Start using 'standout' attribute

Description

int ncurses_standout ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_start_color

(PHP 4 >= 4.1.0)

ncurses_start_color -- Start using colors

Description

int ncurses_start_color ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_termattrs

(PHP 4 >= 4.1.0)

ncurses_termattrs -- Returns a logical OR of all attribute flags supported by terminal

Description

bool ncurses_termattrs ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_termname

(PHP 4 >= 4.2.0)

ncurses_termname -- Returns terminals (short)-name

Description

string ncurses_termname ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

ncurses_termname() returns terminals shortname. The shortname is truncated to 14 characters. On error ncurses_termname() returns NULL.

See also: ncurses_longname()

ncurses_timeout

(PHP 4 >= 4.1.0)

ncurses_timeout -- Set timeout for special key sequences

Description

void ncurses_timeout ( int millisec)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_typeahead

(PHP 4 >= 4.1.0)

ncurses_typeahead -- Specify different filedescriptor for typeahead checking

Description

int ncurses_typeahead ( int fd)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_ungetch

(PHP 4 >= 4.1.0)

ncurses_ungetch -- Put a character back into the input stream

Description

int ncurses_ungetch ( int keycode)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_ungetmouse

(PHP 4 >= 4.2.0)

ncurses_ungetmouse -- Pushes mouse event to queue

Description

bool ncurses_ungetmouse ( array mevent)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

ncurses_getmouse() pushes a KEY_MOUSE event onto the unput queue and associates with this event the given state sata and screen-relative character cell coordinates, specified in mevent. Event options will be specified in associative array mevent:

  • "id" : Id to distinguish multiple devices

  • "x" : screen relative x-position in character cells

  • "y" : screen relative y-position in character cells

  • "z" : currently not supported

  • "mmask" : Mouse action

ncurses_ungetmouse() returns FALSE on success, otherwise TRUE.

See also: ncurses_getmouse()

ncurses_use_default_colors

(PHP 4 >= 4.1.0)

ncurses_use_default_colors -- Assign terminal default colors to color id -1

Description

bool ncurses_use_default_colors ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_use_env

(PHP 4 >= 4.1.0)

ncurses_use_env -- Control use of environment information about terminal size

Description

void ncurses_use_env ( bool flag)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_use_extended_names

(PHP 4 >= 4.1.0)

ncurses_use_extended_names -- Control use of extended names in terminfo descriptions

Description

int ncurses_use_extended_names ( bool flag)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_vidattr

(PHP 4 >= 4.1.0)

ncurses_vidattr -- 

Description

int ncurses_vidattr ( int intarg)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_vline

(PHP 4 >= 4.2.0)

ncurses_vline -- Draw a vertical line at current position using an attributed character and max. n characters long

Description

int ncurses_vline ( int charattr, int n)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

ncurses_wrefresh

(PHP 4 >= 4.2.0)

ncurses_wrefresh -- Refresh window on terminal screen

Description

int ncurses_wrefresh ( resource window)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

LXVIII. Lotus Notes functions

Introdução

Atenção

Este módulo é EXPERIMENTAL. Isso quer dizer que o comportamento neste módulo --- incluindo suas funções e seus nomes, e TUDO mais que está documentado sobre esse módulo --- poderá mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use este módulo por sua própria conta e risco.

Índice
notes_body -- Open the message msg_number in the specified mailbox on the specified server (leave serv
notes_copy_db -- Create a note using form form_name
notes_create_db -- Create a Lotus Notes database
notes_create_note -- Create a note using form form_name
notes_drop_db -- Drop a Lotus Notes database
notes_find_note -- Returns a note id found in database_name. Specify the name of the note. Leaving type bla
notes_header_info -- Open the message msg_number in the specified mailbox on the specified server (leave serv
notes_list_msgs -- Returns the notes from a selected database_name
notes_mark_read -- Mark a note_id as read for the User user_name
notes_mark_unread -- Mark a note_id as unread for the User user_name
notes_nav_create -- Create a navigator name, in database_name
notes_search -- Find notes that match keywords in database_name
notes_unread -- Returns the unread note id's for the current User user_name
notes_version -- Get the version Lotus Notes

notes_body

(PHP 4 >= 4.0.5)

notes_body -- Open the message msg_number in the specified mailbox on the specified server (leave serv

Description

array notes_body ( string server, string mailbox, int msg_number)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

notes_copy_db

(PHP 4 >= 4.0.5)

notes_copy_db -- Create a note using form form_name

Description

string notes_copy_db ( string from_database_name, string to_database_name)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

notes_create_db

(PHP 4 >= 4.0.5)

notes_create_db -- Create a Lotus Notes database

Description

bool notes_create_db ( string database_name)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

notes_create_note

(PHP 4 >= 4.0.5)

notes_create_note -- Create a note using form form_name

Description

string notes_create_note ( string database_name, string form_name)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

notes_drop_db

(PHP 4 >= 4.0.5)

notes_drop_db -- Drop a Lotus Notes database

Description

bool notes_drop_db ( string database_name)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

notes_find_note

(PHP 4 >= 4.0.5)

notes_find_note -- Returns a note id found in database_name. Specify the name of the note. Leaving type bla

Description

bool notes_find_note ( string database_name, string name [, string type])

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

notes_header_info

(PHP 4 >= 4.0.5)

notes_header_info -- Open the message msg_number in the specified mailbox on the specified server (leave serv

Description

object notes_header_info ( string server, string mailbox, int msg_number)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

notes_list_msgs

(PHP 4 >= 4.0.5)

notes_list_msgs -- Returns the notes from a selected database_name

Description

bool notes_list_msgs ( string db)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

notes_mark_read

(PHP 4 >= 4.0.5)

notes_mark_read -- Mark a note_id as read for the User user_name

Description

string notes_mark_read ( string database_name, string user_name, string note_id)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

notes_mark_unread

(PHP 4 >= 4.0.5)

notes_mark_unread -- Mark a note_id as unread for the User user_name

Description

string notes_mark_unread ( string database_name, string user_name, string note_id)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

notes_nav_create

(PHP 4 >= 4.0.5)

notes_nav_create -- Create a navigator name, in database_name

Description

bool notes_nav_create ( string database_name, string name)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

notes_search

(PHP 4 >= 4.0.5)

notes_search -- Find notes that match keywords in database_name

Description

string notes_search ( string database_name, string keywords)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

notes_unread

(PHP 4 >= 4.0.5)

notes_unread -- Returns the unread note id's for the current User user_name

Description

string notes_unread ( string database_name, string user_name)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

notes_version

(PHP 4 >= 4.0.5)

notes_version -- Get the version Lotus Notes

Description

string notes_version ( string database_name)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

LXIX. Unified ODBC functions

Introdução

In addition to normal ODBC support, the Unified ODBC functions in PHP allow you to access several databases that have borrowed the semantics of the ODBC API to implement their own API. Instead of maintaining multiple database drivers that were all nearly identical, these drivers have been unified into a single set of ODBC functions.

The following databases are supported by the Unified ODBC functions: Adabas D, IBM DB2, iODBC, Solid, and Sybase SQL Anywhere.

Nota: There is no ODBC involved when connecting to the above databases. The functions that you use to speak natively to them just happen to share the same names and syntax as the ODBC functions. The exception to this is iODBC. Building PHP with iODBC support enables you to use any ODBC-compliant drivers with your PHP applications. iODBC is maintained by OpenLink Software. More information on iODBC, as well as a HOWTO, is available at http://www.iodbc.org/.


Requisitos

To access any of the supported databases you need to have the required libraries installed.


Instalação

Please see the Database installation options chapter for more information about configuring PHP with these databases.

The windows version of PHP has built in support for this extension. You do not need to load any additional extension in order to use these functions.


Configuração durante execução

O comportamento dessas funções podem ser modificado pelas configurações do php.ini.

Tabela 1. Unified ODBC Configuration Options

Name Default Changeable
odbc.default_db * NULL PHP_INI_ALL
odbc.default_user * NULL PHP_INI_ALL
odbc.default_pw * NULL PHP_INI_ALL
odbc.allow_persistent "1" PHP_INI_SYSTEM
odbc.check_persistent "1" PHP_INI_SYSTEM
odbc.max_persistent "-1" PHP_INI_SYSTEM
odbc.max_links "-1" PHP_INI_SYSTEM
odbc.defaultlrl "4096" PHP_INI_ALL
odbc.defaultbinmode "1" PHP_INI_ALL

Nota: Entries marked with * are not implemented yet.

For further details and definition of the PHP_INI_* constants see ini_set().

Here is a short explanation of the configuration directives.

odbc.default_db string

ODBC data source to use if none is specified in odbc_connect() or odbc_pconnect().

odbc.default_user string

User name to use if none is specified in odbc_connect() or odbc_pconnect().

odbc.default_pw string

Password to use if none is specified in odbc_connect() or odbc_pconnect().

odbc.allow_persistent boolean

Whether to allow persistent ODBC connections.

odbc.check_persistent boolean

Check that a connection is still valid before reuse.

odbc.max_persistent integer

The maximum number of persistent ODBC connections per process.

odbc.max_links integer

The maximum number of ODBC connections per process, including persistent connections.

odbc.defaultlrl integer

Handling of LONG fields. Specifies the number of bytes returned to variables.

odbc.defaultbinmode integer

Handling of binary data.


Tipos Resource

Esta extensão não possui nenhum tipo resource.


Constantes Predefinidas

As contantes abaixo são definidas por esta extensão e somente estarão disponíveis quando a extensão foi compilada com o PHP ou carregada dinamicamente durante a execução.

ODBC_TYPE (integer)

ODBC_BINMODE_PASSTHRU (integer)

ODBC_BINMODE_RETURN (integer)

ODBC_BINMODE_CONVERT (integer)

SQL_ODBC_CURSORS (integer)

SQL_CUR_USE_DRIVER (integer)

SQL_CUR_USE_IF_NEEDED (integer)

SQL_CUR_USE_ODBC (integer)

SQL_CONCURRENCY (integer)

SQL_CONCUR_READ_ONLY (integer)

SQL_CONCUR_LOCK (integer)

SQL_CONCUR_ROWVER (integer)

SQL_CONCUR_VALUES (integer)

SQL_CURSOR_TYPE (integer)

SQL_CURSOR_FORWARD_ONLY (integer)

SQL_CURSOR_KEYSET_DRIVEN (integer)

SQL_CURSOR_DYNAMIC (integer)

SQL_CURSOR_STATIC (integer)

SQL_KEYSET_SIZE (integer)

SQL_CHAR (integer)

SQL_VARCHAR (integer)

SQL_LONGVARCHAR (integer)

SQL_DECIMAL (integer)

SQL_NUMERIC (integer)

SQL_BIT (integer)

SQL_TINYINT (integer)

SQL_SMALLINT (integer)

SQL_INTEGER (integer)

SQL_BIGINT (integer)

SQL_REAL (integer)

SQL_FLOAT (integer)

SQL_DOUBLE (integer)

SQL_BINARY (integer)

SQL_VARBINARY (integer)

SQL_LONGVARBINARY (integer)

SQL_DATE (integer)

SQL_TIME (integer)

SQL_TIMESTAMP (integer)

SQL_TYPE_DATE (integer)

SQL_TYPE_TIME (integer)

SQL_TYPE_TIMESTAMP (integer)

SQL_BEST_ROWID (integer)

SQL_ROWVER (integer)

SQL_SCOPE_CURROW (integer)

SQL_SCOPE_TRANSACTION (integer)

SQL_SCOPE_SESSION (integer)

SQL_NO_NULLS (integer)

SQL_NULLABLE (integer)

SQL_INDEX_UNIQUE (integer)

SQL_INDEX_ALL (integer)

SQL_ENSURE (integer)

SQL_QUICK (integer)

Índice
odbc_autocommit -- Toggle autocommit behaviour
odbc_binmode -- Handling of binary column data
odbc_close_all -- Close all ODBC connections
odbc_close -- Close an ODBC connection
odbc_columnprivileges --  Returns a result identifier that can be used to fetch a list of columns and associated privileges
odbc_columns --  Lists the column names in specified tables. Returns a result identifier containing the information.
odbc_commit -- Commit an ODBC transaction
odbc_connect -- Connect to a datasource
odbc_cursor -- Get cursorname
odbc_data_source -- Returns information about a current connection
odbc_do -- Synonym for odbc_exec()
odbc_error -- Get the last error code
odbc_errormsg -- Get the last error message
odbc_exec -- Prepare and execute a SQL statement
odbc_execute -- Execute a prepared statement
odbc_fetch_array --  Fetch a result row as an associative array
odbc_fetch_into -- Fetch one result row into array
odbc_fetch_object --  Fetch a result row as an object
odbc_fetch_row -- Fetch a row
odbc_field_len -- Get the length (precision) of a field
odbc_field_name -- Get the columnname
odbc_field_num -- Return column number
odbc_field_precision -- Synonym for odbc_field_len()
odbc_field_scale -- Get the scale of a field
odbc_field_type -- Datatype of a field
odbc_foreignkeys --  Returns a list of foreign keys in the specified table or a list of foreign keys in other tables that refer to the primary key in the specified table
odbc_free_result -- Free resources associated with a result
odbc_gettypeinfo --  Returns a result identifier containing information about data types supported by the data source.
odbc_longreadlen -- Handling of LONG columns
odbc_next_result --  Checks if multiple results are avaiable
odbc_num_fields -- Number of columns in a result
odbc_num_rows -- Number of rows in a result
odbc_pconnect -- Open a persistent database connection
odbc_prepare -- Prepares a statement for execution
odbc_primarykeys --  Returns a result identifier that can be used to fetch the column names that comprise the primary key for a table
odbc_procedurecolumns --  Retrieve information about parameters to procedures
odbc_procedures --  Get the list of procedures stored in a specific data source. Returns a result identifier containing the information.
odbc_result_all -- Print result as HTML table
odbc_result -- Get result data
odbc_rollback -- Rollback a transaction
odbc_setoption --  Adjust ODBC settings. Returns FALSE if an error occurs, otherwise TRUE.
odbc_specialcolumns --  Returns either the optimal set of columns that uniquely identifies a row in the table or columns that are automatically updated when any value in the row is updated by a transaction
odbc_statistics -- Retrieve statistics about a table
odbc_tableprivileges --  Lists tables and the privileges associated with each table
odbc_tables --  Get the list of table names stored in a specific data source. Returns a result identifier containing the information.

odbc_autocommit

(PHP 3>= 3.0.6, PHP 4 )

odbc_autocommit -- Toggle autocommit behaviour

Description

bool odbc_autocommit ( resource connection_id [, bool OnOff])

Without the OnOff parameter, this function returns auto-commit status for connection_id. TRUE is returned if auto-commit is on, FALSE if it is off or an error occurs.

If OnOff is TRUE, auto-commit is enabled, if it is FALSE auto-commit is disabled. Returns TRUE on success, FALSE on failure.

By default, auto-commit is on for a connection. Disabling auto-commit is equivalent with starting a transaction.

See also odbc_commit() and odbc_rollback().

odbc_binmode

(PHP 3>= 3.0.6, PHP 4 )

odbc_binmode -- Handling of binary column data

Description

int odbc_binmode ( resource result_id, int mode)

(ODBC SQL types affected: BINARY, VARBINARY, LONGVARBINARY)

  • ODBC_BINMODE_PASSTHRU: Passthru BINARY data

  • ODBC_BINMODE_RETURN: Return as is

  • ODBC_BINMODE_CONVERT: Convert to char and return

When binary SQL data is converted to character C data, each byte (8 bits) of source data is represented as two ASCII characters. These characters are the ASCII character representation of the number in its hexadecimal form. For example, a binary 00000001 is converted to "01" and a binary 11111111 is converted to "FF".

Tabela 1. LONGVARBINARY handling

binmode longreadlen result
ODBC_BINMODE_PASSTHRU 0 passthru
ODBC_BINMODE_RETURN 0 passthru
ODBC_BINMODE_CONVERT 0 passthru
ODBC_BINMODE_PASSTHRU 0 passthru
ODBC_BINMODE_PASSTHRU >0 passthru
ODBC_BINMODE_RETURN >0 return as is
ODBC_BINMODE_CONVERT >0 return as char

If odbc_fetch_into() is used, passthru means that an empty string is returned for these columns.

If result_id is 0, the settings apply as default for new results.

Nota: Default for longreadlen is 4096 and binmode defaults to ODBC_BINMODE_RETURN. Handling of binary long columns is also affected by odbc_longreadlen()

odbc_close_all

(PHP 3>= 3.0.6, PHP 4 )

odbc_close_all -- Close all ODBC connections

Description

void odbc_close_all ( void)

odbc_close_all() will close down all connections to database server(s).

Nota: This function will fail if there are open transactions on a connection. This connection will remain open in this case.

odbc_close

(PHP 3>= 3.0.6, PHP 4 )

odbc_close -- Close an ODBC connection

Description

void odbc_close ( resource connection_id)

odbc_close() will close down the connection to the database server associated with the given connection identifier.

Nota: This function will fail if there are open transactions on this connection. The connection will remain open in this case.

odbc_columnprivileges

(PHP 4 )

odbc_columnprivileges --  Returns a result identifier that can be used to fetch a list of columns and associated privileges

Description

int odbc_columnprivileges ( resource connection_id [, string qualifier [, string owner [, string table_name [, string column_name]]]])

Lists columns and associated privileges for the given table. Returns an ODBC result identifier or FALSE on failure.

The result set has the following columns:

  • TABLE_QUALIFIER

  • TABLE_OWNER

  • TABLE_NAME

  • GRANTOR

  • GRANTEE

  • PRIVILEGE

  • IS_GRANTABLE

The result set is ordered by TABLE_QUALIFIER, TABLE_OWNER and TABLE_NAME.

The column_name argument accepts search patterns ('%' to match zero or more characters and '_' to match a single character).

odbc_columns

(PHP 4 )

odbc_columns --  Lists the column names in specified tables. Returns a result identifier containing the information.

Description

resource odbc_columns ( resource connection_id [, string qualifier [, string schema [, string table_name [, string column_name]]]])

Lists all columns in the requested range. Returns an ODBC result identifier or FALSE on failure.

The result set has the following columns:

  • TABLE_QUALIFIER

  • TABLE_SCHEM

  • TABLE_NAME

  • COLUMN_NAME

  • DATA_TYPE

  • TYPE_NAME

  • PRECISION

  • LENGTH

  • SCALE

  • RADIX

  • NULLABLE

  • REMARKS

The result set is ordered by TABLE_QUALIFIER, TABLE_SCHEM and TABLE_NAME.

The schema, table_name and column_name arguments accept search patterns ('%' to match zero or more characters and '_' to match a single character).

See also odbc_columnprivileges() to retrieve associated privileges.

odbc_commit

(PHP 3>= 3.0.6, PHP 4 )

odbc_commit -- Commit an ODBC transaction

Description

bool odbc_commit ( resource connection_id)

odbc_commit() commits all pending transactions on the connection_id connexion. Retorna TRUE em caso de sucesso ou FALSE em falhas.

odbc_connect

(PHP 3>= 3.0.6, PHP 4 )

odbc_connect -- Connect to a datasource

Description

resource odbc_connect ( string dsn, string user, string password [, int cursor_type])

Returns an ODBC connection id or 0 (FALSE) on error.

The connection id returned by this functions is needed by other ODBC functions. You can have multiple connections open at once. The optional fourth parameter sets the type of cursor to be used for this connection. This parameter is not normally needed, but can be useful for working around problems with some ODBC drivers.

With some ODBC drivers, executing a complex stored procedure may fail with an error similar to: "Cannot open a cursor on a stored procedure that has anything other than a single select statement in it". Using SQL_CUR_USE_ODBC may avoid that error. Also, some drivers don't support the optional row_number parameter in odbc_fetch_row(). SQL_CUR_USE_ODBC might help in that case, too.

The following constants are defined for cursortype:

  • SQL_CUR_USE_IF_NEEDED

  • SQL_CUR_USE_ODBC

  • SQL_CUR_USE_DRIVER

  • SQL_CUR_DEFAULT

For persistent connections see odbc_pconnect().

odbc_cursor

(PHP 3>= 3.0.6, PHP 4 )

odbc_cursor -- Get cursorname

Description

string odbc_cursor ( resource result_id)

odbc_cursor will return a cursorname for the given result_id.

odbc_data_source

(PHP 4 >= 4.3.0)

odbc_data_source -- Returns information about a current connection

Description

resource odbc_data_source ( resource connection_id, constant fetch_type)

Returns FALSE on error, and an array upon success.

This function will return information about the active connection following the information from within the DSN. The connection_id is required to be a valid ODBC connection. The fetch_type can be one of two constant types: SQL_FETCH_FIRST, SQL_FETCH_NEXT. Use SQL_FETCH_FIRST the first time this function is called, thereafter use the SQL_FETCH_NEXT.

odbc_do

(PHP 3>= 3.0.6, PHP 4 )

odbc_do -- Synonym for odbc_exec()

Description

resource odbc_do ( resource conn_id, string query)

odbc_do() will execute a query on the given connection.

odbc_error

(PHP 4 >= 4.0.5)

odbc_error -- Get the last error code

Description

string odbc_error ( [resource connection_id])

Returns a six-digit ODBC state, or an empty string if there has been no errors. If connection_id is specified, the last state of that connection is returned, else the last state of any connection is returned.

See also: odbc_errormsg() and odbc_exec().

odbc_errormsg

(PHP 4 >= 4.0.5)

odbc_errormsg -- Get the last error message

Description

string odbc_errormsg ( [resource connection_id])

Returns a string containing the last ODBC error message, or an empty string if there has been no errors. If connection_id is specified, the last state of that connection is returned, else the last state of any connection is returned.

See also: odbc_error() and odbc_exec().

odbc_exec

(PHP 3>= 3.0.6, PHP 4 )

odbc_exec -- Prepare and execute a SQL statement

Description

resource odbc_exec ( resource connection_id, string query_string)

Returns FALSE on error. Returns an ODBC result identifier if the SQL command was executed successfully.

odbc_exec() will send an SQL statement to the database server specified by connection_id. This parameter must be a valid identifier returned by odbc_connect() or odbc_pconnect().

See also: odbc_prepare() and odbc_execute() for multiple execution of SQL statements.

odbc_execute

(PHP 3>= 3.0.6, PHP 4 )

odbc_execute -- Execute a prepared statement

Description

bool odbc_execute ( resource result_id [, array parameters_array])

Executes a statement prepared with odbc_prepare().Retorna TRUE em caso de sucesso ou FALSE em falhas. The array parameters_array only needs to be given if you really have parameters in your statement.

Parameters in parameter_array will be substituted for placeholders in the prepared statement in order.

Any parameters in parameter_array which start and end with single quotes will be taken as the name of a file to read and send to the database server as the data for the appropriate placeholder.

Nota: As of PHP 4.1.1, this file reading functionality has the following restrictions:

  • File reading is not subject to any safe mode or open-basedir restrictions. This is fixed in PHP 4.2.0.

  • Remote files are not supported.

  • If you wish to store a string which actually begins and ends with single quotes, you must escape them or add a space or other non-single-quote character to the beginning or end of the parameter, which will prevent the parameter's being taken as a file name. If this is not an option, then you must use another mechanism to store the string, such as executing the query directly with odbc_exec()).

odbc_fetch_array

(PHP 4 >= 4.0.2)

odbc_fetch_array --  Fetch a result row as an associative array

Description

array odbc_fetch_array ( resource result [, int rownumber])

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

odbc_fetch_into

(PHP 3>= 3.0.6, PHP 4 )

odbc_fetch_into -- Fetch one result row into array

Description

bool odbc_fetch_into ( resource result_id [, int rownumber, array result_array])

resource odbc_fetch_into ( resource result_id, array result_array [, int rownumber])

Returns the number of columns in the result; FALSE on error. result_array must be passed by reference, but it can be of any type since it will be converted to type array. The array will contain the column values starting at array index 0.

As of PHP 4.0.5 the result_array does not need to be passed by reference any longer.

As of PHP 4.0.6 the rownumber cannot be passed as a constant, but rather as a variable.

As of PHP 4.2.0 the result_array and rownumber have been swapped. This allows the rownumber to be a constant again. This change will also be the last one to this function.

Exemplo 1. odbc_fetch_into() pre 4.0.6 example

$rc = odbc_fetch_into($res_id, $my_array);

or

$rc = odbc_fetch_into($res_id, $row, $my_array);
       
$rc = odbc_fetch_into($res_id, 1, $my_array);

Exemplo 2. odbc_fetch_into() 4.0.6 example

$rc = odbc_fetch_into($res_id, $my_array);

or

$row = 1;
$rc = odbc_fetch_into($res_id, $row, $my_array);

Exemplo 3. odbc_fetch_into() 4.2.0 example

$rc = odbc_fetch_into($res_id, $my_array);

or

$rc = odbc_fetch_into($res_id,$my_array, 2);

odbc_fetch_object

(PHP 4 >= 4.0.2)

odbc_fetch_object --  Fetch a result row as an object

Description

object odbc_fetch_object ( resource result [, int rownumber])

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

odbc_fetch_row

(PHP 3>= 3.0.6, PHP 4 )

odbc_fetch_row -- Fetch a row

Description

bool odbc_fetch_row ( resource result_id [, int row_number])

If odbc_fetch_row() was succesful (there was a row), TRUE is returned. If there are no more rows, FALSE is returned.

odbc_fetch_row() fetches a row of the data that was returned by odbc_do() / odbc_exec(). After odbc_fetch_row() is called, the fields of that row can be accessed with odbc_result().

If row_number is not specified, odbc_fetch_row() will try to fetch the next row in the result set. Calls to odbc_fetch_row() with and without row_number can be mixed.

To step through the result more than once, you can call odbc_fetch_row() with row_number 1, and then continue doing odbc_fetch_row() without row_number to review the result. If a driver doesn't support fetching rows by number, the row_number parameter is ignored.

odbc_field_len

(PHP 3>= 3.0.6, PHP 4 )

odbc_field_len -- Get the length (precision) of a field

Description

int odbc_field_len ( resource result_id, int field_number)

odbc_field_len() will return the length of the field referecend by number in the given ODBC result identifier. Field numbering starts at 1.

See also: odbc_field_scale() to get the scale of a floating point number.

odbc_field_name

(PHP 3>= 3.0.6, PHP 4 )

odbc_field_name -- Get the columnname

Description

string odbc_field_name ( resource result_id, int field_number)

odbc_field_name() will return the name of the field occupying the given column number in the given ODBC result identifier. Field numbering starts at 1. FALSE is returned on error.

odbc_field_num

(PHP 3>= 3.0.6, PHP 4 )

odbc_field_num -- Return column number

Description

int odbc_field_num ( resource result_id, string field_name)

odbc_field_num() will return the number of the column slot that corresponds to the named field in the given ODBC result identifier. Field numbering starts at 1. FALSE is returned on error.

odbc_field_precision

(PHP 4 )

odbc_field_precision -- Synonym for odbc_field_len()

Description

string odbc_field_precision ( resource result_id, int field_number)

odbc_field_precision() will return the precision of the field referecend by number in the given ODBC result identifier.

See also: odbc_field_scale() to get the scale of a floating point number.

odbc_field_scale

(PHP 4 )

odbc_field_scale -- Get the scale of a field

Description

string odbc_field_scale ( resource result_id, int field_number)

odbc_field_precision() will return the scale of the field referecend by number in the given ODBC result identifier.

odbc_field_type

(PHP 3>= 3.0.6, PHP 4 )

odbc_field_type -- Datatype of a field

Description

string odbc_field_type ( resource result_id, int field_number)

odbc_field_type() will return the SQL type of the field referecend by number in the given ODBC result identifier. Field numbering starts at 1.

odbc_foreignkeys

(PHP 4 )

odbc_foreignkeys --  Returns a list of foreign keys in the specified table or a list of foreign keys in other tables that refer to the primary key in the specified table

Description

resource odbc_foreignkeys ( resource connection_id, string pk_qualifier, string pk_owner, string pk_table, string fk_qualifier, string fk_owner, string fk_table)

odbc_foreignkeys() retrieves information about foreign keys. Returns an ODBC result identifier or FALSE on failure.

The result set has the following columns:

  • PKTABLE_QUALIFIER

  • PKTABLE_OWNER

  • PKTABLE_NAME

  • PKCOLUMN_NAME

  • FKTABLE_QUALIFIER

  • FKTABLE_OWNER

  • FKTABLE_NAME

  • FKCOLUMN_NAME

  • KEY_SEQ

  • UPDATE_RULE

  • DELETE_RULE

  • FK_NAME

  • PK_NAME

If pk_table contains a table name, odbc_foreignkeys() returns a result set containing the primary key of the specified table and all of the foreign keys that refer to it.

If fk_table contains a table name, odbc_foreignkeys() returns a result set containing all of the foreign keys in the specified table and the primary keys (in other tables) to which they refer.

If both pk_table and fk_table contain table names, odbc_foreignkeys() returns the foreign keys in the table specified in fk_table that refer to the primary key of the table specified in pk_table. This should be one key at most.

odbc_free_result

(PHP 3>= 3.0.6, PHP 4 )

odbc_free_result -- Free resources associated with a result

Description

bool odbc_free_result ( resource result_id)

Always returns TRUE.

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

Nota: If auto-commit is disabled (see odbc_autocommit()) and you call odbc_free_result() before commiting, all pending transactions are rolled back.

odbc_gettypeinfo

(PHP 4 )

odbc_gettypeinfo --  Returns a result identifier containing information about data types supported by the data source.

Description

int odbc_gettypeinfo ( resource connection_id [, int data_type])

Retrieves information about data types supported by the data source. Returns an ODBC result identifier or FALSE on failure. The optional argument data_type can be used to restrict the information to a single data type.

The result set has the following columns:

  • TYPE_NAME

  • DATA_TYPE

  • PRECISION

  • LITERAL_PREFIX

  • LITERAL_SUFFIX

  • CREATE_PARAMS

  • NULLABLE

  • CASE_SENSITIVE

  • SEARCHABLE

  • UNSIGNED_ATTRIBUTE

  • MONEY

  • AUTO_INCREMENT

  • LOCAL_TYPE_NAME

  • MINIMUM_SCALE

  • MAXIMUM_SCALE

The result set is ordered by DATA_TYPE and TYPE_NAME.

odbc_longreadlen

(PHP 3>= 3.0.6, PHP 4 )

odbc_longreadlen -- Handling of LONG columns

Description

int odbc_longreadlen ( resource result_id, int length)

(ODBC SQL types affected: LONG, LONGVARBINARY) The number of bytes returned to PHP is controled by the parameter length. If it is set to 0, Long column data is passed thru to the client.

Nota: Handling of LONGVARBINARY columns is also affected by odbc_binmode().

odbc_next_result

(PHP 4 >= 4.0.5)

odbc_next_result --  Checks if multiple results are avaiable

Description

bool odbc_next_result ( resource result_id)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

odbc_num_fields

(PHP 3>= 3.0.6, PHP 4 )

odbc_num_fields -- Number of columns in a result

Description

int odbc_num_fields ( resource result_id)

odbc_num_fields() will return the number of fields (columns) in an ODBC result. This function will return -1 on error. The argument is a valid result identifier returned by odbc_exec().

odbc_num_rows

(PHP 3>= 3.0.6, PHP 4 )

odbc_num_rows -- Number of rows in a result

Description

int odbc_num_rows ( resource result_id)

odbc_num_rows() will return the number of rows in an ODBC result. This function will return -1 on error. For INSERT, UPDATE and DELETE statements odbc_num_rows() returns the number of rows affected. For a SELECT clause this can be the number of rows available.

Note: Using odbc_num_rows() to determine the number of rows available after a SELECT will return -1 with many drivers.

odbc_pconnect

(PHP 3>= 3.0.6, PHP 4 )

odbc_pconnect -- Open a persistent database connection

Description

resource odbc_pconnect ( string dsn, string user, string password [, int cursor_type])

Returns an ODBC connection id or 0 (FALSE) on error. This function is much like odbc_connect(), except that the connection is not really closed when the script has finished. Future requests for a connection with the same dsn, user, password combination (via odbc_connect() and odbc_pconnect()) can reuse the persistent connection.

Nota: Persistent connections have no effect if PHP is used as a CGI program.

For information about the optional cursor_type parameter see the odbc_connect() function. For more information on persistent connections, refer to the PHP FAQ.

odbc_prepare

(PHP 3>= 3.0.6, PHP 4 )

odbc_prepare -- Prepares a statement for execution

Description

resource odbc_prepare ( resource connection_id, string query_string)

Returns FALSE on error.

Returns an ODBC result identifier if the SQL command was prepared successfully. The result identifier can be used later to execute the statement with odbc_execute().

odbc_primarykeys

(PHP 4 )

odbc_primarykeys --  Returns a result identifier that can be used to fetch the column names that comprise the primary key for a table

Description

resource odbc_primarykeys ( resource connection_id, string qualifier, string owner, string table)

Returns the column names that comprise the primary key for a table. Returns an ODBC result identifier or FALSE on failure.

The result set has the following columns:

  • TABLE_QUALIFIER

  • TABLE_OWNER

  • TABLE_NAME

  • COLUMN_NAME

  • KEY_SEQ

  • PK_NAME

odbc_procedurecolumns

(PHP 4 )

odbc_procedurecolumns --  Retrieve information about parameters to procedures

Description

resource odbc_procedurecolumns ( resource connection_id [, string qualifier [, string owner [, string proc [, string column]]]])

Returns the list of input and output parameters, as well as the columns that make up the result set for the specified procedures. Returns an ODBC result identifier or FALSE on failure.

The result set has the following columns:

  • PROCEDURE_QUALIFIER

  • PROCEDURE_OWNER

  • PROCEDURE_NAME

  • COLUMN_NAME

  • COLUMN_TYPE

  • DATA_TYPE

  • TYPE_NAME

  • PRECISION

  • LENGTH

  • SCALE

  • RADIX

  • NULLABLE

  • REMARKS

The result set is ordered by PROCEDURE_QUALIFIER, PROCEDURE_OWNER, PROCEDURE_NAME and COLUMN_TYPE.

The owner, proc and column arguments accept search patterns ('%' to match zero or more characters and '_' to match a single character).

odbc_procedures

(PHP 4 )

odbc_procedures --  Get the list of procedures stored in a specific data source. Returns a result identifier containing the information.

Description

resource odbc_procedures ( resource connection_id [, string qualifier [, string owner [, string name]]])

Lists all procedures in the requested range. Returns an ODBC result identifier or FALSE on failure.

The result set has the following columns:

  • PROCEDURE_QUALIFIER

  • PROCEDURE_OWNER

  • PROCEDURE_NAME

  • NUM_INPUT_PARAMS

  • NUM_OUTPUT_PARAMS

  • NUM_RESULT_SETS

  • REMARKS

  • PROCEDURE_TYPE

The owner and name arguments accept search patterns ('%' to match zero or more characters and '_' to match a single character).

odbc_result_all

(PHP 3>= 3.0.6, PHP 4 )

odbc_result_all -- Print result as HTML table

Description

int odbc_result_all ( resource result_id [, string format])

Returns the number of rows in the result or FALSE on error.

odbc_result_all() will print all rows from a result identifier produced by odbc_exec(). The result is printed in HTML table format. With the optional string argument format, additional overall table formatting can be done.

odbc_result

(PHP 3>= 3.0.6, PHP 4 )

odbc_result -- Get result data

Description

string odbc_result ( resource result_id, mixed field)

Returns the contents of the field.

field can either be an integer containing the column number of the field you want; or it can be a string containing the name of the field. For example:

$item_3 = odbc_result ($Query_ID, 3);
$item_val = odbc_result ($Query_ID, "val");

The first call to odbc_result() returns the value of the third field in the current record of the query result. The second function call to odbc_result() returns the value of the field whose field name is "val" in the current record of the query result. An error occurs if a column number parameter for a field is less than one or exceeds the number of columns (or fields) in the current record. Similarly, an error occurs if a field with a name that is not one of the fieldnames of the table(s) that is(are) being queried.

Field indices start from 1. Regarding the way binary or long column data is returned refer to odbc_binmode() and odbc_longreadlen().

odbc_rollback

(PHP 3>= 3.0.6, PHP 4 )

odbc_rollback -- Rollback a transaction

Description

int odbc_rollback ( resource connection_id)

Rolls back all pending statements on connection_id. Returns TRUE on success, FALSE on failure.

odbc_setoption

(PHP 3>= 3.0.6, PHP 4 )

odbc_setoption --  Adjust ODBC settings. Returns FALSE if an error occurs, otherwise TRUE.

Description

int odbc_setoption ( resource id, int function, int option, int param)

This function allows fiddling with the ODBC options for a particular connection or query result. It was written to help find work arounds to problems in quirky ODBC drivers. You should probably only use this function if you are an ODBC programmer and understand the effects the various options will have. You will certainly need a good ODBC reference to explain all the different options and values that can be used. Different driver versions support different options.

Because the effects may vary depending on the ODBC driver, use of this function in scripts to be made publicly available is strongly discouraged. Also, some ODBC options are not available to this function because they must be set before the connection is established or the query is prepared. However, if on a particular job it can make PHP work so your boss doesn't tell you to use a commercial product, that's all that really matters.

id is a connection id or result id on which to change the settings.For SQLSetConnectOption(), this is a connection id. For SQLSetStmtOption(), this is a result id.

Function is the ODBC function to use. The value should be 1 for SQLSetConnectOption() and 2 for SQLSetStmtOption().

Parameter option is the option to set.

Parameter param is the value for the given option.

Exemplo 1. ODBC Setoption Examples

// 1. Option 102 of SQLSetConnectOption() is SQL_AUTOCOMMIT.
//    Value 1 of SQL_AUTOCOMMIT is SQL_AUTOCOMMIT_ON.
//    This example has the same effect as
//    odbc_autocommit($conn, true);

odbc_setoption ($conn, 1, 102, 1);

// 2. Option 0 of SQLSetStmtOption() is SQL_QUERY_TIMEOUT.
//    This example sets the query to timeout after 30 seconds.

$result = odbc_prepare ($conn, $sql);
odbc_setoption ($result, 2, 0, 30);
odbc_execute ($result);

odbc_specialcolumns

(PHP 4 )

odbc_specialcolumns --  Returns either the optimal set of columns that uniquely identifies a row in the table or columns that are automatically updated when any value in the row is updated by a transaction

Description

resource odbc_specialcolumns ( resource connection_id, int type, string qualifier, string owner, string table, int scope, int nullable)

When the type argument is SQL_BEST_ROWID, odbc_specialcolumns() returns the column or columns that uniquely identify each row in the table.

When the type argument is SQL_ROWVER, odbc_specialcolumns() returns the optimal column or set of columns that, by retrieving values from the column or columns, allows any row in the specified table to be uniquely identified.

Returns an ODBC result identifier or FALSE on failure.

The result set has the following columns:

  • SCOPE

  • COLUMN_NAME

  • DATA_TYPE

  • TYPE_NAME

  • PRECISION

  • LENGTH

  • SCALE

  • PSEUDO_COLUMN

The result set is ordered by SCOPE.

odbc_statistics

(PHP 4 )

odbc_statistics -- Retrieve statistics about a table

Description

resource odbc_statistics ( resource connection_id, string qualifier, string owner, string table_name, int unique, int accuracy)

Get statistics about a table and it's indexes. Returns an ODBC result identifier or FALSE on failure.

The result set has the following columns:

  • TABLE_QUALIFIER

  • TABLE_OWNER

  • TABLE_NAME

  • NON_UNIQUE

  • INDEX_QUALIFIER

  • INDEX_NAME

  • TYPE

  • SEQ_IN_INDEX

  • COLUMN_NAME

  • COLLATION

  • CARDINALITY

  • PAGES

  • FILTER_CONDITION

The result set is ordered by NON_UNIQUE, TYPE, INDEX_QUALIFIER, INDEX_NAME and SEQ_IN_INDEX.

odbc_tableprivileges

(PHP 4 )

odbc_tableprivileges --  Lists tables and the privileges associated with each table

Description

int odbc_tableprivileges ( resource connection_id [, string qualifier [, string owner [, string name]]])

Lists tables in the requested range and the privileges associated with each table. Returns an ODBC result identifier or FALSE on failure.

The result set has the following columns:

  • TABLE_QUALIFIER

  • TABLE_OWNER

  • TABLE_NAME

  • GRANTOR

  • GRANTEE

  • PRIVILEGE

  • IS_GRANTABLE

The result set is ordered by TABLE_QUALIFIER, TABLE_OWNER and TABLE_NAME.

The owner and name arguments accept search patterns ('%' to match zero or more characters and '_' to match a single character).

odbc_tables

(PHP 3>= 3.0.17, PHP 4 )

odbc_tables --  Get the list of table names stored in a specific data source. Returns a result identifier containing the information.

Description

int odbc_tables ( resource connection_id [, string qualifier [, string owner [, string name [, string types]]]])

Lists all tables in the requested range. Returns an ODBC result identifier or FALSE on failure.

The result set has the following columns:

  • TABLE_QUALIFIER

  • TABLE_OWNER

  • TABLE_NAME

  • TABLE_TYPE

  • REMARKS

The result set is ordered by TABLE_TYPE, TABLE_QUALIFIER, TABLE_OWNER and TABLE_NAME.

The owner and name arguments accept search patterns ('%' to match zero or more characters and '_' to match a single character).

To support enumeration of qualifiers, owners, and table types, the following special semantics for the qualifier, owner, name, and table_type are available:

  • If qualifier is a single percent character (%) and owner and name are empty strings, then the result set contains a list of valid qualifiers for the data source. (All columns except the TABLE_QUALIFIER column contain NULLs.)

  • If owner is a single percent character (%) and qualifier and name are empty strings, then the result set contains a list of valid owners for the data source. (All columns except the TABLE_OWNER column contain NULLs.)

  • If table_type is a single percent character (%) and qualifier, owner and name are empty strings, then the result set contains a list of valid table types for the data source. (All columns except the TABLE_TYPE column contain NULLs.)

If table_type is not an empty string, it must contain a list of comma-separated values for the types of interest; each value may be enclosed in single quotes (') or unquoted. For example, "'TABLE','VIEW'" or "TABLE, VIEW". If the data source does not support a specified table type, odbc_tables() does not return any results for that type.

See also odbc_tableprivileges() to retrieve associated privileges.

LXX. Object Aggregation/Composition Functions

Atenção

Este módulo é EXPERIMENTAL. Isso quer dizer que o comportamento neste módulo --- incluindo suas funções e seus nomes, e TUDO mais que está documentado sobre esse módulo --- poderá mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use este módulo por sua própria conta e risco.


Introdução

In Object Oriented Programming, it is common to see the composition of simple classes (and/or instances) into a more complex one. This is a flexible strategy for building complicated objects and object hierachies and can function as a dynamic alternative to multiple inheritance. There are two ways to perform class (and/or object) composition depending on the relationship between the composed elements: Association and Aggregation.

An Association is a composition of independently constructed and externally visible parts. When we associate classes or objects, each one keeps a reference to the ones it is associated with. When we associate classes statically, one class will contain a reference to an instance of the other class. For example:

Exemplo 1. Class association

class DateTime {
   
   function DateTime() {
       // empty constructor
   }

   function now() {
       return date("Y-m-d H:i:s");
   }
}

class Report {
   var $_dt = new DateTime();
   // more properties ...

   function Report() {
       // initialization code ...
   }

   function generateReport() {
       $dateTime = $_dt->now();
       // more code ...
   }

   // more methods ...
}

$rep = new Report();
We can also associate instances at runtime by passing a reference in a constructor (or any other method), which allow us to dynamically change the association relationship between objects. We will modify the example above to illustrate this point:

Exemplo 2. Object association

class DateTime {
   // same as previous example
}

class DateTimePlus {
   var $_format;
   
   function DateTimePlus($format="Y-m-d H:i:s") {
       $this->_format = $format
   }

   function now() {
       return date($this->_format);
   }
}

class Report {
   var $_dt;    // we'll keep the reference to DateTime here
   // more properties ...

   function Report() {
       // do some initialization
   }

   function setDateTime(&$dt) {
       $this->_dt =& $dt;
   }

   function generateReport() {
       $dateTime = $_dt->now();
       // more code ...
   }

   // more methods ...
}

$rep = new Report();
$dt = new DateTime();
$dtp = new DateTimePlus("l, F j, Y (h:i:s a, T)");

// generate report with simple date for web display
$rep->setDateTime(&$dt);
echo $rep->generateReport();

// later on in the code ...

// generate report with fancy date
$rep->setDateTime(&$dtp);
$output = $rep->generateReport();
// save $output in database
// ... etc ...

Aggregation, on the other hand, implies encapsulation (hidding) of the parts of the composition. We can aggregate classes by using a (static) inner class (PHP does not yet support inner classes), in this case the aggregated class definition is not accessible, except through the class that contains it. The aggregation of instances (object aggregation) involves the dynamic creation of subobjects inside an object, in the process, expanding the properties and methods of that object.

Object aggregation is a natural way of representing a whole-part relationship, (for example, molecules are aggregates of atoms), or can be used to obtain an effect equivalent to multiple inheritance, without having to permanently bind a subclass to two or more parent classes and their interfaces. In fact object aggregation can be more flexible, in which we can select what methods or properties to "inherit" in the aggregated object.


Exemplos

We define 3 classes, each implementing a different storage method:

Exemplo 3. storage_classes.inc

<?php
class FileStorage {
    var $data;

    function FileStorage($data) {
        $this->data = $data;
    }
    function write($name) {
        $fp = fopen(name, "w");
        fwrite($fp, $this->data);
        fclose($data);
    }
}

class WDDXStorage {
    var $data;
    var $version = "1.0";
    var $_id; // "private" variable

    function WDDXStorage($data) {
        $this->data = $data;
        $this->_id = $this->_genID();
    }

    function store() {
        if ($this->_id) {
            $pid = wddx_packet_start($this->_id);
            wddx_add_vars($pid, "this->data");
            $packet = wddx_packet_end($pid);
        } else {
            $packet = wddx_serialize_value($this->data);
        }
        $dbh = dba_open("varstore", "w", "gdbm");
        dba_insert(md5(uniqid("",true)), $packet, $dbh);
        dba_close($dbh);
    }

    // a private method
    function _genID() {
        return md5(uniqid(rand(),true));
    }
}

class DBStorage {
    var $data;
    var $dbtype = "mysql";

    function DBStorage($data) {
        $this->data = $data;
    }

    function save() {
        $dbh = mysql_connect();
        mysql_select_db("storage", $dbh);
        $serdata = serialize($this->data);
        mysql_query("insert into vars ('$serdata',now())", $dbh);
        mysql_close($dbh);
    }
}

?>

We then instantiate a couple of objects from the defined classes, and perform some aggregations and deaggregations, printing some object information along the way:

Exemplo 4. test_aggregation.php

<?php
include "storageclasses.inc";

// some utilty functions

function p_arr($arr) {
    foreach($arr as $k=>$v)
        $out[] = "\t$k => $v";
    return implode("\n", $out);
}

function object_info($obj) {
    $out[] = "Class: ".get_class($obj);
    foreach(get_object_vars($obj) as $var=>$val)
        if (is_array($val))
            $out[] = "property: $var (array)\n".p_arr($val);
        else
            $out[] = "property: $var = $val";
    foreach(get_class_methods($obj) as $method)
        $out[] = "method: $method";
    return implode("\n", $out);
}


$data = array(M_PI, "kludge != cruft");

// we create some basic objects
$fs = new FileStorage($data);
$ws = new WDDXStorage($data);

// print information on the objects
echo "\$fs object\n";
echo object_info($fs)."\n";
echo "\n\$ws object\n";
echo object_info($ws)."\n";

// do some aggregation

echo "\nLet's aggregate \$fs to the WDDXStorage class\n";
aggregate($fs, "WDDXStorage");
echo "\$fs object\n";
echo object_info($fs)."\n";

echo "\nNow let us aggregate it to the DBStorage class\n";
aggregate($fs, "DBStorage");
echo "\$fs object\n";
echo object_info($fs)."\n";

echo "\nAnd finally deaggregate WDDXStorage\n";
deaggregate($fs, "WDDXStorage");
echo "\$fs object\n";
echo object_info($fs)."\n";

?>

We will now consider the output to understand some of the side-effects and limitation of object aggregation in PHP. First, the newly created $fs and $ws objects give the expected output (according to their respective class declaration). Note that for the purposes of object aggregation, private elements of a class/object begin with an underscore character ("_"), even though there is not real distinction between public and private class/object elements in PHP.

$fs object
Class: filestorage
property: data (array)
    0 => 3.1415926535898
    1 => kludge != cruft
method: filestorage
method: write

$ws object
Class: wddxstorage
property: data (array)
    0 => 3.1415926535898
    1 => kludge != cruft
property: version = 1.0
property: _id = ID::9bb2b640764d4370eb04808af8b076a5
method: wddxstorage
method: store
method: _genid

We then aggregate $fs with the WDDXStorage class, and print out the object information. We can see now that even though nominally the $fs object is still of FileStorage, it now has the property $version, and the method store(), both defined in WDDXStorage. One important thing to note is that it has not aggregated the private elements defined in the class, which are present in the $ws object. Also absent is the constructor from WDDXStorage, which will not be logical to aggegate.

Let's aggregate $fs to the WDDXStorage class
$fs object
Class: filestorage
property: data (array)
    0 => 3.1415926535898
    1 => kludge != cruft
property: version = 1.0
method: filestorage
method: write
method: store

The proccess of aggregation is cummulative, so when we aggregate $fs with the class DBStorage, generating an object that can use the storage methods of all the defined classes.

Now let us aggregate it to the DBStorage class
$fs object
Class: filestorage
property: data (array)
    0 => 3.1415926535898
    1 => kludge != cruft
property: version = 1.0
property: dbtype = mysql
method: filestorage
method: write
method: store
method: save

Finally, the same way we aggregated properties and methods dynamically, we can also deaggregate them from the object. So, if we deaggregate the class WDDXStorage from $fs, we will obtain:

And deaggregate the WDDXStorage methods and properties
$fs object
Class: filestorage
property: data (array)
    0 => 3.1415926535898
    1 => kludge != cruft
property: dbtype = mysql
method: filestorage
method: write
method: save

One point that we have not mentioned above, is that the process of aggregation will not override existing properties or methods in the objects. For example, the class FileStorage defines a $data property, and the class WDDXStorage also defines a similar property which will not override the one in the object acquired during instantiation from the class FileStorage.

Índice
aggregate_info --  returns an associative array of the methods and properties from each class that has been aggregated to the object.
aggregate_methods_by_list --  selective dynamic class methods aggregation to an object
aggregate_methods_by_regexp --  selective class methods aggregation to an object using a regular expression
aggregate_methods --  dynamic class and object aggregation of methods
aggregate_properties_by_list --  selective dynamic class properties aggregation to an object
aggregate_properties_by_regexp --  selective class properties aggregation to an object using a regular expression
aggregate_properties --  dynamic aggregation of class properties to an object
aggregate --  dynamic class and object aggregation of methods and properties
aggregation_info -- Synonym for aggregate_info()
deaggregate --  removes the aggregated methods and properties from an object

aggregate_info

(PHP 5 CVS only)

aggregate_info --  returns an associative array of the methods and properties from each class that has been aggregated to the object.

Description

array aggregate_info ( object object)

Will return the aggretaion information for a particular object as an associative array of arrays of methods and properties. The key for the main array is the name of the aggregated class.

For example the code below

Exemplo 1. Using aggregate_info()

<?php

class Slicer {
    var $vegetable;

    function Slicer($vegetable) {
        $this->vegetable = $vegetable;
    }

    function slice_it($num_cuts) {
        echo "Doing some simple slicing\n";
        for ($i=0; $i < $num_cuts; $i++) {
            // do some slicing
        }
    }
}

class Dicer {
    var $vegetable;
    var $rotation_angle = 90;   // degrees

    function Dicer($vegetable) {
        $this->vegetable = $vegetable;
    }

    function dice_it($num_cuts) {
        echo "Cutting in one direction\n";
        for ($i=0; $i < $num_cuts; $i++) {
            // do some cutting
        }
        $this->rotate($this->rotation_angle);
        echo "Cutting in a second direction\n";
        for ($i=0; $i < $num_cuts; $i++) {
            // do some more cutting
        }
    }

    function rotate($deg) {
        echo "Now rotating {$this->vegetable} {$deg} degrees\n";
    }

    function _secret_super_dicing($num_cuts) {
        // so secret we cannot show you ;-)
    }
}

$obj = new Slicer('onion');
aggregate($obj, 'Dicer');
print_r(aggregate_info($obj));
?>

Will produce the output

Array
(
    [dicer] => Array
        (
            [methods] => Array
                (
                    [0] => dice_it
                    [1] => rotate
                )

            [properties] => Array
                (
                    [0] => rotation_angle
                )

        )

)

As you can see, all properties and methods of the Dicer class have been aggregated into our new object, with the exception of the class constructor and the method _secret_super_dicing

See also aggregate(), aggregate_methods(), aggregate_methods_by_list(), aggregate_methods_by_regexp(), aggregate_properties(), aggregate_properties_by_list(), aggregate_properties_by_regexp(), deaggregate()

aggregate_methods_by_list

(PHP 4 >= 4.2.0)

aggregate_methods_by_list --  selective dynamic class methods aggregation to an object

Description

void aggregate_methods_by_list ( object object, string class_name, array methods_list [, boolean exclude])

Aggregates methods from a class to an existing object using a list of method names. The optional paramater exclude is used to decide whether the list contains the names of methods to include in the aggregation (i.e. exclude is FALSE, which is the default value), or to exclude from the aggregation (exclude is TRUE).

The class constructor or methods whose names start with an underscore character (_), which are considered private to the aggregated class, are always excluded.

See also aggregate(), aggregate_info(), aggregate_methods(), aggregate_methods_by_regexp(), aggregate_properties(), aggregate_properties_by_list(), aggregate_properties_by_regexp(), deaggregate()

aggregate_methods_by_regexp

(PHP 4 >= 4.2.0)

aggregate_methods_by_regexp --  selective class methods aggregation to an object using a regular expression

Description

void aggregate_methods_by_regexp ( object object, string class_name, string regexp [, boolean exclude])

Aggregates methods from a class to an existing object using a regular expresion to match method names. The optional paramater exclude is used to decide whether the regular expression will select the names of methods to include in the aggregation (i.e. exclude is FALSE, which is the default value), or to exclude from the aggregation (exclude is TRUE).

The class constructor or methods whose names start with an underscore character (_), which are considered private to the aggregated class, are always excluded.

See also aggregate(), aggregate_info(), aggregate_methods(), aggregate_methods_by_list(), aggregate_properties(), aggregate_properties_by_list(), aggregate_properties_by_regexp(), deaggregate()

aggregate_methods

(PHP 4 >= 4.2.0)

aggregate_methods --  dynamic class and object aggregation of methods

Description

void aggregate_methods ( object object, string class_name)

Aggregates all methods defined in a class to an existing object, except for the class constructor, or methods whose names start with an underscore character (_) which are considered private to the aggregated class.

See also aggregate(), aggregate_info(), aggregate_methods_by_list(), aggregate_methods_by_regexp(), aggregate_properties(), aggregate_properties_by_list(), aggregate_properties_by_regexp(), deaggregate()

aggregate_properties_by_list

(PHP 4 >= 4.2.0)

aggregate_properties_by_list --  selective dynamic class properties aggregation to an object

Description

void aggregate_properties_by_list ( object object, string class_name, array properties_list [, boolean exclude])

Aggregates properties from a class to an existing object using a list of property names. The optional paramater exclude is used to decide whether the list contains the names of class properties to include in the aggregation (i.e. exclude is FALSE, which is the default value), or to exclude from the aggregation (exclude is TRUE).

The properties whose names start with an underscore character (_), which are considered private to the aggregated class, are always excluded.

See also aggregate(), aggregate_methods(), aggregate_methods_by_list(), aggregate_methods_by_regexp(), aggregate_properties(), aggregate_properties_by_regexp(), aggregate_info(), deaggregate()

aggregate_properties_by_regexp

(PHP 4 >= 4.2.0)

aggregate_properties_by_regexp --  selective class properties aggregation to an object using a regular expression

Description

void aggregate_properties_by_regexp ( object object, string class_name, string regexp [, boolean exclude])

Aggregates properties from a class to an existing object using a regular expresion to match their names. The optional paramater exclude is used to decide whether the regular expression will select the names of class properties to include in the aggregation (i.e. exclude is FALSE, which is the default value), or to exclude from the aggregation (exclude is TRUE).

The properties whose names start with an underscore character (_), which are considered private to the aggregated class, are always excluded.

See also aggregate(), aggregate_methods(), aggregate_methods_by_list(), aggregate_methods_by_regexp(), aggregate_properties(), aggregate_properties_by_list(), aggregate_info(), deaggregate()

aggregate_properties

(PHP 4 >= 4.2.0)

aggregate_properties --  dynamic aggregation of class properties to an object

Description

void aggregate_properties ( object object, string class_name)

Aggregates all properties defined in a class to an existing object, except for properties whose names start with an underscore character (_) which are considered private to the aggregated class.

See also aggregate(), aggregate_methods(), aggregate_methods_by_list(), aggregate_methods_by_regexp(), aggregate_properties_by_list(), aggregate_properties_by_regexp(), aggregate_info(), deaggregate()

aggregate

(PHP 4 >= 4.2.0)

aggregate --  dynamic class and object aggregation of methods and properties

Description

void aggregate ( object object, string class_name)

Aggregates methods and properties defined in a class to an existing object. Methods and properties with names starting with an underscore character (_) are considered private to the aggregated class and are not used, constructors are also excluded from the aggregation procedure.

See also aggregate_info(), aggregate_methods(), aggregate_methods_by_list(), aggregate_methods_by_regexp(), aggregate_properties(), aggregate_properties_by_list(), aggregate_properties_by_regexp(), deaggregate()

aggregation_info

(PHP 4 >= 4.2.0)

aggregation_info -- Synonym for aggregate_info()

Description

array aggregation_info ( object object)

Will return the aggretaion information for a particular object as an associative array of arrays of methods and properties. The key for the main array is the name of the aggregated class.

deaggregate

(PHP 4 >= 4.2.0)

deaggregate --  removes the aggregated methods and properties from an object

Description

void object_aggregation ( object object [, string class_name])

Removes the methods and properties from classes that were aggregated to an object. If the optional class_name parameters is passed, only those methods and properties defined in that class are removed, otherwise all aggregated methods and properties are eliminated.

See also aggregate(), aggregate_methods(), aggregate_methods_by_list(), aggregate_methods_by_regexp(), aggregate_properties(), aggregate_properties_by_list(), aggregate_properties_by_regexp(), aggregate_info()

LXXI. Oracle 8 functions

Introdução

These functions allow you to access Oracle8 and Oracle7 databases. It uses the Oracle8 Call-Interface (OCI8)

This extension is more flexible than the standard Oracle extension. It supports binding of global and local PHP variables to Oracle placeholders, has full LOB, FILE and ROWID support and allows you to use user-supplied define variables.


Requisitos

You will need the Oracle8 client libraries to use this extension.

Before using this extension, make sure that you have set up your Oracle environment variables properly for the Oracle user, as well as your web daemon user. The variables you might need to set are as follows:

  • ORACLE_HOME

  • ORACLE_SID

  • LD_PRELOAD

  • LD_LIBRARY_PATH

  • NLS_LANG

  • ORA_NLS33

After setting up the environment variables for your webserver user, be sure to also add the webserver user (nobody, www) to the oracle group.

If your webserver doesn't start or crashes at startup: Check that Apache is linked with the pthread library:

# ldd /www/apache/bin/httpd 
    libpthread.so.0 => /lib/libpthread.so.0 (0x4001c000)
    libm.so.6 => /lib/libm.so.6 (0x4002f000)
    libcrypt.so.1 => /lib/libcrypt.so.1 (0x4004c000)
    libdl.so.2 => /lib/libdl.so.2 (0x4007a000)
    libc.so.6 => /lib/libc.so.6 (0x4007e000)
    /lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x40000000)

If the libpthread is not listed you have to reinstall Apache:

# cd /usr/src/apache_1.3.xx
# make clean
# LIBS=-lpthread ./config.status
# make
# make install

Please note that on some systems like UnixWare it is libthread instead of libpthread. PHP and Apache have to be configured with EXTRA_LIBS=-lthread.


Instalação

You have to compile PHP with the option --with-oci8[=DIR], where DIR defaults to your environmment variable ORACLE_HOME.


Configuração durante execução

Esta extenção não define nenhum parâmetro de configuração no php.ini.


Tipos Resource


Constantes Predefinidas

As contantes abaixo são definidas por esta extensão e somente estarão disponíveis quando a extensão foi compilada com o PHP ou carregada dinamicamente durante a execução.

OCI_DEFAULT (integer)

OCI_DESCRIBE_ONLY (integer)

OCI_COMMIT_ON_SUCCESS (integer)

OCI_EXACT_FETCH (integer)

SQLT_BFILEE (integer)

SQLT_CFILEE (integer)

SQLT_CLOB (integer)

SQLT_BLOB (integer)

SQLT_RDD (integer)

OCI_B_SQLT_NTY (integer)

OCI_SYSDATE (integer)

OCI_B_BFILE (integer)

OCI_B_CFILEE (integer)

OCI_B_CLOB (integer)

OCI_B_BLOB (integer)

OCI_B_ROWID (integer)

OCI_B_CURSOR (integer)

OCI_B_BIN (integer)

OCI_FETCHSTATEMENT_BY_COLUMN (integer)

OCI_FETCHSTATEMENT_BY_ROW (integer)

OCI_ASSOC (integer)

OCI_NUM (integer)

OCI_BOTH (integer)

OCI_RETURN_NULLS (integer)

OCI_RETURN_LOBS (integer)

OCI_DTYPE_FILE (integer)

OCI_DTYPE_LOB (integer)

OCI_DTYPE_ROWID (integer)

OCI_D_FILE (integer)

OCI_D_LOB (integer)

OCI_D_ROWID (integer)


Exemplos

Exemplo 1. OCI Hints

<?php
// by sergo@bacup.ru

// Use option: OCI_DEFAULT for execute command to delay execution
OCIExecute($stmt, OCI_DEFAULT);

// for retrieve data use (after fetch):

$result = OCIResult($stmt, $n);
if (is_object ($result)) $result = $result->load();

// For INSERT or UPDATE statement use:

$sql = "insert into table (field1, field2) values (field1 = 'value',
 field2 = empty_clob()) returning field2 into :field2";
OCIParse($conn, $sql);
$clob = OCINewDescriptor($conn, OCI_D_LOB);
OCIBindByName ($stmt, ":field2", &$clob, -1, OCI_B_CLOB);
OCIExecute($stmt, OCI_DEFAULT);
$clob->save ("some text");
OCICommit($conn);

?>

You can easily access stored procedures in the same way as you would from the commands line.

Exemplo 2. Using Stored Procedures

<?php
// by webmaster@remoterealty.com
$sth = OCIParse ( $dbh, "begin sp_newaddress( :address_id, '$firstname',
 '$lastname', '$company', '$address1', '$address2', '$city', '$state',
 '$postalcode', '$country', :error_code );end;" );

// This calls stored procedure sp_newaddress, with :address_id being an
// in/out variable and :error_code being an out variable. 
// Then you do the binding:

   OCIBindByName ( $sth, ":address_id", $addr_id, 10 );
   OCIBindByName ( $sth, ":error_code", $errorcode, 10 );
   OCIExecute ( $sth );

?>

Índice
OCIBindByName --  Bind a PHP variable to an Oracle Placeholder
OCICancel -- Cancel reading from cursor
OCICollAppend -- Coming soon
OCICollAssign -- Coming soon
OCICollAssignElem -- Coming soon
OCICollGetElem -- Coming soon
OCICollMax -- Coming soon
OCICollSize -- Coming soon
OCICollTrim -- Coming soon
OCIColumnIsNULL -- Test whether a result column is NULL
OCIColumnName -- Returns the name of a column
OCIColumnPrecision -- Coming soon
OCIColumnScale -- Coming soon
OCIColumnSize -- Return result column size
OCIColumnType -- Returns the data type of a column
OCIColumnTypeRaw -- Coming soon
OCICommit -- Commits outstanding transactions
OCIDefineByName --  Use a PHP variable for the define-step during a SELECT
OCIError -- Return the last error of stmt|conn|global
OCIExecute -- Execute a statement
OCIFetch -- Fetches the next row into result-buffer
OCIFetchInto -- Fetches the next row into result-array
OCIFetchStatement -- Fetch all rows of result data into an array
OCIFreeCollection -- Coming soon
OCIFreeCursor --  Free all resources associated with a cursor
OCIFreeDesc -- Deletes a large object descriptor
OCIFreeStatement --  Free all resources associated with a statement
OCIInternalDebug --  Enables or disables internal debug output
OCILoadLob -- Coming soon
OCILogOff -- Disconnects from Oracle
OCILogon -- Establishes a connection to Oracle
OCINewCollection -- Coming soon
OCINewCursor --  Return a new cursor (Statement-Handle)
OCINewDescriptor --  Initialize a new empty LOB or FILE descriptor
OCINLogon -- Establishes a new connection to Oracle
OCINumCols --  Return the number of result columns in a statement
OCIParse -- Parse a query and return a statement
OCIPLogon -- Connect to an Oracle database using a persistent connection
OCIResult -- Returns column value for fetched row
OCIRollback -- Rolls back outstanding transactions
OCIRowCount -- Gets the number of affected rows
OCISaveLob -- Coming soon
OCISaveLobFile -- Coming soon
OCIServerVersion -- Return a string containing server version information
OCISetPrefetch -- Sets number of rows to be prefetched
OCIStatementType -- Return the type of an OCI statement
OCIWriteLobToFile -- Coming soon

OCIBindByName

(PHP 3>= 3.0.4, PHP 4 )

OCIBindByName --  Bind a PHP variable to an Oracle Placeholder

Description

bool OCIBindByName ( int stmt, string ph_name, mixed & variable, int length [, int type])

OCIBindByName() binds the PHP variable variable to the Oracle placeholder ph_name. Whether it will be used for input or output will be determined run-time, and the necessary storage space will be allocated. The length parameter sets the maximum length for the bind. If you set length to -1 OCIBindByName() will use the current length of variable to set the maximum length.

If you need to bind an abstract Datatype (LOB/ROWID/BFILE) you need to allocate it first using OCINewDescriptor() function. The length is not used for abstract Datatypes and should be set to -1. The type variable tells oracle, what kind of descriptor we want to use. Possible values are: OCI_B_FILE (Binary-File), OCI_B_CFILE (Character-File), OCI_B_CLOB (Character-LOB), OCI_B_BLOB (Binary-LOB) and OCI_B_ROWID (ROWID).

Exemplo 1. OCIDefineByName

<?php
/* OCIBindByPos example thies@thieso.net (980221)
  inserts 3 records into emp, and uses the ROWID for updating the 
  records just after the insert.
*/

$conn = OCILogon("scott","tiger");

$stmt = OCIParse($conn,"insert into emp (empno, ename) ".
					   "values (:empno,:ename) ".
					   "returning ROWID into :rid");

$data = array(1111 => "Larry", 2222 => "Bill", 3333 => "Jim");

$rowid = OCINewDescriptor($conn,OCI_D_ROWID);

OCIBindByName($stmt,":empno",&$empno,32);
OCIBindByName($stmt,":ename",&$ename,32);
OCIBindByName($stmt,":rid",&$rowid,-1,OCI_B_ROWID);

$update = OCIParse($conn,"update emp set sal = :sal where ROWID = :rid");
OCIBindByName($update,":rid",&$rowid,-1,OCI_B_ROWID);
OCIBindByName($update,":sal",&$sal,32);

$sal = 10000;

while (list($empno,$ename) = each($data)) {
	OCIExecute($stmt);
	OCIExecute($update);
} 

$rowid->free();

OCIFreeStatement($update);
OCIFreeStatement($stmt);

$stmt = OCIParse($conn,"select * from emp where empno in (1111,2222,3333)");
OCIExecute($stmt);
while (OCIFetchInto($stmt,&$arr,OCI_ASSOC)) {
	var_dump($arr);
}
OCIFreeStatement($stmt);

/* delete our "junk" from the emp table.... */
$stmt = OCIParse($conn,"delete from emp where empno in (1111,2222,3333)");
OCIExecute($stmt);
OCIFreeStatement($stmt);

OCILogoff($conn);
?>

Atenção

It is a bad idea to use magic quotes and OciBindByName() simultaneously as no quoting is needed on quoted variables and any quotes magically applied will be written into your database as OciBindByName() is not able to distinguish magically added quotings from those added by intention.

OCICancel

(PHP 3>= 3.0.8, PHP 4 )

OCICancel -- Cancel reading from cursor

Description

bool OCICancel ( int stmt)

If you do not want read more data from a cursor, then call OCICancel().

OCICollAppend

(PHP 4 >= 4.0.6)

OCICollAppend -- Coming soon

Description

bool OCICollAppend ( object collection, object object)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

OCICollAssign

(PHP 4 >= 4.0.6)

OCICollAssign -- Coming soon

Description

bool OCICollAssign ( object collection, object object)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

OCICollAssignElem

(PHP 4 >= 4.0.6)

OCICollAssignElem -- Coming soon

Description

bool OCICollAssignElem ( object collection, string ndx, string val)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

OCICollGetElem

(PHP 4 >= 4.0.6)

OCICollGetElem -- Coming soon

Description

string OCICollGetElem ( object collection, string ndx)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

OCICollMax

(PHP 4 >= 4.0.6)

OCICollMax -- Coming soon

Description

int OCICollMax ( object collection)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

OCICollSize

(PHP 4 >= 4.0.6)

OCICollSize -- Coming soon

Description

int OCICollSize ( object collection)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

OCICollTrim

(PHP 4 >= 4.0.6)

OCICollTrim -- Coming soon

Description

bool OCICollTrim ( object collection, int num)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

OCIColumnIsNULL

(PHP 3>= 3.0.4, PHP 4 )

OCIColumnIsNULL -- Test whether a result column is NULL

Description

bool OCIColumnIsNULL ( int stmt, mixed column)

OCIColumnIsNULL() returns TRUE if the returned column column in the result from the statement stmt is NULL. You can either use the column-number (1-Based) or the column-name for the col parameter.

OCIColumnName

(PHP 3>= 3.0.4, PHP 4 )

OCIColumnName -- Returns the name of a column

Description

string OCIColumnName ( int stmt, int col)

OCIColumnName() returns the name of the column corresponding to the column number (1-based) that is passed in.

Exemplo 1. OCIColumnName

<?php   
    print "<HTML><PRE>\n";   
    $conn = OCILogon("scott", "tiger");
    $stmt = OCIParse($conn,"select * from emp");
    OCIExecute($stmt);
    print "<TABLE BORDER=\"1\">";
    print "<TR>";
    print "<TH>Name</TH>";
    print "<TH>Type</TH>";
    print "<TH>Length</TH>";
    print "</TR>";
    $ncols = OCINumCols($stmt);
    for ( $i = 1; $i <= $ncols; $i++ ) {
        $column_name  = OCIColumnName($stmt,$i);
        $column_type  = OCIColumnType($stmt,$i);
        $column_size  = OCIColumnSize($stmt,$i);
        print "<TR>";
        print "<TD>$column_name</TD>";
        print "<TD>$column_type</TD>";
        print "<TD>$column_size</TD>";
        print "</TR>";
    }
    print "</TABLE>\n"; 
    OCIFreeStatement($stmt);  
    OCILogoff($conn);   
    print "</PRE>";
    print "</HTML>\n"; 
?>

See also OCINumCols(), OCIColumnType(), and OCIColumnSize().

OCIColumnPrecision

(PHP 4 )

OCIColumnPrecision -- Coming soon

Description

int OCIColumnPrecision ( int stmt, int col)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

OCIColumnScale

(PHP 4 )

OCIColumnScale -- Coming soon

Description

int OCIColumnScale ( int stmt, int col)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

OCIColumnSize

(PHP 3>= 3.0.4, PHP 4 )

OCIColumnSize -- Return result column size

Description

int OCIColumnSize ( int stmt, mixed column)

OCIColumnSize() returns the size of the column as given by Oracle. You can either use the column-number (1-Based) or the column-name for the col parameter.

Exemplo 1. OCIColumnSize

<?php   
    print "<HTML><PRE>\n";   
    $conn = OCILogon("scott", "tiger");
    $stmt = OCIParse($conn,"select * from emp");
    OCIExecute($stmt);
    print "<TABLE BORDER=\"1\">";
    print "<TR>";
    print "<TH>Name</TH>";
    print "<TH>Type</TH>";
    print "<TH>Length</TH>";
    print "</TR>";
    $ncols = OCINumCols($stmt);
    for ( $i = 1; $i <= $ncols; $i++ ) {
        $column_name  = OCIColumnName($stmt,$i);
        $column_type  = OCIColumnType($stmt,$i);
        $column_size  = OCIColumnSize($stmt,$i);
        print "<TR>";
        print "<TD>$column_name</TD>";
        print "<TD>$column_type</TD>";
        print "<TD>$column_size</TD>";
        print "</TR>";
    }
    print "</TABLE>";
    OCIFreeStatement($stmt);  
    OCILogoff($conn);   
    print "</PRE>";
    print "</HTML>\n"; 
?>

See also OCINumCols(), OCIColumnName(), and OCIColumnSize().

OCIColumnType

(PHP 3>= 3.0.4, PHP 4 )

OCIColumnType -- Returns the data type of a column

Description

mixed OCIColumnType ( int stmt, int col)

OCIColumnType() returns the data type of the column corresponding to the column number (1-based) that is passed in.

Exemplo 1. OCIColumnType

<?php   
    print "<HTML><PRE>\n";   
    $conn = OCILogon("scott", "tiger");
    $stmt = OCIParse($conn,"select * from emp");
    OCIExecute($stmt);
    print "<TABLE BORDER=\"1\">";
    print "<TR>";
    print "<TH>Name</TH>";
    print "<TH>Type</TH>";
    print "<TH>Length</TH>";
    print "</TR>";
    $ncols = OCINumCols($stmt);
    for ( $i = 1; $i <= $ncols; $i++ ) {
        $column_name  = OCIColumnName($stmt,$i);
        $column_type  = OCIColumnType($stmt,$i);
        $column_size  = OCIColumnSize($stmt,$i);
        print "<TR>";
        print "<TD>$column_name</TD>";
        print "<TD>$column_type</TD>";
        print "<TD>$column_size</TD>";
        print "</TR>";
    }
    print "</TABLE>\n"; 
    OCIFreeStatement($stmt);  
    OCILogoff($conn);   
    print "</PRE>";
    print "</HTML>\n"; 
?>

See also OCINumCols(), OCIColumnName(), and OCIColumnSize().

OCIColumnTypeRaw

(PHP 4 )

OCIColumnTypeRaw -- Coming soon

Description

mixed OCIColumnTypeRaw ( int stmt, int col)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

OCICommit

(PHP 3>= 3.0.7, PHP 4 )

OCICommit -- Commits outstanding transactions

Description

bool OCICommit ( int connection)

OCICommit() commits all outstanding statements for Oracle connection connection. Retorna TRUE em caso de sucesso ou FALSE em falhas.

This example demonstrates how OCICommit is used.

Exemplo 1. OCICommit

<?php
    // Login to Oracle server
    $conn = OCILogon('scott', 'tiger');

    // Parse SQL
    $stmt = OCIParse($conn, "INSERT INTO employees (name, surname) VALUES ('Maxim', 'Maletsky')");

    // Execute statement
    OCIExecute($stmt);

    // Commit transaction
    $committed = OCICommit($conn);

    // Test whether commit was successful. If error occurred, return error message
    if(!$committed) {
        $error = OCIError($conn);
        echo 'Commit failed. Oracle reports: ' . $error['message'];
    }

    // Close connection
    OCILogoff($conn);
?>

See also OCIRollback().

OCIDefineByName

(PHP 3>= 3.0.7, PHP 4 )

OCIDefineByName --  Use a PHP variable for the define-step during a SELECT

Description

bool OCIDefineByName ( int stmt, string Column-Name, mixed variable [, int type])

OCIDefineByName() binds PHP variables for fetches of SQL-Columns. Be careful that Oracle uses ALL-UPPERCASE column-names, whereby in your select you can also write lowercase. OCIDefineByName() expects the Column-Name to be in uppercase. If you define a variable that doesn't exists in you select statement, no error will be given!

If you need to define an abstract datatype (LOB/ROWID/BFILE) you need to allocate it first using OCINewDescriptor() function. See also the OCIBindByName() function.

Exemplo 1. OCIDefineByName

<?php
/* OCIDefineByName example - thies@thieso.net (980219) */

$conn = OCILogon("scott","tiger");

$stmt = OCIParse($conn,"select empno, ename from emp");

/* the define MUST be done BEFORE ociexecute! */

OCIDefineByName($stmt,"EMPNO",$empno);
OCIDefineByName($stmt,"ENAME",$ename);

OCIExecute($stmt);

while (OCIFetch($stmt)) {
    echo "empno:".$empno."\n";
    echo "ename:".$ename."\n";
}

OCIFreeStatement($stmt);
OCILogoff($conn);
?>

OCIError

(PHP 3>= 3.0.7, PHP 4 )

OCIError -- Return the last error of stmt|conn|global

Description

array OCIError ( [int stmt|conn|global])

OCIError() returns the last error found. If the optional stmt|conn|global is not provided, the last error encountered is returned. If no error is found, OCIError() returns FALSE. OCIError() returns the error as an associative array. In this array, code consists the oracle error code and message the oracle errorstring.

OCIExecute

(PHP 3>= 3.0.4, PHP 4 )

OCIExecute -- Execute a statement

Description

int OCIExecute ( int statement [, int mode])

OCIExecute() executes a previously parsed statement. (see OCIParse()). The optional mode allows you to specify the execution-mode (default is OCI_COMMIT_ON_SUCCESS). If you don't want statements to be committed automatically specify OCI_DEFAULT as your mode.

Retorna TRUE em caso de sucesso ou FALSE em falhas.

OCIFetch

(PHP 3>= 3.0.4, PHP 4 )

OCIFetch -- Fetches the next row into result-buffer

Description

bool OCIFetch ( int statement)

OCIFetch() fetches the next row (for SELECT statements) into the internal result-buffer.

OCIFetchInto

(PHP 3>= 3.0.4, PHP 4 )

OCIFetchInto -- Fetches the next row into result-array

Description

int OCIFetchInto ( int stmt, array &result [, int mode])

OCIFetchInto() fetches the next row (for SELECT statements) into the result array. OCIFetchInto() will overwrite the previous content of result. By default result will contain a zero-based array of all columns that are not NULL.

The mode parameter allows you to change the default behaviour. You can specify more than one flag by simply adding them up (eg OCI_ASSOC+OCI_RETURN_NULLS). The known flags are:

OCI_ASSOC Return an associative array.
OCI_NUM Return an numbered array starting with zero. (DEFAULT)
OCI_RETURN_NULLS Return empty columns.
OCI_RETURN_LOBS Return the value of a LOB instead of the descriptor.

Exemplo 1. A simple OCIFetchInto() example

<?php
$conn = ocilogon("username","password");

$query = "SELECT apples FROM oranges";

$statement = OCIParse ($conn, $query);
OCIExecute ($statement);

while (OCIFetchInto ($statement, $row, OCI_ASSOC)) {
    print $row['apples'];
}
?>

See also OCIFetch() and OCIExecute().

OCIFetchStatement

(PHP 3>= 3.0.8, PHP 4 )

OCIFetchStatement -- Fetch all rows of result data into an array

Description

int OCIFetchStatement ( int stmt, array & variable)

OCIFetchStatement() fetches all the rows from a result into a user-defined array. OCIFetchStatement() returns the number of rows fetched.

Exemplo 1. OCIFetchStatement

<?php
/* OCIFetchStatement example mbritton@verinet.com (990624) */

$conn = OCILogon("scott","tiger");

$stmt = OCIParse($conn,"select * from emp");

OCIExecute($stmt);

$nrows = OCIFetchStatement($stmt,$results);
if ( $nrows > 0 ) {
   print "<TABLE BORDER=\"1\">\n";
   print "<TR>\n";
   while ( list( $key, $val ) = each( $results ) ) {
      print "<TH>$key</TH>\n";
   }
   print "</TR>\n";
   
   for ( $i = 0; $i < $nrows; $i++ ) {
      reset($results);
      print "<TR>\n";
      while ( $column = each($results) ) {   
         $data = $column['value'];
         print "<TD>$data[$i]</TD>\n";
      }
      print "</TR>\n";
   }
   print "</TABLE>\n";
} else {
   echo "No data found<BR>\n";
}      
print "$nrows Records Selected<BR>\n";
 
OCIFreeStatement($stmt);
OCILogoff($conn);
?>

OCIFreeCollection

(PHP 4 >= 4.1.0)

OCIFreeCollection -- Coming soon

Description

bool OCIFreeCollection ( object lob)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

OCIFreeCursor

(PHP 3>= 3.0.8, PHP 4 )

OCIFreeCursor --  Free all resources associated with a cursor

Description

int OCIFreeCursor ( int stmt)

OCIFreeCursor() returns TRUE if successful, or FALSE if unsuccessful.

OCIFreeDesc

(PHP 4 )

OCIFreeDesc -- Deletes a large object descriptor

Description

bool OCIFreeDesc ( object lob)

OCIFreeDesc() returns TRUE if successful, or FALSE if unsuccessful.

OCIFreeStatement

(PHP 3>= 3.0.5, PHP 4 )

OCIFreeStatement --  Free all resources associated with a statement

Description

bool OCIFreeStatement ( int stmt)

OCIFreeStatement() returns TRUE if successful, or FALSE if unsuccessful.

OCIInternalDebug

(PHP 3>= 3.0.4, PHP 4 )

OCIInternalDebug --  Enables or disables internal debug output

Description

void OCIInternalDebug ( int onoff)

OCIInternalDebug() enables internal debug output. Set onoff to 0 to turn debug output off, 1 to turn it on.

OCILoadLob

(PHP 4 )

OCILoadLob -- Coming soon

Description

string OCILoadLob ( object lob)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

OCILogOff

(PHP 3>= 3.0.4, PHP 4 )

OCILogOff -- Disconnects from Oracle

Description

bool OCILogOff ( int connection)

OCILogOff() closes an Oracle connection.

Using OCILogOff() isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution. See also freeing resources.

OCILogon

(PHP 3>= 3.0.4, PHP 4 )

OCILogon -- Establishes a connection to Oracle

Description

int OCILogon ( string username, string password [, string db])

OCILogon() returns an connection identifier needed for most other OCI calls. The optional third parameter can either contain the name of the local Oracle instance or the name of the entry in tnsnames.ora to which you want to connect. If the optional third parameter is not specified, PHP uses the environment variables ORACLE_SID (Oracle instance) or TWO_TASK (tnsnames.ora) to determine which database to connect to.

Connections are shared at the page level when using OCILogon(). This means that commits and rollbacks apply to all open transactions in the page, even if you have created multiple connections.

This example demonstrates how the connections are shared.

Exemplo 1. OCILogon

<?php
print "<HTML><PRE>";
$db = "";

$c1 = ocilogon("scott","tiger",$db);
$c2 = ocilogon("scott","tiger",$db);

function create_table($conn)
{ $stmt = ociparse($conn,"create table scott.hallo (test varchar2(64))");
  ociexecute($stmt);
  echo $conn." created table\n\n";
}

function drop_table($conn)
{ $stmt = ociparse($conn,"drop table scott.hallo");
  ociexecute($stmt);
  echo $conn." dropped table\n\n";
}

function insert_data($conn)
{ $stmt = ociparse($conn,"insert into scott.hallo 
            values('$conn' || ' ' || to_char(sysdate,'DD-MON-YY HH24:MI:SS'))");
  ociexecute($stmt,OCI_DEFAULT);
  echo $conn." inserted hallo\n\n";
}

function delete_data($conn)
{ $stmt = ociparse($conn,"delete from scott.hallo");
  ociexecute($stmt,OCI_DEFAULT);
  echo $conn." deleted hallo\n\n";
}

function commit($conn)
{ ocicommit($conn);
  echo $conn." committed\n\n";
}

function rollback($conn)
{ ocirollback($conn);
  echo $conn." rollback\n\n";
}

function select_data($conn)
{ $stmt = ociparse($conn,"select * from scott.hallo");
  ociexecute($stmt,OCI_DEFAULT);
  echo $conn."----selecting\n\n";
  while (ocifetch($stmt))
    echo $conn." <".ociresult($stmt,"TEST").">\n\n";
  echo $conn."----done\n\n";
}

create_table($c1);
insert_data($c1);   // Insert a row using c1
insert_data($c2);   // Insert a row using c2

select_data($c1);   // Results of both inserts are returned
select_data($c2);   

rollback($c1);      // Rollback using c1

select_data($c1);   // Both inserts have been rolled back
select_data($c2);   

insert_data($c2);   // Insert a row using c2
commit($c2);        // commit using c2

select_data($c1);   // result of c2 insert is returned

delete_data($c1);   // delete all rows in table using c1
select_data($c1);   // no rows returned
select_data($c2);   // no rows returned
commit($c1);        // commit using c1

select_data($c1);   // no rows returned
select_data($c2);   // no rows returned

drop_table($c1);
print "</PRE></HTML>";
?>

See also OCIPLogon() and OCINLogon().

OCINewCollection

(PHP 4 >= 4.0.6)

OCINewCollection -- Coming soon

Description

bool OCINewCollection ( int conn, string tdo [, string shema])

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

OCINewCursor

(PHP 3>= 3.0.8, PHP 4 )

OCINewCursor --  Return a new cursor (Statement-Handle)

Description

int OCINewCursor ( int conn)

OCINewCursor() allocates a new statement handle on the specified connection.

Exemplo 1. Using a REF CURSOR from a stored procedure

<?php   
// suppose your stored procedure info.output returns a ref cursor in :data

$conn = OCILogon("scott","tiger");
$curs = OCINewCursor($conn);
$stmt = OCIParse($conn,"begin info.output(:data); end;");

ocibindbyname($stmt,"data",&$curs,-1,OCI_B_CURSOR);
ociexecute($stmt);
ociexecute($curs);

while (OCIFetchInto($curs,&$data)) {
    var_dump($data);
}
 
OCIFreeStatement($stmt);
OCIFreeCursor($curs);
OCILogoff($conn);
?>

Exemplo 2. Using a REF CURSOR in a select statement

<?php   
print "<HTML><BODY>";
$conn = OCILogon("scott","tiger");
$count_cursor = "CURSOR(select count(empno) num_emps from emp " .
                "where emp.deptno = dept.deptno) as EMPCNT from dept";
$stmt = OCIParse($conn,"select deptno,dname,$count_cursor");

ociexecute($stmt);
print "<TABLE BORDER=\"1\">";
print "<TR>";
print "<TH>DEPT NAME</TH>";
print "<TH>DEPT #</TH>";
print "<TH># EMPLOYEES</TH>";
print "</TR>";

while (OCIFetchInto($stmt,&$data,OCI_ASSOC)) {
    print "<TR>";
    $dname  = $data["DNAME"];
    $deptno = $data["DEPTNO"];
    print "<TD>$dname</TD>";
    print "<TD>$deptno</TD>";
    ociexecute($data["EMPCNT"]);
    while (OCIFetchInto($data["EMPCNT"],&$subdata,OCI_ASSOC)) {
        $num_emps = $subdata["NUM_EMPS"];
        print  "<TD>$num_emps</TD>";
    }
    print "</TR>";
}
print "</TABLE>";
print "</BODY></HTML>";
OCIFreeStatement($stmt);
OCILogoff($conn);
?>

OCINewDescriptor

(PHP 3>= 3.0.7, PHP 4 )

OCINewDescriptor --  Initialize a new empty LOB or FILE descriptor

Description

string OCINewDescriptor ( int connection [, int type])

OCINewDescriptor() allocates storage to hold descriptors or LOB locators. Valid values for type are OCI_D_FILE, OCI_D_LOB, OCI_D_ROWID. For LOB descriptors, the methods load, save, and savefile are associated with the descriptor, for BFILE only the load method exists. See the second example usage hints.

Exemplo 1. OCINewDescriptor

<?php   
    /* This script is designed to be called from a HTML form.
     * It expects $user, $password, $table, $where, and $commitsize
     * to be passed in from the form.  The script then deletes
     * the selected rows using the ROWID and commits after each
     * set of $commitsize rows. (Use with care, there is no rollback)
     */
    $conn = OCILogon($user, $password);
    $stmt = OCIParse($conn,"select rowid from $table $where");
    $rowid = OCINewDescriptor($conn,OCI_D_ROWID);
    OCIDefineByName($stmt,"ROWID",&$rowid);   
    OCIExecute($stmt);
    while ( OCIFetch($stmt) ) {      
       $nrows = OCIRowCount($stmt);
       $delete = OCIParse($conn,"delete from $table where ROWID = :rid");
       OCIBindByName($delete,":rid",&$rowid,-1,OCI_B_ROWID);
       OCIExecute($delete);      
       print "$nrows\n";
       if ( ($nrows % $commitsize) == 0 ) {
           OCICommit($conn);      
       }   
    }
    $nrows = OCIRowCount($stmt);   
    print "$nrows deleted...\n";
    OCIFreeStatement($stmt);  
    OCILogoff($conn);
?>
<?php
    /* This script demonstrates file upload to LOB columns
     * The formfield used for this example looks like this
     * <form action="upload.php" method="post" enctype="multipart/form-data">
     * <input type="file" name="lob_upload">
     * ...
     */
  if(!isset($lob_upload) || $lob_upload == 'none'){
?>
<form action="upload.php" method="post" enctype="multipart/form-data">
Upload file: <input type="file" name="lob_upload"><br>
<input type="submit" value="Upload"> - <input type="reset">
</form>
<?php
  } else {

     // $lob_upload contains the temporary filename of the uploaded file

     // see also the features section on file upload,
     // if you would like to use secure uploads
     
     $conn = OCILogon($user, $password);
     $lob = OCINewDescriptor($conn, OCI_D_LOB);
     $stmt = OCIParse($conn,"insert into $table (id, the_blob) 
               values(my_seq.NEXTVAL, EMPTY_BLOB()) returning the_blob into :the_blob");
     OCIBindByName($stmt, ':the_blob', &$lob, -1, OCI_B_BLOB);
     OCIExecute($stmt, OCI_DEFAULT);
     if($lob->savefile($lob_upload)){
        OCICommit($conn);
        echo "Blob successfully uploaded\n";
     }else{
        echo "Couldn't upload Blob\n";
     }
     OCIFreeDesc($lob);
     OCIFreeStatement($stmt);
     OCILogoff($conn);
  }
?>

Exemplo 2. OCINewDescriptor

<?php   
    /* Calling PL/SQL stored procedures which contain clobs as input
     * parameters (PHP 4 >= 4.0.6). 
     * Example PL/SQL stored procedure signature is:
     *
     * PROCEDURE save_data
     *   Argument Name                  Type                    In/Out Default?
     *   ------------------------------ ----------------------- ------ --------
     *   KEY                            NUMBER(38)              IN
     *   DATA                           CLOB                    IN
     *
     */

    $conn = OCILogon($user, $password);
    $stmt = OCIParse($conn, "begin save_data(:key, :data); end;");
    $clob = OCINewDescriptor($conn, OCI_D_LOB);
	OCIBindByName($stmt, ':key', $key);
	OCIBindByName($stmt, ':data', $clob, -1, OCI_B_CLOB);
	$clob->WriteTemporary($data);
	OCIExecute($stmt, OCI_DEFAULT);
	OCICommit($conn);
	$clob->close();
	$clob->free();
	OCIFreeStatement($stmt);
?>

OCINLogon

(PHP 3>= 3.0.8, PHP 4 )

OCINLogon -- Establishes a new connection to Oracle

Description

int OCINLogon ( string username, string password [, string db])

OCINLogon() creates a new connection to an Oracle 8 database and logs on. The optional third parameter can either contain the name of the local Oracle instance or the name of the entry in tnsnames.ora to which you want to connect. If the optional third parameter is not specified, PHP uses the environment variables ORACLE_SID (Oracle instance) or TWO_TASK (tnsnames.ora) to determine which database to connect to.

OCINLogon() forces a new connection. This should be used if you need to isolate a set of transactions. By default, connections are shared at the page level if using OCILogon() or at the web server process level if using OCIPLogon(). If you have multiple connections open using OCINLogon(), all commits and rollbacks apply to the specified connection only.

This example demonstrates how the connections are separated.

Exemplo 1. OCINLogon

<?php
print "<HTML><PRE>";
$db = "";

$c1 = ocilogon("scott","tiger",$db);
$c2 = ocinlogon("scott","tiger",$db);

function create_table($conn)
{ $stmt = ociparse($conn,"create table scott.hallo (test
varchar2(64))");
  ociexecute($stmt);
  echo $conn." created table\n\n";
}

function drop_table($conn)
{ $stmt = ociparse($conn,"drop table scott.hallo");
  ociexecute($stmt);
  echo $conn." dropped table\n\n";
}

function insert_data($conn)
{ $stmt = ociparse($conn,"insert into scott.hallo 
            values('$conn' || ' ' || to_char(sysdate,'DD-MON-YY HH24:MI:SS'))");
  ociexecute($stmt,OCI_DEFAULT);
  echo $conn." inserted hallo\n\n";
}

function delete_data($conn)
{ $stmt = ociparse($conn,"delete from scott.hallo");
  ociexecute($stmt,OCI_DEFAULT);
  echo $conn." deleted hallo\n\n";
}

function commit($conn)
{ ocicommit($conn);
  echo $conn." committed\n\n";
}

function rollback($conn)
{ ocirollback($conn);
  echo $conn." rollback\n\n";
}

function select_data($conn)
{ $stmt = ociparse($conn,"select * from scott.hallo");
  ociexecute($stmt,OCI_DEFAULT);
  echo $conn."----selecting\n\n";
  while (ocifetch($stmt))
    echo $conn." <".ociresult($stmt,"TEST").">\n\n";
  echo $conn."----done\n\n";
}

create_table($c1);
insert_data($c1);

select_data($c1);   
select_data($c2);   

rollback($c1);      

select_data($c1);   
select_data($c2);   

insert_data($c2);   
commit($c2);        

select_data($c1);   

delete_data($c1);   
select_data($c1);   
select_data($c2);   
commit($c1);        

select_data($c1);
select_data($c2);

drop_table($c1);
print "</PRE></HTML>";
?>

See also OCILogon() and OCIPLogon().

OCINumCols

(PHP 3>= 3.0.4, PHP 4 )

OCINumCols --  Return the number of result columns in a statement

Description

int OCINumCols ( int stmt)

OCINumCols() returns the number of columns in a statement.

Exemplo 1. OCINumCols

<?php   
    print "<HTML><PRE>\n";   
    $conn = OCILogon("scott", "tiger");
    $stmt = OCIParse($conn,"select * from emp");
    OCIExecute($stmt);
    while ( OCIFetch($stmt) ) {
        print "\n";   
        $ncols = OCINumCols($stmt);
        for ( $i = 1; $i <= $ncols; $i++ ) {
            $column_name  = OCIColumnName($stmt,$i);
            $column_value = OCIResult($stmt,$i);
            print $column_name . ': ' . $column_value . "\n";
        }
        print "\n";
    }
    OCIFreeStatement($stmt);  
    OCILogoff($conn);   
    print "</PRE>";
    print "</HTML>\n"; 
?>

OCIParse

(PHP 3>= 3.0.4, PHP 4 )

OCIParse -- Parse a query and return a statement

Description

int OCIParse ( int conn, string query)

OCIParse() parses the query using conn. It returns the statement identity if the query is valid, FALSE if not. The query can be any valid SQL statement or PL/SQL block.

OCIPLogon

(PHP 3>= 3.0.8, PHP 4 )

OCIPLogon -- Connect to an Oracle database using a persistent connection

Description

int OCIPLogon ( string username, string password [, string db])

OCIPLogon() creates a persistent connection to an Oracle 8 database and logs on. The optional third parameter can either contain the name of the local Oracle instance or the name of the entry in tnsnames.ora to which you want to connect. If the optional third parameter is not specified, PHP uses the environment variables ORACLE_SID (Oracle instance) or TWO_TASK (tnsnames.ora) to determine which database to connect to.

See also OCILogon() and OCINLogon().

OCIResult

(PHP 3>= 3.0.4, PHP 4 )

OCIResult -- Returns column value for fetched row

Description

mixed OCIResult ( int statement, mixed column)

OCIResult() returns the data for column column in the current row (see OCIFetch()).OCIResult() will return everything as strings except for abstract types (ROWIDs, LOBs and FILEs).

OCIRollback

(PHP 3>= 3.0.7, PHP 4 )

OCIRollback -- Rolls back outstanding transactions

Description

bool OCIRollback ( int connection)

OCIRollback() rolls back all outstanding statements for Oracle connection connection. OCIRollback() returns TRUE on success and FALSE otherwise.

See also OCICommit().

OCIRowCount

(PHP 3>= 3.0.7, PHP 4 )

OCIRowCount -- Gets the number of affected rows

Description

int OCIRowCount ( int statement)

OCIRowCount() returns the number of rows affected for eg update-statements. This function will not tell you the number of rows that a select will return!

Exemplo 1. OCIRowCount

<?php
    print "<HTML><PRE>";
    $conn = OCILogon("scott","tiger");
    $stmt = OCIParse($conn,"create table emp2 as select * from emp");
    OCIExecute($stmt);
    print OCIRowCount($stmt) . " rows inserted.<BR>";
    OCIFreeStatement($stmt);
    $stmt = OCIParse($conn,"delete from emp2");
    OCIExecute($stmt);
    print OCIRowCount($stmt) . " rows deleted.<BR>";
    OCICommit($conn);
    OCIFreeStatement($stmt);
    $stmt = OCIParse($conn,"drop table emp2");
    OCIExecute($stmt);
    OCIFreeStatement($stmt);
    OCILogOff($conn);
    print "</PRE></HTML>";
?>

OCISaveLob

(PHP 4 )

OCISaveLob -- Coming soon

Description

bool OCISaveLob ( object lob)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

OCISaveLobFile

(PHP 4 )

OCISaveLobFile -- Coming soon

Description

bool OCISaveLobFile ( object lob)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

OCIServerVersion

(PHP 3>= 3.0.4, PHP 4 )

OCIServerVersion -- Return a string containing server version information

Description

string OCIServerVersion ( int conn)

Exemplo 1. OCIServerVersion

<?php
   $conn = OCILogon("scott","tiger");
   print "Server Version: " . OCIServerVersion($conn);
   OCILogOff($conn);
?>

OCISetPrefetch

(PHP 3>= 3.0.12, PHP 4 )

OCISetPrefetch -- Sets number of rows to be prefetched

Description

int OCISetPrefetch ( int stmt, int rows)

Sets the number of top level rows to be prefetched. The default value is 1 row.

OCIStatementType

(PHP 3>= 3.0.5, PHP 4 )

OCIStatementType -- Return the type of an OCI statement

Description

string OCIStatementType ( int stmt)

OCIStatementType() returns one of the following values:

  1. "SELECT"

  2. "UPDATE"

  3. "DELETE"

  4. "INSERT"

  5. "CREATE"

  6. "DROP"

  7. "ALTER"

  8. "BEGIN"

  9. "DECLARE"

  10. "UNKNOWN"

Exemplo 1. OCIStatementType() examples

<?php
    print "<HTML><PRE>";
    $conn = OCILogon("scott","tiger");
    $sql  = "delete from emp where deptno = 10";
   
    $stmt = OCIParse($conn,$sql);
    if ( OCIStatementType($stmt) == "DELETE" ) {
        die "You are not allowed to delete from this table<BR>";
    }
   
    OCILogoff($conn);
    print "</PRE></HTML>";
?>

OCIWriteLobToFile

(PHP 4 )

OCIWriteLobToFile -- Coming soon

Description

bool OCIWriteLobToFile ( object lob [, string filename [, int start [, int lenght]]])

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

LXXII. OpenSSL functions

Introdução

This module uses the functions of OpenSSL for generation and verification of signatures and for sealing (encrypting) and opening (decrypting) data. OpenSSL offers many features that this module currently doesn't support. Some of these may be added in the future.


Requisitos

In order to use the OpenSSL functions you need to install the OpenSSL package. PHP-4.0.4pl1 requires OpenSSL >= 0.9.6, but PHP-4.0.5 and greater will also work with OpenSSL >= 0.9.5.


Instalação

To use PHP's OpenSSL support you must also compile PHP --with-openssl[=DIR].

Note to Win32 Users: In order to enable this module on a Windows environment, you must copy libeay32.dll from the DLL folder of the PHP/Win32 binary package to the SYSTEM32 folder of your windows machine. (Ex: C:\WINNT\SYSTEM32 or C:\WINDOWS\SYSTEM32)

Additionally, if you are planning to use the key generation and certificate signing functions, you will need to install a valid openssl.cnf on your system. As of PHP 4.3.0, we include a sample configuration file in the openssl of our win32 binary distribution. If you are using PHP 4.2.0 or later and are missing the file, you can obtain it from the OpenSSL home page or by downloading the PHP 4.3.0 release and using the configuration file from there.

Note to Win32 Users: PHP will search for the openssl.cnf using the following logic:

  • the OPENSSL_CONF environmental variable, if set, will be used as the path (including filename) of the configuration file.

  • the SSLEAY_CONF environmental variable, if set, will be used as the path (including filename) of the configuration file.

  • The file openssl.cnf will be assumed to be found in the default certificate area, as configured at the time that the openssl DLL was compiled. This is usually means that the default filename is c:\usr\local\ssl\openssl.cnf.

In your installation, you need to decide whether to install the configuration file at c:\usr\local\ssl\openssl.cnf or whether to install it someplace else and use environmental variables (possibly on a per-virtual-host basis) to locate the configuration file. Note that it is possible to override the default path from the script using the configargs of the functions that require a configuration file.


Configuração durante execução

Esta extenção não define nenhum parâmetro de configuração no php.ini.


Tipos Resource


Key/Certificate parameters

Quite a few of the openssl functions require a key or a certificate parameter. PHP 4.0.5 and earlier have to use a key or certificate resource returned by one of the openssl_get_xxx functions. Later versions may use one of the following methods:

  • Certificates

    1. An X.509 resource returned from openssl_x509_read()

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

    3. A string containing the content of a certificate, PEM encoded

  • Public/Private Keys

    1. A key resource returned from openssl_get_publickey() or openssl_get_privatekey()

    2. For public keys only: an X.509 resource

    3. A string having the format file://path/to/file.pem - the named file must contain a PEM encoded certificate/private key (it may contain both)

    4. A string containing the content of a certificate/key, PEM encoded

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


Certificate Verification

When calling a function that will verify a signature/certificate, the cainfo parameter is an array containing file and directory names that specify the locations of trusted CA files. If a directory is specified, then it must be a correctly formed hashed directory as the openssl command would use.


Constantes Predefinidas

As contantes abaixo são definidas por esta extensão e somente estarão disponíveis quando a extensão foi compilada com o PHP ou carregada dinamicamente durante a execução.

X509_PURPOSE_SSL_CLIENT (integer)

X509_PURPOSE_SSL_SERVER (integer)

X509_PURPOSE_NS_SSL_SERVER (integer)

X509_PURPOSE_SMIME_SIGN (integer)

X509_PURPOSE_SMIME_ENCRYPT (integer)

X509_PURPOSE_CRL_SIGN (integer)

X509_PURPOSE_ANY (integer)

OPENSSL_PKCS1_PADDING (integer)

OPENSSL_SSLV23_PADDING (integer)

OPENSSL_NO_PADDING (integer)

OPENSSL_PKCS1_OAEP_PADDING (integer)

OPENSSL_KEYTYPE_RSA (integer)

OPENSSL_KEYTYPE_DSA (integer)

OPENSSL_KEYTYPE_DH (integer)


PKCS7 Flags/Constants

The S/MIME functions make use of flags which are specified using a bitfield which can include one or more of the following values:

Tabela 1. PKCS7 CONSTANTS

Constant Description
PKCS7_TEXT adds text/plain content type headers to encrypted/signed message. If decrypting or verifying, it strips those headers from the output - if the decrypted or verified message is not of MIME type text/plain then an error will occur.
PKCS7_BINARY normally the input message is converted to "canonical" format which is effectively using CR and LF as end of line: as required by the S/MIME specification. When this options is present, no translation occurs. This is useful when handling binary data which may not be in MIME format.
PKCS7_NOINTERN when verifying a message, certificates (if any) included in the message are normally searched for the signing certificate. With this option only the certificates specified in the extracerts parameter of openssl_pkcs7_verify() are used. The supplied certificates can still be used as untrusted CAs however.
PKCS7_NOVERIFY do not verify the signers certificate of a signed message.
PKCS7_NOCHAIN do not chain verification of signers certificates: that is don't use the certificates in the signed message as untrusted CAs.
PKCS7_NOCERTS when signing a message the signer's certificate is normally included - with this option it is excluded. This will reduce the size of the signed message but the verifier must have a copy of the signers certificate available locally (passed using the extracerts to openssl_pkcs7_verify() for example.
PKCS7_NOATTR normally when a message is signed, a set of attributes are included which include the signing time and the supported symmetric algorithms. With this option they are not included.
PKCS7_DETACHED When signing a message, use cleartext signing with the MIME type multipart/signed. This is the default if the flags parameter to openssl_pkcs7_sign() if you do not specify any flags. If you turn this option off, the message will be signed using opaque signing, which is more resistant to translation by mail relays but cannot be read by mail agents that do not support S/MIME.
PKCS7_NOSIGS Don't try and verify the signatures on a message

Nota: These constants were added in 4.0.6.

Índice
openssl_csr_export_to_file -- Exports a CSR to a file
openssl_csr_export -- Exports a CSR as a string
openssl_csr_new -- Generates a CSR
openssl_csr_sign -- Sign a CSR with another certificate (or itself) and generate a certificate
openssl_error_string -- Return openSSL error message
openssl_free_key -- Free key resource
openssl_get_privatekey -- Get a private key
openssl_get_publickey -- Extract public key from certificate and prepare it for use
openssl_open -- Open sealed data
openssl_pkcs7_decrypt -- Decrypts an S/MIME encrypted message
openssl_pkcs7_encrypt -- Encrypt an S/MIME message
openssl_pkcs7_sign -- sign an S/MIME message
openssl_pkcs7_verify -- Verifies the signature of an S/MIME signed message
openssl_pkey_export_to_file -- Gets an exportable representation of a key into a file
openssl_pkey_export -- Gets an exportable representation of a key into a string
openssl_pkey_get_private -- Get a private key
openssl_pkey_get_public -- Extract public key from certificate and prepare it for use
openssl_pkey_new -- Generates a new private key
openssl_private_decrypt -- Decrypts data with private key
openssl_private_encrypt -- Encrypts data with private key
openssl_public_decrypt -- Decrypts data with public key
openssl_public_encrypt -- Encrypts data with public key
openssl_seal -- Seal (encrypt) data
openssl_sign -- Generate signature
openssl_verify -- Verify signature
openssl_x509_check_private_key -- Checks if a private key corresponds to a certificate
openssl_x509_checkpurpose -- Verifies if a certificate can be used for a particular purpose
openssl_x509_export_to_file -- Exports a certificate to file
openssl_x509_export -- Exports a certificate as a string
openssl_x509_free -- Free certificate resource
openssl_x509_parse -- Parse an X509 certificate and return the information as an array
openssl_x509_read -- Parse an X.509 certificate and return a resource identifier for it

openssl_csr_export_to_file

(PHP 4 >= 4.2.0)

openssl_csr_export_to_file -- Exports a CSR to a file

Description

bool openssl_csr_export_to_file ( resource csr, string outfilename [, bool notext])

openssl_csr_export_to_file() takes the Certificate Signing Request represented by csr and saves it as ascii-armoured text into the file named by outfilename. Retorna TRUE em caso de sucesso ou FALSE em falhas. The optional notext affects the verbosity of the output; if it is FALSE then additional human-readable information is included in the output. The default value of notext is TRUE

See also openssl_csr_export(), openssl_csr_new() and openssl_csr_sign().

openssl_csr_export

(PHP 4 >= 4.2.0)

openssl_csr_export -- Exports a CSR as a string

Description

bool openssl_csr_export ( resource csr, string &out [, bool notext])

openssl_csr_export() takes the Certificate Signing Request represented by csr and stores it as ascii-armoured text into out, which is passed by reference. Retorna TRUE em caso de sucesso ou FALSE em falhas. The optional notext affects the verbosity of the output; if it is FALSE then additional human-readable information is included in the output. The default value of notext is TRUE

See also openssl_csr_export_to_file(), openssl_csr_new() and openssl_csr_sign().

openssl_csr_new

(PHP 4 >= 4.2.0)

openssl_csr_new -- Generates a CSR

Description

bool openssl_csr_new ( array dn, resource privkey [, array configargs [, array extraattribs]])

openssl_csr_new() generates a new CSR (Certificate Signing Request) based on the information provided by dn, which represents the Distinguished Name to be used in the certificate.

privkey should be set to a private key that was previously generated by openssl_pkey_new() (or otherwise obtained from the other openssl_pkey family of functions). The corresponding public portion of the key will be used to sign the CSR.

extraattribs is used to specify additional configuration options for the CSR. Both dn and extraattribs are associative arrays whose keys are converted to OIDs and applied to the relevant part of the request.

Nota: You need to have a valid openssl.cnf installed for this function to operate correctly. See the notes under the installation section for more information.

By default, the information in your system openssl.conf is used to initialize the request; you can specify a configuration file section by setting the config_section_section key of configargs. You can also specify and alternative openssl configuration file by setting the config key to the path of the file you want to use. The following keys, if present in configargs behave as their equivalents in the openssl.conf, as listed in the table below.

Tabela 1. Configuration overrides

configargs key type openssl.conf equivalent description
digest_alg string default_md Selects which digest method to use
x509_extensions string x509_extensions Selects which extensions should be used when creating an x509 certificate
req_extensions string req_extensions Selects which extensions should be used when creating a CSR
private_key_bits integer default_bits Specifies how many bits should be used to generate a private key
private_key_type integer none Specifies the type of private key to create. This can be one of OPENSSL_KEYTYPE_DSA, OPENSSL_KEYTYPE_DH or OPENSSL_KEYTYPE_RSA. The default value is OPENSSL_KEYTYPE_RSA which is currently the only supported key type.
encrypt_key booean encrypt_key Should an exported key (with passphrase) be encrypted?

Retorna TRUE em caso de sucesso ou FALSE em falhas.

Exemplo 1. openssl_csr_new() example - creating a self-signed-certificate

// Fill in data for the distinguished name to be used in the cert
// You must change the values of these keys to match your name and
// company, or more precisely, the name and company of the person/site
// that you are generating the certificate for.
// For SSL certificates, the commonName is usually the domain name of
// that will be using the certificate, but for S/MIME certificates,
// the commonName will be the name of the individual who will use the
// certificate.
$dn = array(
    "countryName" => "UK",
    "stateOrProvinceName" => "Somerset",
    "localityName" => "Glastonbury",
    "organizationName" => "The Brain Room Limited",
    "organizationalUnitName" => "PHP Documentation Team",
    "commonName" => "Wez Furlong",
    "emailAddress" => "wez@php.net"
);

// Generate a new private (and public) key pair
$privkey = openssl_pkey_new();

// Generate a certificate signing request
$csr = openssl_csr_new($dn, $privkey);

// You will usually want to create a self-signed certificate at this
// point until your CA fulfills your request.
// This creates a self-signed cert that is valid for 365 days
$sscert = openssl_csr_sign($csr, null, $privkey, 365);

// Now you will want to preserve your private key, CSR and self-signed
// cert so that they can be installed into your web server, mail server
// or mail client (depending on the intended use of the certificate).
// This example shows how to get those things into variables, but you
// can also store them directly into files.
// Typically, you will send the CSR on to your CA who will then issue
// you with the "real" certificate.
openssl_csr_export($csr, $csrout) and debug_zval_dump($csrout);
openssl_x509_export($sscert, $certout) and debug_zval_dump($certout);
openssl_pkey_export($privkey, $pkeyout, "mypassword") and debug_zval_dump($pkeyout);

// Show any errors that occurred here
while (($e = openssl_error_string()) !== false) {
    echo $e . "\n";
}

openssl_csr_sign

(PHP 4 >= 4.2.0)

openssl_csr_sign -- Sign a CSR with another certificate (or itself) and generate a certificate

Description

resource openssl_csr_sign ( mixed csr, mixed cacert, mixed priv_key, long days)

openssl_csr_sign() generates an x509 certificate resource from the csr previously generated by openssl_csr_new(), but it can also be the path to a PEM encoded CSR when specified as file://path/to/csr or an exported string generated by openssl_csr_export(). The generated certificate will be signed by cacert. If cacert is NULL, the generated certificate will be a self-signed certificate. priv_key is the private key that corresponds to cacert. days specifies the length of time for which the generated certificate will be valid, in days.

Returns an x509 certificate resource on success, FALSE on failure.

Nota: You need to have a valid openssl.cnf installed for this function to operate correctly. See the notes under the installation section for more information.

Exemplo 1. openssl_csr_sign() example - signing a CSR (how to implement your own CA)

// Let's assume that this script is set to receive a CSR that has
// been pasted into a textarea from another page
$csrdata = $_POST["CSR"];

// We will sign the request using our own "certificate authority"
// certificate.  You can use any certificate to sign another, but
// the process is worthless unless the signing certificate is trusted
// by the software/users that will deal with the newly signed certificate

// We need our CA cert and it's private key
$cacert = "file://path/to/ca.crt";
$privkey = array("file://path/to/ca.key", "your_ca_key_passphrase");

$userscert = openssl_csr_sign($csrdata, $cacert, $privkey, 365);

// Now display the generated certificate so that the user can
// copy and paste it into their local configuration (such as a file
// to hold the certificate for their SSL server)
openssl_x509_export($usercert, $certout) and echo $certout;

// Show any errors that occurred here
while (($e = openssl_error_string()) !== false) {
    echo $e . "\n";
}

openssl_error_string

(PHP 4 >= 4.0.6)

openssl_error_string -- Return openSSL error message

Description

mixed openssl_error_string ( void)

Returns an error message string, or FALSE if there are no more error messages to return.

openssl_error_string() returns the last error from the openSSL library. Error messages are stacked, so this function should be called multiple times to collect all of the information.

Exemplo 1. openssl_error_string() example

// lets assume you just called an openssl function that failed
while($msg = openssl_error_string())
    echo $msg . "<br />\n";

Nota: This function was added in 4.0.6.

openssl_free_key

(PHP 4 >= 4.0.4)

openssl_free_key -- Free key resource

Description

void openssl_free_key ( resource key_identifier)

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

openssl_get_privatekey

(PHP 4 >= 4.0.4)

openssl_get_privatekey -- Get a private key

Description

resource openssl_get_privatekey ( mixed key [, string passphrase])

This is an alias for openssl_pkey_get_private().

openssl_get_publickey

(PHP 4 >= 4.0.4)

openssl_get_publickey -- Extract public key from certificate and prepare it for use

Description

resource openssl_get_publickey ( mixed certificate)

This is an alias for openssl_pkey_get_public().

openssl_open

(PHP 4 >= 4.0.4)

openssl_open -- Open sealed data

Description

bool openssl_open ( string sealed_data, string open_data, string env_key, mixed priv_key_id)

Retorna TRUE em caso de sucesso ou FALSE em falhas. If successful the opened data is returned in open_data.

openssl_open() opens (decrypts) sealed_data using the private key associated with the key identifier priv_key_id and the envelope key env_key, and fills open_data with the decrypted data. The envelope key is generated when the data are sealed and can only be used by one specific private key. See openssl_seal() for more information.

Exemplo 1. openssl_open() example

// $sealed and $env_key are assumed to contain the sealed data
// and our envelope key, both given to us by the sealer.

// fetch private key from file and ready it
$fp = fopen("/src/openssl-0.9.6/demos/sign/key.pem", "r");
$priv_key = fread($fp, 8192);
fclose($fp);
$pkeyid = openssl_get_privatekey($priv_key);

// decrypt the data and store it in $open
if (openssl_open($sealed, $open, $env_key, $pkeyid))
    echo "here is the opened data: ", $open;
else
    echo "failed to open data";

// free the private key from memory
openssl_free_key($pkeyid);

See also openssl_seal().

openssl_pkcs7_decrypt

(PHP 4 >= 4.0.6)

openssl_pkcs7_decrypt -- Decrypts an S/MIME encrypted message

Description

bool openssl_pkcs7_decrypt ( string infilename, string outfilename, mixed recipcert [, mixed recipkey])

Decrypts the S/MIME encrypted message contained in the file specified by infilename using the certificate and it's associated private key specified by recipcert and recipkey.

The decrypted message is output to the file specified by outfilename

Exemplo 1. openssl_pkcs7_decrypt() example

// $cert and $key are assumed to contain your personal certificate and private
// key pair, and that you are the recipient of an S/MIME message
$infilename = "encrypted.msg";  // this file holds your encrypted message
$outfilename = "decrypted.msg"; // make sure you can write to this file

if (openssl_pkcs7_decrypt($infilename, $outfilename, $cert, $key))
    echo "decrypted!";
else
    echo "failed to decrypt!";

Nota: This function was added in 4.0.6.

openssl_pkcs7_encrypt

(PHP 4 >= 4.0.6)

openssl_pkcs7_encrypt -- Encrypt an S/MIME message

Description

bool openssl_pkcs7_encrypt ( string infile, string outfile, mixed recipcerts, array headers [, long flags])

openssl_pkcs7_encrypt() takes the contents of the file named infile and encrypts them using an RC2 40-bit cipher so that they can only be read by the intended recipients specified by recipcerts, which is either a lone X.509 certificate, or an array of X.509 certificates. headers is an array of headers that will be prepended to the data after it has been encrypted. flags can be used to specify options that affect the encoding process - see PKCS7 constants. headers can be either an associative array keyed by header name, or an indexed array, where each element contains a single header line.

Exemplo 1. openssl_pkcs7_encrypt() example

// the message you want to encrypt and send to your secret agent
// in the field, known as nighthawk.  You have his certificate
// in the file nighthawk.pem
$data = <<<EOD
Nighthawk,

Top secret, for your eyes only!

The enemy is closing in! Meet me at the cafe at 8.30am
to collect your forged passport!

HQ
EOD;

// load key
$key = file_get_contents("nighthawk.pem");

// save message to file
$fp = fopen("msg.txt", "w");
fwrite($fp, $data);
fclose($fp);

// encrypt it
if (openssl_pkcs7_encrypt("msg.txt", "enc.txt", $key,
    array("To" => "nighthawk@example.com", // keyed syntax
          "From: HQ <hq@example.com>", // indexed syntax
          "Subject" => "Eyes only")))
{
    // message encrypted - send it!
    exec(ini_get("sendmail_path") . " < enc.txt");
}

openssl_pkcs7_sign

(PHP 4 >= 4.0.6)

openssl_pkcs7_sign -- sign an S/MIME message

Description

bool openssl_pkcs7_sign ( string infilename, string outfilename, mixed signcert, mixed privkey, array headers [, long flags [, string extracertsfilename]])

openssl_pkcs7_sign() takes the contents of the file named infilename and signs them using the certificate and it's matching private key specified by signcert and privkey parameters.

headers is an array of headers that will be prepended to the data after it has been signed (see openssl_pkcs7_encrypt() for more information about the format of this parameter.

flags can be used to alter the output - see PKCS7 constants - if not specified, it defaults to PKCS7_DETACHED.

extracerts specifies the name of a file containing a bunch of extra certificates to include in the signature which can for example be used to help the recipient to verify the certificate that you used.

Exemplo 1. openssl_pkcs7_sign() example

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

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

The CEO
EOD;
// save message to file
$fp = fopen("msg.txt", "w");
fwrite($fp, $data);
fclose($fp);
// encrypt it
if (openssl_pkcs7_sign("msg.txt", "signed.txt", "mycert.pem",
    array("mycert.pem", "mypassphrase"),
    array("To" => "joes@sales.com", // keyed syntax
          "From: HQ <ceo@sales.com>", // indexed syntax
          "Subject" => "Eyes only"))
{
    // message signed - send it!
    exec(ini_get("sendmail_path") . " < signed.txt");
}

Nota: This function was added in 4.0.6.

openssl_pkcs7_verify

(PHP 4 >= 4.0.6)

openssl_pkcs7_verify -- Verifies the signature of an S/MIME signed message

Description

bool openssl_pkcs7_verify ( string filename, int flags [, string outfilename [, array cainfo [, string extracerts]]])

openssl_pkcs7_verify() reads the S/MIME message contained in the filename specified by filename and examines the digital signature. It returns TRUE if the signature is verified, FALSE if it is not correct (the message has been tampered with, or the signing certificate is invalid), or -1 on error.

flags can be used to affect how the signature is verified - see PKCS7 constants for more information.

If the outfilename is specified, it should be a string holding the name of a file into which the certificates of the persons that signed the messages will be stored in PEM format.

If the cainfo is specified, it should hold information about the trusted CA certificates to use in the verification process - see certificate verification for more information about this parameter.

If the extracerts is specified, it is the filename of a file containing a bunch of certificates to use as untrusted CAs.

Nota: This function was added in 4.0.6.

openssl_pkey_export_to_file

(PHP 4 >= 4.2.0)

openssl_pkey_export_to_file -- Gets an exportable representation of a key into a file

Description

bool openssl_pkey_export_to_file ( mixed key, string outfilename [, string passphrase [, array configargs]])

openssl_pkey_export_to_file() saves an ascii-armoured (PEM encoded) rendition of key into the file named by outfilename. The key can be optionally protected by a passphrase. configargs can be used to fine-tune the export process by specifying and/or overriding options for the openssl configuration file. See openssl_csr_new() for more information about configargs. Retorna TRUE em caso de sucesso ou FALSE em falhas.

Nota: You need to have a valid openssl.cnf installed for this function to operate correctly. See the notes under the installation section for more information.

openssl_pkey_export

(PHP 4 >= 4.2.0)

openssl_pkey_export -- Gets an exportable representation of a key into a string

Description

bool openssl_pkey_export ( mixed key, string &out [, string passphrase [, array configargs]])

openssl_pkey_export() exports key as a PEM encoded string and stores it into out (which is passed by reference). The key is optionally protected by passphrase. configargs can be used to fine-tune the export process by specifying and/or overriding options for the openssl configuration file. See openssl_csr_new() for more information about configargs. Retorna TRUE em caso de sucesso ou FALSE em falhas.

Nota: You need to have a valid openssl.cnf installed for this function to operate correctly. See the notes under the installation section for more information.

openssl_pkey_get_private

(PHP 4 >= 4.2.0)

openssl_pkey_get_private -- Get a private key

Description

resource openssl_get_privatekey ( mixed key [, string passphrase])

Returns a positive key resource identifier on success, or FALSE on error.

openssl_get_privatekey() parses key and prepares it for use by other functions. key can be one of the following:

  1. a string having the format file://path/to/file.pem. The named file must contain a PEM encoded certificate/private key (it may contain both).

  2. A PEM formatted private key.

The optional parameter passphrase must be used if the specified key is encrypted (protected by a passphrase).

openssl_pkey_get_public

(PHP 4 >= 4.2.0)

openssl_pkey_get_public -- Extract public key from certificate and prepare it for use

Description

resource openssl_pkey_get_public ( mixed certificate)

Returns a positive key resource identifier on success, or FALSE on error.

openssl_get_publickey() extracts the public key from certificate and prepares it for use by other functions. certificate can be one of the following:

  1. an X.509 certificate resource

  2. a string having the format file://path/to/file.pem. The named file must contain a PEM encoded certificate/private key (it may contain both).

  3. A PEM formatted private key.

openssl_pkey_new

(PHP 4 >= 4.2.0)

openssl_pkey_new -- Generates a new private key

Description

resource openssl_pkey_new ( [array configargs])

openssl_pkey_new() generates a new private and public key pair. The public component of the key can be obtained using openssl_pkey_get_public(). You can finetune the key generation (such as specifying the number of bits) using configargs. See openssl_csr_new() for more information about configargs.

Nota: You need to have a valid openssl.cnf installed for this function to operate correctly. See the notes under the installation section for more information.

openssl_private_decrypt

(PHP 4 >= 4.0.6)

openssl_private_decrypt -- Decrypts data with private key

Description

bool openssl_private_decrypt ( string data, string &decrypted, mixed key [, int padding])

openssl_private_decrypt() decrypts data that was previous encrypted via openssl_private_encrypt() and stores the result into decrypted. key must be the private key corresponding that was used to encrypt the data. padding defaults to OPENSSL_PKCS1_PADDING, but can also be one of OPENSSL_SSLV23_PADDING, OPENSSL_PKCS1_OAEP_PADDING OPENSSL_NO_PADDING.

openssl_private_encrypt

(PHP 4 >= 4.0.6)

openssl_private_encrypt -- Encrypts data with private key

Description

bool openssl_private_encrypt ( string data, string crypted, mixed key [, int padding])

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

openssl_public_decrypt

(PHP 4 >= 4.0.6)

openssl_public_decrypt -- Decrypts data with public key

Description

bool openssl_public_decrypt ( string data, string crypted, resource key [, int padding])

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

openssl_public_encrypt

(PHP 4 >= 4.0.6)

openssl_public_encrypt -- Encrypts data with public key

Description

bool openssl_public_encrypt ( string data, string crypted, mixed key [, int padding])

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

openssl_seal

(PHP 4 >= 4.0.4)

openssl_seal -- Seal (encrypt) data

Description

int openssl_seal ( string data, string sealed_data, array env_keys, array pub_key_ids)

Returns the length of the sealed data on success, or FALSE on error. If successful the sealed data is returned in sealed_data, and the envelope keys in env_keys.

openssl_seal() seals (encrypts) data by using RC4 with a randomly generated secret key. The key is encrypted with each of the public keys associated with the identifiers in pub_key_ids and each encrypted key is returned in env_keys. This means that one can send sealed data to multiple recipients (provided one has obtained their public keys). Each recipient must receive both the sealed data and the envelope key that was encrypted with the recipient's public key.

Exemplo 1. openssl_seal() example

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

// fetch public keys for our recipients, and ready them
$fp = fopen("/src/openssl-0.9.6/demos/maurice/cert.pem", "r");
$cert = fread($fp, 8192);
fclose($fp);
$pk1 = openssl_get_publickey($cert);
// Repeat for second recipient
$fp = fopen("/src/openssl-0.9.6/demos/sign/cert.pem", "r");
$cert = fread($fp, 8192);
fclose($fp);
$pk2 = openssl_get_publickey($cert);

// seal message, only owners of $pk1 and $pk2 can decrypt $sealed with keys
// $ekeys[0] and $ekeys[1] respectively.
openssl_seal($data, $sealed, $ekeys, array($pk1,$pk2));

// free the keys from memory
openssl_free_key($pk1);
openssl_free_key($pk2);

See also openssl_open().

openssl_sign

(PHP 4 >= 4.0.4)

openssl_sign -- Generate signature

Description

bool openssl_sign ( string data, string signature, mixed priv_key_id)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Retorna TRUE em caso de sucesso ou FALSE em falhas. If successful the signature is returned in signature.

openssl_sign() computes a signature for the specified data by using SHA1 for hashing followed by encryption using the private key associated with priv_key_id. Note that the data itself is not encrypted.

Exemplo 1. openssl_sign() example

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

// fetch private key from file and ready it
$fp = fopen("/src/openssl-0.9.6/demos/sign/key.pem", "r");
$priv_key = fread($fp, 8192);
fclose($fp);
$pkeyid = openssl_get_privatekey($priv_key);

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

// free the key from memory
openssl_free_key($pkeyid);

See also openssl_verify().

openssl_verify

(PHP 4 >= 4.0.4)

openssl_verify -- Verify signature

Description

int openssl_verify ( string data, string signature, mixed pub_key_id)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Returns 1 if the signature is correct, 0 if it is incorrect, and -1 on error.

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

Exemplo 1. openssl_verify() example

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

// fetch public key from certificate and ready it
$fp = fopen("/src/openssl-0.9.6/demos/sign/cert.pem", "r");
$cert = fread($fp, 8192);
fclose($fp);
$pubkeyid = openssl_get_publickey($cert);

// state whether signature is okay or not
$ok = openssl_verify($data, $signature, $pubkeyid);
if ($ok == 1)
    echo "good";
elseif ($ok == 0)
    echo "bad";
else
    echo "ugly, error checking signature";

// free the key from memory
openssl_free_key($pubkeyid);

See also openssl_sign().

openssl_x509_check_private_key

(PHP 4 >= 4.2.0)

openssl_x509_check_private_key -- Checks if a private key corresponds to a certificate

Description

bool openssl_x509_check_private_key ( mixed cert, mixed key)

openssl_x509_check_private_key() returns TRUE if key is the private key that corresponds to cert, or FALSE otherwise.

openssl_x509_checkpurpose

(PHP 4 >= 4.0.6)

openssl_x509_checkpurpose -- Verifies if a certificate can be used for a particular purpose

Description

bool openssl_x509_checkpurpose ( mixed x509cert, int purpose, array cainfo [, string untrustedfile])

Returns TRUE if the certificate can be used for the intended purpose, FALSE if it cannot, or -1 on error.

openssl_x509_checkpurpose() examines the certificate specified by x509cert to see if it can be used for the purpose specified by purpose.

cainfo should be an array of trusted CA files/dirs as described in Certificate Verification.

untrustedfile, if specified, is the name of a PEM encoded file holding certificates that can be used to help verify the certificate, although no trust in placed in the certificates that come from that file.

Tabela 1. openssl_x509_checkpurpose() purposes

Constant Description
X509_PURPOSE_SSL_CLIENT Can the certificate be used for the client side of an SSL connection?
X509_PURPOSE_SSL_SERVER Can the certificate be used for the server side of an SSL connection?
X509_PURPOSE_NS_SSL_SERVER Can the cert be used for Netscape SSL server?
X509_PURPOSE_SMIME_SIGN Can the cert be used to sign S/MIME email?
X509_PURPOSE_SMIME_ENCRYPT Can the cert be used to encrypt S/MIME email?
X509_PURPOSE_CRL_SIGN Can the cert be used to sign a certificate revocation list (CRL)?
X509_PURPOSE_ANY Can the cert be used for Any/All purposes?
These options are not bitfields - you may specify one only!

Nota: This function was added in 4.0.6.

openssl_x509_export_to_file

(PHP 4 >= 4.2.0)

openssl_x509_export_to_file -- Exports a certificate to file

Description

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

openssl_x509_export_to_file() stores x509 into a file named by outfilename in a PEM encoded format. The optional parameter notext default to TRUE. If set to FALSE, additional human readable text will also be stored into the output file. Retorna TRUE em caso de sucesso ou FALSE em falhas.

openssl_x509_export

(PHP 4 >= 4.2.0)

openssl_x509_export -- Exports a certificate as a string

Description

bool openssl_x509_export ( mixed x509, string &output [, bool notext])

openssl_x509_export() stores x509 into a file named by outfilename in a PEM encoded format. The optional parameter notext default to TRUE. If set to FALSE, additional human readable text will also be stored into output. Retorna TRUE em caso de sucesso ou FALSE em falhas.

openssl_x509_free

(PHP 4 >= 4.0.6)

openssl_x509_free -- Free certificate resource

Description

void openssl_x509_free ( resource x509cert)

openssl_x509_free() frees the certificate associated with the specified x509cert resource from memory.

Nota: This function was added in 4.0.6.

openssl_x509_parse

(PHP 4 >= 4.0.6)

openssl_x509_parse -- Parse an X509 certificate and return the information as an array

Description

array openssl_x509_parse ( mixed x509cert [, bool shortnames])

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

openssl_x509_parse() returns information about the supplied x509cert, including fields such as subject name, issuer name, purposes, valid from and valid to dates etc. shortnames controls how the data is indexed in the array - if shortnames is TRUE (the default) then fields will be indexed with the short name form, otherwise, the long name form will be used - e.g.: CN is the shortname form of commonName.

The structure of the returned data is (deliberately) not yet documented, as it is still subject to change.

Nota: This function was added in 4.0.6.

openssl_x509_read

(PHP 4 >= 4.0.6)

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

Description

resource openssl_x509_read ( mixed x509certdata)

openssl_x509_read() parses the certificate supplied by x509certdata and returns a resource identifier for it.

Nota: This function was added in 4.0.6.

LXXIII. Oracle functions

Introdução

This extension adds support for Oracle database server access. See also the OCI8 extension.


Instalação

You have to compile PHP with the option --with-oracle[=DIR], where DIR defaults to your environmment variable ORACLE_HOME.


Constantes Predefinidas

As contantes abaixo são definidas por esta extensão e somente estarão disponíveis quando a extensão foi compilada com o PHP ou carregada dinamicamente durante a execução.

ORA_BIND_INOUT (integer)

ORA_BIND_IN (integer)

ORA_BIND_OUT (integer)

ORA_FETCHINTO_ASSOC (integer)

ORA_FETCHINTO_NULLS (integer)

Índice
Ora_Bind -- bind a PHP variable to an Oracle parameter
Ora_Close -- close an Oracle cursor
Ora_ColumnName -- get name of Oracle result column
Ora_ColumnSize -- get size of Oracle result column
Ora_ColumnType -- get type of Oracle result column
Ora_Commit -- commit an Oracle transaction
Ora_CommitOff -- disable automatic commit
Ora_CommitOn -- enable automatic commit
Ora_Do -- Parse, Exec, Fetch
Ora_Error -- get Oracle error message
Ora_ErrorCode -- get Oracle error code
Ora_Exec -- execute parsed statement on an Oracle cursor
Ora_Fetch_Into -- Fetch a row into the specified result array
Ora_Fetch -- fetch a row of data from a cursor
Ora_GetColumn -- get data from a fetched column
Ora_Logoff -- close an Oracle connection
Ora_Logon -- open an Oracle connection
Ora_Numcols -- Returns the number of columns
Ora_Numrows -- Returns the number of rows
Ora_Open -- open an Oracle cursor
Ora_Parse -- parse an SQL statement
Ora_pLogon --  Open a persistent Oracle connection
Ora_Rollback -- roll back transaction

Ora_Bind

(PHP 3, PHP 4 )

Ora_Bind -- bind a PHP variable to an Oracle parameter

Description

int ora_bind ( int cursor, string PHP variable name, string SQL parameter name, int length [, int type])

Returns TRUE if the bind succeeds, otherwise FALSE. Details about the error can be retrieved using the ora_error() and ora_errorcode() functions.

This function binds the named PHP variable with a SQL parameter. The SQL parameter must be in the form ":name". With the optional type parameter, you can define whether the SQL parameter is an in/out (0, default), in (1) or out (2) parameter. As of PHP 3.0.1, you can use the constants ORA_BIND_INOUT, ORA_BIND_IN and ORA_BIND_OUT instead of the numbers.

ora_bind must be called after ora_parse() and before ora_exec(). Input values can be given by assignment to the bound PHP variables, after calling ora_exec() the bound PHP variables contain the output values if available.

<?php
ora_parse($curs, "declare tmp INTEGER; begin tmp := :in; :out := tmp; :x := 7.77; end;");
ora_bind($curs, "result", ":x", $len, 2);
ora_bind($curs, "input", ":in", 5, 1);
ora_bind($curs, "output", ":out", 5, 2);
$input = 765;
ora_exec($curs);
echo "Result: $result<BR>Out: $output<BR>In: $input";
?>

Ora_Close

(PHP 3, PHP 4 )

Ora_Close -- close an Oracle cursor

Description

int ora_close ( int cursor)

Returns TRUE if the close succeeds, otherwise FALSE. Details about the error can be retrieved using the ora_error() and ora_errorcode() functions.

This function closes a data cursor opened with ora_open().

Ora_ColumnName

(PHP 3, PHP 4 )

Ora_ColumnName -- get name of Oracle result column

Description

string Ora_ColumnName ( int cursor, int column)

Returns the name of the field/column column on the cursor cursor. The returned name is in all uppercase letters. Column 0 is the first column.

Ora_ColumnSize

(PHP 3, PHP 4 )

Ora_ColumnSize -- get size of Oracle result column

Description

int Ora_ColumnSize ( int cursor, int column)

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

Ora_ColumnType

(PHP 3, PHP 4 )

Ora_ColumnType -- get type of Oracle result column

Description

string Ora_ColumnType ( int cursor, int column)

Returns the Oracle data type name of the field/column column on the cursor cursor. Column 0 is the first column. The returned type will be one of the following:

"VARCHAR2"
"VARCHAR"
"CHAR"
"NUMBER"
"LONG"
"LONG RAW"
"ROWID"
"DATE"
"CURSOR"

Ora_Commit

(PHP 3, PHP 4 )

Ora_Commit -- commit an Oracle transaction

Description

int ora_commit ( int conn)

Retorna TRUE em caso de sucesso ou FALSE em falhas. Details about the error can be retrieved using the ora_error() and ora_errorcode() functions.

This function commits an Oracle transaction. A transaction is defined as all the changes on a given connection since the last commit/rollback, autocommit was turned off or when the connection was established.

Ora_CommitOff

(PHP 3, PHP 4 )

Ora_CommitOff -- disable automatic commit

Description

int ora_commitoff ( int conn)

Retorna TRUE em caso de sucesso ou FALSE em falhas. Details about the error can be retrieved using the ora_error() and ora_errorcode() functions.

This function turns off automatic commit after each ora_exec().

Ora_CommitOn

(PHP 3, PHP 4 )

Ora_CommitOn -- enable automatic commit

Description

int ora_commiton ( int conn)

This function turns on automatic commit after each ora_exec() on the given connection.

Retorna TRUE em caso de sucesso ou FALSE em falhas. Details about the error can be retrieved using the ora_error() and ora_errorcode() functions.

Ora_Do

(PHP 3, PHP 4 )

Ora_Do -- Parse, Exec, Fetch

Description

int ora_do ( int conn, string query)

This function is quick combination of ora_parse(), ora_exec() and ora_fetch(). It will parse and execute a statement, then fetch the first result row.

Retorna TRUE em caso de sucesso ou FALSE em falhas. Details about the error can be retrieved using the ora_error() and ora_errorcode() functions.

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

Ora_Error

(PHP 3, PHP 4 )

Ora_Error -- get Oracle error message

Description

string Ora_Error ( int cursor_or_connection)

Returns an error message of the form XXX-NNNNN where XXX is where the error comes from and NNNNN identifies the error message.

Nota: Support for connection ids was added in 3.0.4.

On UNIX versions of Oracle, you can find details about an error message like this: $ oerr ora 00001 00001, 00000, "unique constraint (%s.%s) violated" // *Cause: An update or insert statement attempted to insert a duplicate key // For Trusted ORACLE configured in DBMS MAC mode, you may see // this message if a duplicate entry exists at a different level. // *Action: Either remove the unique restriction or do not insert the key

Ora_ErrorCode

(PHP 3, PHP 4 )

Ora_ErrorCode -- get Oracle error code

Description

int Ora_ErrorCode ( int cursor_or_connection)

Returns the numeric error code of the last executed statement on the specified cursor or connection.

Nota: Support for connection ids was added in 3.0.4.

Ora_Exec

(PHP 3, PHP 4 )

Ora_Exec -- execute parsed statement on an Oracle cursor

Description

int ora_exec ( int cursor)

Retorna TRUE em caso de sucesso ou FALSE em falhas. Details about the error can be retrieved using the ora_error() and ora_errorcode() functions.

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

Ora_Fetch_Into

(PHP 3, PHP 4 )

Ora_Fetch_Into -- Fetch a row into the specified result array

Description

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

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

Returns the number of columns fetched.

Exemplo 1. ora_fetch_into()

<?php
$results = array();
ora_fetch_into($cursor, $results);
echo $results[0];
echo $results[1];
$results = array();
ora_fetch_into($cursor, $results, ORA_FETCHINTO_NULLS|ORA_FETCHINTO_ASSOC);
echo $results['MyColumn'];
?>

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

Ora_Fetch

(PHP 3, PHP 4 )

Ora_Fetch -- fetch a row of data from a cursor

Description

int ora_fetch ( int cursor)

Returns TRUE (a row was fetched) or FALSE (no more rows, or an error occured). If an error occured, details can be retrieved using the ora_error() and ora_errorcode() functions. If there was no error, ora_errorcode() will return 0.

Retrieves a row of data from the specified cursor.

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

Ora_GetColumn

(PHP 3, PHP 4 )

Ora_GetColumn -- get data from a fetched column

Description

mixed ora_getcolumn ( int cursor, mixed column)

Returns the column data. If an error occurs, FALSE is returned and ora_errorcode() will return a non-zero value. Note, however, that a test for FALSE on the results from this function may be TRUE in cases where there is not error as well (NULL result, empty string, the number 0, the string "0").

Fetches the data for a column or function result.

Ora_Logoff

(PHP 3, PHP 4 )

Ora_Logoff -- close an Oracle connection

Description

int ora_logoff ( int connection)

Retorna TRUE em caso de sucesso ou FALSE em falhas. Details about the error can be retrieved using the ora_error() and ora_errorcode() functions.

Logs out the user and disconnects from the server.

See also ora_logon().

Ora_Logon

(PHP 3, PHP 4 )

Ora_Logon -- open an Oracle connection

Description

int ora_logon ( string user, string password)

Establishes a connection between PHP and an Oracle database with the given username and password.

Connections can be made using SQL*Net by supplying the TNS name to user like this:

$conn = Ora_Logon("user@TNSNAME", "pass");

If you have character data with non-ASCII characters, you should make sure that NLS_LANG is set in your environment. For server modules, you should set it in the server's environment before starting the server.

Returns a connection index on success, or FALSE on failure. Details about the error can be retrieved using the ora_error() and ora_errorcode() functions.

Ora_Numcols

(PHP 3, PHP 4 )

Ora_Numcols -- Returns the number of columns

Description

int ora_numcols ( int cursor_ind)

ora_numcols() returns the number of columns in a result. Only returns meaningful values after an parse/exec/fetch sequence.

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

Ora_Numrows

(PHP 3, PHP 4 )

Ora_Numrows -- Returns the number of rows

Description

int ora_numrows ( int cursor_ind)

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

Ora_Open

(PHP 3, PHP 4 )

Ora_Open -- open an Oracle cursor

Description

int ora_open ( int connection)

Opens an Oracle cursor associated with connection.

Returns a cursor index or FALSE on failure. Details about the error can be retrieved using the ora_error() and ora_errorcode() functions.

Ora_Parse

(PHP 3, PHP 4 )

Ora_Parse -- parse an SQL statement

Description

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

This function parses an SQL statement or a PL/SQL block and associates it with the given cursor.

Retorna TRUE em caso de sucesso ou FALSE em falhas.

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

Ora_pLogon

(PHP 3, PHP 4 )

Ora_pLogon --  Open a persistent Oracle connection

Description

int ora_plogon ( string user, string password)

Establishes a persistent connection between PHP and an Oracle database with the given username and password.

See also ora_logon().

Ora_Rollback

(PHP 3, PHP 4 )

Ora_Rollback -- roll back transaction

Description

int ora_rollback ( int connection)

This function undoes an Oracle transaction. (See ora_commit() for the definition of a transaction.)

Retorna TRUE em caso de sucesso ou FALSE em falhas. Details about the error can be retrieved using the ora_error() and ora_errorcode() functions.

LXXIV. Ovrimos SQL functions

Introdução

Ovrimos SQL Server, is a client/server, transactional RDBMS combined with Web capabilities and fast transactions.

Nota: This extension is not available on Windows platforms.


Requisitos

Ovrimos SQL Server is available at http://www.ovrimos.com/. You'll need to install the sqlcli library available in the Ovrimos SQL Server distribution.


Instalação

To enable Ovrimos support in PHP just compile PHP with the --with-ovrimos[=DIR] parameter to your configure line. DIR is the Ovrimos' libsqlcli install directory.


Configuração durante execução

Esta extenção não define nenhum parâmetro de configuração no php.ini.


Tipos Resource


Exemplos

Exemplo 1. Connect to Ovrimos SQL Server and select from a system table

<?php
$conn = ovrimos_connect ("server.domain.com", "8001", "admin", "password");
if ($conn != 0) {
    echo ("Connection ok!");
    $res = ovrimos_exec ($conn, "select table_id, table_name from sys.tables");
    if ($res != 0) {
        echo "Statement ok!";
        ovrimos_result_all ($res);
        ovrimos_free_result ($res);
    }
    ovrimos_close($conn);
}
?>
This will just connect to an Ovrimos SQL server.

Índice
ovrimos_close -- Closes the connection to ovrimos
ovrimos_commit -- Commits the transaction
ovrimos_connect -- Connect to the specified database
ovrimos_cursor -- Returns the name of the cursor
ovrimos_exec -- Executes an SQL statement
ovrimos_execute -- Executes a prepared SQL statement
ovrimos_fetch_into -- Fetches a row from the result set
ovrimos_fetch_row -- Fetches a row from the result set
ovrimos_field_len -- Returns the length of the output column
ovrimos_field_name -- Returns the output column name
ovrimos_field_num --  Returns the (1-based) index of the output column
ovrimos_field_type --  Returns the (numeric) type of the output column
ovrimos_free_result -- Frees the specified result_id
ovrimos_longreadlen --  Specifies how many bytes are to be retrieved from long datatypes
ovrimos_num_fields -- Returns the number of columns
ovrimos_num_rows --  Returns the number of rows affected by update operations
ovrimos_prepare -- Prepares an SQL statement
ovrimos_result_all --  Prints the whole result set as an HTML table
ovrimos_result -- Retrieves the output column
ovrimos_rollback -- Rolls back the transaction

ovrimos_close

(PHP 4 >= 4.0.3)

ovrimos_close -- Closes the connection to ovrimos

Description

void ovrimos_close ( int connection)

ovrimos_close() is used to close the specified connection.

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

ovrimos_commit

(PHP 4 >= 4.0.3)

ovrimos_commit -- Commits the transaction

Description

int ovrimos_commit ( int connection_id)

ovrimos_commit() is used to commit the transaction.

ovrimos_commit() commits the transaction.

ovrimos_connect

(PHP 4 >= 4.0.3)

ovrimos_connect -- Connect to the specified database

Description

int ovrimos_connect ( string host, string db, string user, string password)

ovrimos_connect() is used to connect to the specified database.

ovrimos_connect() returns a connection id (greater than 0) or 0 for failure. The meaning of 'host' and 'port' are those used everywhere in Ovrimos APIs. 'Host' is a host name or IP address and 'db' is either a database name, or a string containing the port number.

Exemplo 1. ovrimos_connect() Example

<?php
$conn = ovrimos_connect ("server.domain.com", "8001", "admin", "password");
if ($conn != 0) {
    echo "Connection ok!";
    $res=ovrimos_exec ($conn, "select table_id, table_name from sys.tables");
    if ($res != 0) {
        echo "Statement ok!";
        ovrimos_result_all ($res);
        ovrimos_free_result ($res);
    }
    ovrimos_close($conn);
}
?>
The above example will connect to the database and print out the specified table.

ovrimos_cursor

(PHP 4 >= 4.0.3)

ovrimos_cursor -- Returns the name of the cursor

Description

int ovrimos_cursor ( int result_id)

ovrimos_cursor() is used to get the name of the cursor.

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

ovrimos_exec

(PHP 4 >= 4.0.3)

ovrimos_exec -- Executes an SQL statement

Description

int ovrimos_exec ( int connection_id, string query)

ovrimos_exec() is used to execute an SQL statement.

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

ovrimos_execute

(PHP 4 >= 4.0.3)

ovrimos_execute -- Executes a prepared SQL statement

Description

bool ovrimos_execute ( int result_id [, array parameters_array])

ovrimos_execute() is used to execute an SQL statement.

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

ovrimos_fetch_into

(PHP 4 >= 4.0.3)

ovrimos_fetch_into -- Fetches a row from the result set

Description

bool ovrimos_fetch_into ( int result_id, array result_array [, string how [, int rownumber]])

ovrimos_fetch_into() is used to fetch a row from the result set.

ovrimos_fetch_into() fetches a row from the result set into 'result_array', which should be passed by reference. Which row is fetched is determined by the two last parameters. 'how' is one of 'Next' (default), 'Prev', 'First', 'Last', 'Absolute', corresponding to forward direction from current position, backward direction from current position, forward direction from the start, backward direction from the end and absolute position from the start (essentially equivalent to 'first' but needs 'rownumber'). Case is not significant. 'Rownumber' is optional except for absolute positioning. Returns TRUE or FALSE.

Exemplo 1. A fetch into example

<?php
$conn=ovrimos_connect ("neptune", "8001", "admin", "password");
if ($conn!=0) {
    echo "Connection ok!";
    $res=ovrimos_exec ($conn,"select table_id, table_name from sys.tables");
    if ($res != 0) {
        echo "Statement ok!";
        if (ovrimos_fetch_into ($res, &$row)) {
            list ($table_id, $table_name) = $row;
            echo "table_id=".$table_id.", table_name=".$table_name."\n";
            if (ovrimos_fetch_into ($res, &$row)) {
                list ($table_id, $table_name) = $row;
                echo "table_id=".$table_id.", table_name=".$table_name."\n";
            } else {
                echo "Next: error\n";
            }
        } else {
            echo "First: error\n";
        }
        ovrimos_free_result ($res);
    }
    ovrimos_close($conn);
}
?>
This example will fetch a row.

ovrimos_fetch_row

(PHP 4 >= 4.0.3)

ovrimos_fetch_row -- Fetches a row from the result set

Description

bool ovrimos_fetch_row ( int result_id [, int how [, int row_number]])

ovrimos_fetch_row() is used to fetch a row from the result set.

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

Exemplo 1. A fetch row example

<?php
$conn = ovrimos_connect ("remote.host", "8001", "admin", "password");
if ($conn != 0) {
    echo "Connection ok!";
    $res=ovrimos_exec ($conn, "select table_id, table_name from sys.tables");
    if ($res != 0) {
        echo "Statement ok!";
        if (ovrimos_fetch_row ($res, "First")) {
            $table_id = ovrimos_result ($res, 1);
            $table_name = ovrimos_result ($res, 2);
            echo "table_id=".$table_id.", table_name=".$table_name."\n";
            if (ovrimos_fetch_row ($res, "Next")) {
                $table_id = ovrimos_result ($res, "table_id");
                $table_name = ovrimos_result ($res, "table_name");
                echo "table_id=".$table_id.", table_name=".$table_name."\n";
            } else {
                echo "Next: error\n";
            }
        } else {
            echo "First: error\n";
        }
        ovrimos_free_result ($res);
    }
    ovrimos_close($conn);
}
?>
This will fetch a row and print the result.

ovrimos_field_len

(PHP 4 >= 4.0.3)

ovrimos_field_len -- Returns the length of the output column

Description

int ovrimos_field_len ( int result_id, int field_number)

ovrimos_field_len() is used to get the length of the output column with number field_number, in result result_id.

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

ovrimos_field_name

(PHP 4 >= 4.0.3)

ovrimos_field_name -- Returns the output column name

Description

int ovrimos_field_name ( int result_id, int field_number)

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

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

ovrimos_field_num

(PHP 4 >= 4.0.3)

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

Description

int ovrimos_field_num ( int result_id, string field_name)

ovrimos_field_num() is used to get the (1-based) index of the output column.

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

ovrimos_field_type

(PHP 4 >= 4.0.3)

ovrimos_field_type --  Returns the (numeric) type of the output column

Description

int ovrimos_field_type ( int result_id, int field_number)

ovrimos_field_type() is used to get the (numeric) type of the output column.

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

ovrimos_free_result

(PHP 4 >= 4.0.3)

ovrimos_free_result -- Frees the specified result_id

Description

bool ovrimos_free_result ( int result_id)

ovrimos_free_result() is used to free the result_id.

ovrimos_free_result() frees the specified result_id result_id. Returns TRUE.

ovrimos_longreadlen

(PHP 4 >= 4.0.3)

ovrimos_longreadlen --  Specifies how many bytes are to be retrieved from long datatypes

Description

int ovrimos_longreadlen ( int result_id, int length)

ovrimos_longreadlen() is used to specify how many bytes are to be retrieved from long datatypes.

ovrimos_longreadlen() specifies how many bytes are to be retrieved from long datatypes (long varchar and long varbinary). Default is zero. It currently sets this parameter the specified result set. Returns TRUE.

ovrimos_num_fields

(PHP 4 >= 4.0.3)

ovrimos_num_fields -- Returns the number of columns

Description

int ovrimos_num_fields ( int result_id)

ovrimos_num_fields() is used to get the number of columns.

ovrimos_num_fields() returns the number of columns in a result_id resulting from a query.

ovrimos_num_rows

(PHP 4 >= 4.0.3)

ovrimos_num_rows --  Returns the number of rows affected by update operations

Description

int ovrimos_num_rows ( int result_id)

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

ovrimos_num_rows() returns the number of rows affected by update operations.

ovrimos_prepare

(PHP 4 >= 4.0.3)

ovrimos_prepare -- Prepares an SQL statement

Description

int ovrimos_prepare ( int connection_id, string query)

ovrimos_prepare() is used to prepare an SQL statement.

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

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

<?php
$conn=ovrimos_connect ("db_host", "8001", "admin", "password");
if ($conn!=0) {
    echo "Connection ok!";
    $res=ovrimos_prepare ($conn, "select table_id, table_name 
                                  from sys.tables where table_id=1");
    if ($res != 0) {
        echo "Prepare ok!";
        if (ovrimos_execute ($res)) {
            echo "Execute ok!\n";
            ovrimos_result_all ($res);
        } else {
            echo "Execute not ok!";
        }
        ovrimos_free_result ($res);
    } else {
        echo "Prepare not ok!\n";
    }
    ovrimos_close($conn);
}
?>
This will connect to Ovrimos SQL Server, prepare a statement and the execute it.

ovrimos_result_all

(PHP 4 >= 4.0.3)

ovrimos_result_all --  Prints the whole result set as an HTML table

Description

bool ovrimos_result_all ( int result_id [, string format])

ovrimos_result_all() is used to print an HTML table containing the whole result set.

ovrimos_result_all() prints the whole result set as an HTML table. Returns TRUE or FALSE.

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

<?php
$conn = ovrimos_connect ("db_host", "8001", "admin", "password");
if ($conn != 0) {
    echo "Connection ok!";
    $res = ovrimos_prepare ($conn, "select table_id, table_name 
                                    from sys.tables where table_id = 7");
    if ($res != 0) {
        echo "Prepare ok!";
        if (ovrimos_execute ($res, array(3))) {
            echo "Execute ok!\n";
            ovrimos_result_all ($res);
        } else {
            echo "Execute not ok!";
        }
        ovrimos_free_result ($res);
    } else {
        echo "Prepare not ok!\n";
    }
    ovrimos_close($conn);
}
?>
This will execute an SQL statement and print the result in an HTML table.

Exemplo 2. Ovrimos_result_all with meta-information

<?php
$conn = ovrimos_connect ("db_host", "8001", "admin", "password");
if ($conn != 0) {
    echo "Connection ok!";
    $res = ovrimos_exec ($conn, "select table_id, table_name 
                                 from sys.tables where table_id = 1")
    if ($res != 0) {
        echo "Statement ok! cursor=".ovrimos_cursor ($res)."\n";
        $colnb = ovrimos_num_fields ($res);
        echo "Output columns=".$colnb."\n";
        for ($i=1; $i <= $colnb; $i++) {
            $name = ovrimos_field_name ($res, $i);
            $type = ovrimos_field_type ($res, $i);
            $len = ovrimos_field_len ($res, $i);  
            echo "Column ".$i." name=".$name." type=".$type." len=".$len."\n";
        }
        ovrimos_result_all ($res);
        ovrimos_free_result ($res);
    }
    ovrimos_close($conn);
}
?>

Exemplo 3. ovrimos_result_all example

<?php
$conn = ovrimos_connect ("db_host", "8001", "admin", "password");
if ($conn != 0) {
    echo "Connection ok!";
    $res = ovrimos_exec ($conn, "update test set i=5");
    if ($res != 0) {
        echo "Statement ok!";
        echo ovrimos_num_rows ($res)." rows affected\n";
        ovrimos_free_result ($res);
    }
    ovrimos_close($conn);
}
?>

ovrimos_result

(PHP 4 >= 4.0.3)

ovrimos_result -- Retrieves the output column

Description

int ovrimos_result ( int result_id, mixed field)

ovrimos_result() is used to retrieve the output column.

ovrimos_result() retrieves the output column specified by 'field', either as a string or as an 1-based index.

ovrimos_rollback

(PHP 4 >= 4.0.3)

ovrimos_rollback -- Rolls back the transaction

Description

int ovrimos_rollback ( int connection_id)

ovrimos_rollback() is used to roll back the transaction.

ovrimos_rollback() rolls back the transaction.

LXXV. Output Control Functions

Introdução

The Output Control functions allow you to control when output is sent from the script. This can be useful in several different situations, especially if you need to send headers to the browser after your script has began outputting data. The Output Control functions do not affect headers sent using header() or setcookie(), only functions such as echo() and data between blocks of PHP code.


Requisitos

Nenhuma biblioteca externa é necessária para compilar esta extensão.


Instalação

Não há nenhuma instalação nescessária para utilizar estas funções, elas fazem parte do núcleo do PHP.


Configuração durante execução

O comportamento dessas funções podem ser modificado pelas configurações do php.ini.

Tabela 1. Output Control configuration options

Name Default Changeable
output_buffering "0" PHP_INI_PERDIR|PHP_INI_SYSTEM
output_handler NULL PHP_INI_PERDIR|PHP_INI_SYSTEM
implicit_flush "0" PHP_INI_PERDIR|PHP_INI_SYSTEM
For further details and definition of the PHP_INI_* constants see ini_set().

Here is a short explanation of the configuration directives.

output_buffering boolean/integer

You can enable output buffering for all files by setting this directive to 'On'. If you wish to limit the size of the buffer to a certain size - you can use a maximum number of bytes instead of 'On', as a value for this directive (e.g., output_buffering=4096).

output_handler string

You can redirect all of the output of your scripts to a function. For example, if you set output_handler to mb_output_handler(), character encoding will be transparently converted to the specified encoding. Setting any output handler automatically turns on output buffering.

Nota: You cannot use both mb_output_handler() with ob_inconv_handler() and you cannot use both ob_gzhandler() and zlib.output_compression.

implicit_flush boolean

FALSE by default. Changing this to TRUE tells PHP to tell the output layer to flush itself automatically after every output block. This is equivalent to calling the PHP function flush() after each and every call to print() or echo() and each and every HTML block.

When using PHP within an web environment, turning this option on has serious performance implications and is generally recommended for debugging purposes only. This value defaults to TRUE when operating under the CLI SAPI.

See also ob_implicit_flush().


Tipos Resource

Esta extensão não possui nenhum tipo resource.


Constantes Predefinidas

Esta extensão não possui nenhuma constante.


Exemplos

Exemplo 1. Output Control example

<?php

ob_start();
echo "Hello\n";

setcookie ("cookiename", "cookiedata");

ob_end_flush();

?>

In the above example, the output from echo() would be stored in the output buffer until ob_end_flush() was called. In the mean time, the call to setcookie() successfully stored a cookie without causing an error. (You can not normally send headers to the browser after data has already been sent.)

Nota: When upgrading from PHP 4.1 (and 4.2) to 4.3 that due to a bug in earlier versions you must ensure that implict_flush is OFF in your php.ini, otherwise any output with ob_start() will be not be hidden from output.


Veja Também

See also header() and setcookie().

Índice
flush -- Flush the output buffer
ob_clean --  Clean (erase) the output buffer
ob_end_clean --  Clean (erase) the output buffer and turn off output buffering
ob_end_flush --  Flush (send) the output buffer and turn off output buffering
ob_flush --  Flush (send) the output buffer
ob_get_contents --  Return the contents of the output buffer
ob_get_length --  Return the length of the output buffer
ob_get_level --  Return the nesting level of the output buffering mechanism
ob_get_status --  Get status of output buffers
ob_gzhandler --  ob_start callback function to gzip output buffer
ob_implicit_flush --  Turn implicit flush on/off
ob_start -- Turn on output buffering

flush

(PHP 3, PHP 4 )

flush -- Flush the output buffer

Description

void flush ( void)

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

Nota: flush() has no effect on the buffering scheme of your webserver or the browser on the client side.

Several servers, especially on Win32, will still buffer the output from your script until it terminates before transmitting the results to the browser.

Server modules for Apache like mod_gzip may do buffering of their own that will cause flush() to not result in data being sent immediately to the client.

Even the browser may buffer its input before displaying it. Netscape, for example, buffers text until it receives an end-of-line or the beginning of a tag, and it won't render tables until the </table> tag of the outermost table is seen.

Some versions of Microsoft Internet Explorer will only start to display the page after they have received 256 bytes of output, so you may need to send extra whitespace before flushing to get those browsers to display the page.

ob_clean

(PHP 4 >= 4.2.0)

ob_clean --  Clean (erase) the output buffer

Description

void ob_clean ( void)

This function discards the contents of the output buffer.

This function does not destroy the output buffer like ob_end_clean() does.

See also ob_flush(), ob_end_flush() and ob_end_clean().

ob_end_clean

(PHP 4 )

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

Description

void ob_end_clean ( void)

This function discards the contents of the output buffer and turns off output buffering.

See also ob_start(), ob_clean() and ob_end_flush().

ob_end_flush

(PHP 4 )

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

Description

void ob_end_flush ( void)

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

See also ob_start(), ob_get_contents(), ob_flush() and ob_end_clean().

ob_flush

(PHP 4 >= 4.2.0)

ob_flush --  Flush (send) the output buffer

Description

void ob_flush ( void)

This function will send the contents of the output buffer (if any). If you want to further process the buffer's contents you have to call ob_get_contents() before ob_flush() as the buffer contents are discarded after ob_flush() is called.

This function does not destroy the output buffer like ob_end_flush() does.

See also ob_get_contents(), ob_clean(), ob_end_flush() and ob_end_clean().

ob_get_contents

(PHP 4 )

ob_get_contents --  Return the contents of the output buffer

Description

string ob_get_contents ( void)

This will return the contents of the output buffer or FALSE, if output buffering isn't active.

See also ob_start() and ob_get_length().

ob_get_length

(PHP 4 >= 4.0.2)

ob_get_length --  Return the length of the output buffer

Description

string ob_get_length ( void)

This will return the length of the contents in the output buffer or FALSE, if output buffering isn't active.

See also ob_start() and ob_get_contents().

ob_get_level

(PHP 4 >= 4.2.0)

ob_get_level --  Return the nesting level of the output buffering mechanism

Description

int ob_get_level ( void)

This will return the level of nested output buffering handlers.

See also ob_start() and ob_get_contents().

ob_get_status

(PHP 4 >= 4.2.0)

ob_get_status --  Get status of output buffers

Description

array ob_get_status ( [bool full_status])

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

This will return the current status of output buffers. It returns array contains buffer status or FALSE for error.

See also ob_get_level().

ob_gzhandler

(PHP 4 >= 4.0.4)

ob_gzhandler --  ob_start callback function to gzip output buffer

Description

string ob_gzhandler ( string buffer [, int mode])

Nota: mode was added in PHP 4.0.5.

ob_gzhandler() is intended to be used as a callback function for ob_start() to help facilitate sending gz-encoded data to web browsers that support compressed web pages. Before ob_gzhandler() actually sends compressed data, it determines what type of content encoding the browser will accept ("gzip", "deflate" or none at all) and will return it's output accordingly. All browsers are supported since it's up to the browser to send the correct header saying that it accepts compressed web pages.

Nota: You cannot use both ob_gzhandler() and ini.zlib.output_compression. Also note that using ini.zlib.output_compression is preferred over ob_gzhandler().

Exemplo 1. ob_gzhandler() Example

<?php

ob_start("ob_gzhandler");

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

See also ob_start() and ob_end_flush().

ob_implicit_flush

(PHP 4 )

ob_implicit_flush --  Turn implicit flush on/off

Description

void ob_implicit_flush ( [int flag])

ob_implicit_flush() will turn implicit flushing on or off (if no flag is given, it defaults to on). Implicit flushing will result in a flush operation after every output call, so that explicit calls to flush() will no longer be needed.

Turning implicit flushing on will disable output buffering, the output buffers current output will be sent as if ob_end_flush() had been called.

See also flush(), ob_start(), and ob_end_flush().

ob_start

(PHP 4 )

ob_start -- Turn on output buffering

Description

void ob_start ( [string output_callback])

This function will turn output buffering on. While output buffering is active no output is sent from the script (other than headers), instead the output is stored in an internal buffer.

The contents of this internal buffer may be copied into a string variable using ob_get_contents(). To output what is stored in the internal buffer, use ob_end_flush(). Alternatively, ob_end_clean() will silently discard the buffer contents.

An optional output_callback function may be specified. This function takes a string as a parameter and should return a string. The function will be called when ob_end_flush() is called, or when the output buffer is flushed to the browser at the end of the request. When output_callback is called, it will receive the contents of the output buffer as its parameter and is expected to return a new output buffer as a result, which will be sent to the browser.

Nota: In PHP 4.0.4, ob_gzhandler() was introduced to facilitate sending gz-encoded data to web browsers that support compressed web pages. ob_gzhandler() determines what type of content encoding the browser will accept and will return it's output accordingly.

Output buffers are stackable, that is, you may call ob_start() while another ob_start() is active. Just make sure that you call ob_end_flush() the appropriate number of times. If multiple output callback functions are active, output is being filtered sequentially through each of them in nesting order.

ob_end_clean(), ob_end_flush(), ob_clean(), ob_flush() and ob_start() may not be called from a callback function. If you call them from callback function, the behavior is undefined. If you would like to delete the contents of a buffer, return "" (a null string) from callback function.

Exemplo 1. User defined callback function example

<?php

function callback($buffer) {

  // replace all the apples with oranges
  return (ereg_replace("apples", "oranges", $buffer));

}

ob_start("callback");

?>

<html>
<body>
<p>It's like comparing apples to oranges.
</body>
</html>

<?php

ob_end_flush();

?>

Would produce:

<html>
<body>
<p>It's like comparing oranges to oranges.
</body>
</html>

See also ob_get_contents(), ob_end_flush(), ob_end_clean(), ob_implicit_flush() and ob_gzhandler().

LXXVI. Sobrecarga de propriedades e métodos de objetos

Introdução

O propósito desta extensão é permitir a sobrecarga de propriedades de acesso e metodos de objetos. Somente uma função é definida nesta extensão, overload() que recebe o nome da classe que deve ter esta funcionalidade habilitada. A classe especificada tem que definir os metodos para ter esta funcionalidade: __get(), __set() e __call() respectivamente para leitura/escrita das propriedades, ou chamar um metodo. Desta forma a sobrecarga pode ser seletiva: Dentro destas funções a sobrecarga é desabilitada de forma que você possa acessar propriedades do objeto normalmente.

Atenção

Este módulo é EXPERIMENTAL. Isso quer dizer que o comportamento neste módulo --- incluindo suas funções e seus nomes, e TUDO mais que está documentado sobre esse módulo --- poderá mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use este módulo por sua própria conta e risco.


Requisitos

Nenhuma biblioteca externa é necessária para compilar esta extensão.


Instalação

Para poder utilizar essas funções, você precisa compilar o PHP com a opção --enable-overload.


Configuração durante execução

Esta extenção não define nenhum parâmetro de configuração no php.ini.


Tipos Resource

Esta extensão não possui nenhum tipo resource.


Constantes Predefinidas

Esta extensão não possui nenhuma constante.


Exemplos

Alguns exemplos simples da utilização da função overload():

Exemplo 1. Sobrecarga de uma classe no PHP

<?php

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

    // Metodo callback para pegar uma propriedade
    function __get($prop_name, &$prop_value)
    {
        if (isset($this->elem[$prop_name])) {
            $prop_value = $this->elem[$prop_name];
            return true;
        } else {
            return false;
        }
    }

    // Metodo callback para definir uma propriedade
    function __set($prop_name, $prop_value)
    {
        $this->elem[$prop_name] = $prop_value;
        return true;
    }
}

// Aqui nós sobrecarregamos o objeto OO
overload('OO');

$o = new OO;
print "\$o->a: $o->a\n"; // imprime: $o->a:
print "\$o->b: $o->b\n"; // imprime: $o->b: 9
print "\$o->c: $o->c\n"; // imprime: $o->c: 42
print "\$o->d: $o->d\n"; // imprime: $o->d:

// adicionar um novo intem para o array $elem em OO
$o->x = 56;

// iniciar stdclass (é integrada no PHP 4)
// $var não é sobrecarregada!
$val = new stdclass;
$val->prop = 555;

// Que "a" seja um array com o objeto $val dentro dele
// mas __set() o colocará no array $elem
$o->a = array($val);
var_dump($o->a[0]->prop);

?>

Atenção

Como esta é uma extensão experimental, nem todas as coisas funcionam. Não existe ainda suporte para __call() e você somente pode fazer a sobrecaraga das operações get e set para propriedades. Você não pode invocar as chamadas originais da classe e __set() somente funciona até um nível de acesso de propriedades.

Índice
overload -- Ativa a chamada sobrecarregada de propriedades e métodos para uma classe

overload

(4.2.0 - 4.3.0 only)

overload -- Ativa a chamada sobrecarregada de propriedades e métodos para uma classe

Descrição

void overload ( [string class_name])

A função overload() ativa a chamada sobrecarregada de propriedades e métodos para a classe identificada por class_name. Veja o exemplo na seção introdutória desse módulo.

LXXVII. PDF functions

Introdução

The PDF functions in PHP can create PDF files using the PDFlib library created by Thomas Merz.

The documentation in this section is only meant to be an overview of the available functions in the PDFlib library and should not be considered an exhaustive reference. Please consult the documentation included in the source distribution of PDFlib for the full and detailed explanation of each function here. It provides a very good overview of what PDFlib is capable of doing and contains the most up-to-date documentation of all functions.

All of the functions in PDFlib and the PHP module have identical function names and parameters. You will need to understand some of the basic concepts of PDF and PostScript to efficiently use this extension. All lengths and coordinates are measured in PostScript points. There are generally 72 PostScript points to an inch, but this depends on the output resolution. Please see the PDFlib documentation included with the source distribution of PDFlib for a more thorough explanation of the coordinate system used.

Please note that most of the PDF functions require a pdf object as its first parameter. Please see the examples below for more information.


Requisitos

PDFlib is available for download at http://www.pdflib.com/pdflib/index.html, but requires that you purchase a license for commercial use. The JPEG and TIFF libraries are required to compile this extension.


Issues with older versions of PDFlib

Any version of PHP 4 after March 9, 2000 does not support versions of PDFlib older than 3.0.

PDFlib 3.0 or greater is supported by PHP 3.0.19 and later.


Instalação

To get these functions to work, you have to compile PHP with --with-pdflib[=DIR]. DIR is the PDFlib base install directory, defaults to /usr/local. In addition you can specify the jpeg, tiff, and pnglibrary for PDFlib to use, which is optional for PDFlib 4.x. To do so add to your configure line the options --with-jpeg-dir[=DIR] --with-png-dir[=DIR] --with-tiff-dir[=DIR].

When using version 3.x of PDFlib, you should configure PDFlib with the option --enable-shared-pdflib.


Configuração durante execução

Esta extenção não define nenhum parâmetro de configuração no php.ini.


Confusion with old PDFlib versions

Starting with PHP 4.0.5, the PHP extension for PDFlib is officially supported by PDFlib GmbH. This means that all the functions described in the PDFlib manual (V3.00 or greater) are supported by PHP 4 with exactly the same meaning and the same parameters. Only the return values may differ from the PDFlib manual, because the PHP convention of returning FALSE was adopted. For compatibility reasons, this binding for PDFlib still supports the old functions, but they should be replaced by their new versions. PDFlib GmbH will not support any problems arising from the use of these deprecated functions.

Tabela 1. Deprecated functions and their replacements

Old function Replacement
pdf_put_image() Not needed anymore.
pdf_execute_image() Not needed anymore.
pdf_get_annotation() pdf_get_bookmark() using the same parameters.
pdf_get_font() pdf_get_value() passing "font" as the second parameter.
pdf_get_fontsize() pdf_get_value() passing "fontsize" as the second parameter.
pdf_get_fontname() pdf_get_parameter() passing "fontname" as the second parameter.
pdf_set_info_creator() pdf_set_info() passing "Creator" as the second parameter.
pdf_set_info_title() pdf_set_info() passing "Title" as the second parameter.
pdf_set_info_subject() pdf_set_info() passing "Subject" as the second parameter.
pdf_set_info_author() pdf_set_info() passing "Author" as the second parameter.
pdf_set_info_keywords() pdf_set_info() passing "Keywords" as the second parameter.
pdf_set_leading() pdf_set_value() passing "leading" as the second parameter.
pdf_set_text_rendering() pdf_set_value() passing "textrendering" as the second parameter.
pdf_set_text_rise() pdf_set_value() passing "textrise" as the second parameter.
pdf_set_horiz_scaling() pdf_set_value() passing "horizscaling" as the second parameter.
pdf_set_text_matrix() Not available anymore
pdf_set_char_spacing() pdf_set_value() passing "charspacing" as the second parameter.
pdf_set_word_spacing() pdf_set_value() passing "wordspacing" as the second parameter.
pdf_set_transition() pdf_set_parameter() passing "transition" as the second parameter.
pdf_open() pdf_new() plus an subsequent call of pdf_open_file()
pdf_set_font() pdf_findfont() plus an subsequent call of pdf_setfont()
pdf_set_duration() pdf_set_value() passing "duration" as the second parameter.
pdf_open_gif() pdf_open_image_file() passing "gif" as the second parameter.
pdf_open_jpeg() pdf_open_image_file() passing "jpeg" as the second parameter.
pdf_open_tiff() pdf_open_image_file() passing "tiff" as the second parameter.
pdf_open_png() pdf_open_image_file() passing "png" as the second parameter.
pdf_get_image_width() pdf_get_value() passing "imagewidth" as the second parameter and the image as the third parameter.
pdf_get_image_height() pdf_get_value() passing "imageheight" as the second parameter and the image as the third parameter.


Exemplos

Most of the functions are fairly easy to use. The most difficult part is probably creating your first PDF document. The following example should help to get you started. It creates test.pdf with one page. The page contains the text "Times Roman outlined" in an outlined, 30pt font. The text is also underlined.

Exemplo 1. Creating a PDF document with PDFlib

<?php
$pdf = pdf_new();
pdf_open_file($pdf, "test.pdf");
pdf_set_info($pdf, "Author", "Uwe Steinmann");
pdf_set_info($pdf, "Title", "Test for PHP wrapper of PDFlib 2.0");
pdf_set_info($pdf, "Creator", "See Author");
pdf_set_info($pdf, "Subject", "Testing");
pdf_begin_page($pdf, 595, 842);
pdf_add_outline($pdf, "Page 1");
$font = pdf_findfont($pdf, "Times New Roman", "winansi", 1);
pdf_setfont($pdf, $font, 10);
pdf_set_value($pdf, "textrendering", 1);
pdf_show_xy($pdf, "Times Roman outlined", 50, 750);
pdf_moveto($pdf, 50, 740);
pdf_lineto($pdf, 330, 740);
pdf_stroke($pdf);
pdf_end_page($pdf);
pdf_close($pdf);
pdf_delete($pdf);
echo "<A HREF=getpdf.php>finished</A>";
?>

The script getpdf.php just returns the pdf document.

<?php
$len = filesize($filename);
header("Content-type: application/pdf");
header("Content-Length: $len");
header("Content-Disposition: inline; filename=foo.pdf");
readfile($filename);
?>

The PDFlib distribution contains a more complex example which creates a page with an analog clock. Here we use the in-memory creation feature of PDFlib to alleviate the need to use temporary files. The example was converted to PHP from the PDFlib example. (The same example is available in the CLibPDF documentation.)

Exemplo 2. pdfclock example from PDFlib distribution

<?php
$radius = 200;
$margin = 20;
$pagecount = 10;

$pdf = pdf_new();

if (!pdf_open_file($pdf, "")) {
    print error;
    exit;
};

pdf_set_parameter($pdf, "warning", "true");

pdf_set_info($pdf, "Creator", "pdf_clock.php");
pdf_set_info($pdf, "Author", "Uwe Steinmann");
pdf_set_info($pdf, "Title", "Analog Clock");

while($pagecount-- > 0) {
    pdf_begin_page($pdf, 2 * ($radius + $margin), 2 * ($radius + $margin));

    pdf_set_parameter($pdf, "transition", "wipe");
    pdf_set_value($pdf, "duration", 0.5);
  
    pdf_translate($pdf, $radius + $margin, $radius + $margin);
    pdf_save($pdf);
    pdf_setrgbcolor($pdf, 0.0, 0.0, 1.0);

    /* minute strokes */
    pdf_setlinewidth($pdf, 2.0);
    for ($alpha = 0; $alpha < 360; $alpha += 6) {
        pdf_rotate($pdf, 6.0);
        pdf_moveto($pdf, $radius, 0.0);
        pdf_lineto($pdf, $radius-$margin/3, 0.0);
        pdf_stroke($pdf);
    }

    pdf_restore($pdf);
    pdf_save($pdf);

    /* 5 minute strokes */
    pdf_setlinewidth($pdf, 3.0);
    for ($alpha = 0; $alpha < 360; $alpha += 30) { 
        pdf_rotate($pdf, 30.0);
        pdf_moveto($pdf, $radius, 0.0);
        pdf_lineto($pdf, $radius-$margin, 0.0);
        pdf_stroke($pdf);
    }

    $ltime = getdate();

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

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

    /* draw second hand */
    pdf_setrgbcolor($pdf, 1.0, 0.0, 0.0);
    pdf_setlinewidth($pdf, 2);
    pdf_save($pdf);
    pdf_rotate($pdf, -(($ltime['seconds'] - 15.0) * 6.0));
    pdf_moveto($pdf, -$radius/5, 0.0);
    pdf_lineto($pdf, $radius, 0.0);
    pdf_stroke($pdf);
    pdf_restore($pdf);

    /* draw little circle at center */
    pdf_circle($pdf, 0, 0, $radius/30);
    pdf_fill($pdf);

    pdf_restore($pdf);

    pdf_end_page($pdf);

    # to see some difference
    sleep(1);
}

pdf_close($pdf);

$buf = pdf_get_buffer($pdf);
$len = strlen($buf);

header("Content-type: application/pdf");
header("Content-Length: $len");
header("Content-Disposition: inline; filename=foo.pdf");
print $buf;

pdf_delete($pdf);
?>


Veja Também

Nota: An alternative PHP module for PDF document creation based on FastIO's ClibPDF is available. Please see the ClibPDF section for details. Note that ClibPDF has a slightly different API than PDFlib.

Índice
pdf_add_annotation -- Deprecated: Adds annotation
pdf_add_bookmark -- Adds bookmark for current page
pdf_add_launchlink -- Add a launch annotation for current page
pdf_add_locallink -- Add a link annotation for current page
pdf_add_note -- Add a note annotation for current page
pdf_add_outline -- Deprecated: Adds bookmark for current page
pdf_add_pdflink -- Adds file link annotation for current page
pdf_add_thumbnail -- Adds thumbnail for current page
pdf_add_weblink -- Adds weblink for current page
pdf_arc -- Draws an arc (counterclockwise)
pdf_arcn -- Draws an arc (clockwise)
pdf_attach_file -- Adds a file attachement for current page
pdf_begin_page -- Starts new page
pdf_begin_pattern -- Starts new pattern
pdf_begin_template -- Starts new template
pdf_circle -- Draws a circle
pdf_clip -- Clips to current path
pdf_close_image -- Closes an image
pdf_close_pdi_page --  Close the page handle
pdf_close_pdi --  Close the input PDF document
pdf_close -- Closes a pdf object
pdf_closepath_fill_stroke -- Closes, fills and strokes current path
pdf_closepath_stroke -- Closes path and draws line along path
pdf_closepath -- Closes path
pdf_concat -- Concatenate a matrix to the CTM
pdf_continue_text -- Outputs text in next line
pdf_curveto -- Draws a curve
pdf_delete -- Deletes a PDF object
pdf_end_page -- Ends a page
pdf_end_pattern -- Finish pattern
pdf_end_template -- Finish template
pdf_endpath -- Deprecated: Ends current path
pdf_fill_stroke -- Fills and strokes current path
pdf_fill -- Fills current path
pdf_findfont -- Prepare font for later use with pdf_setfont().
pdf_get_buffer -- Fetch the buffer containig the generated PDF data.
pdf_get_font -- Deprecated: font handling
pdf_get_fontname -- Deprecated: font handling
pdf_get_fontsize -- Deprecated: font handling
pdf_get_image_height -- Returns height of an image
pdf_get_image_width -- Returns width of an image
pdf_get_majorversion --  Returns the major version number of the PDFlib
pdf_get_minorversion --  Returns the minor version number of the PDFlib
pdf_get_parameter -- Gets certain parameters
pdf_get_pdi_parameter -- Get some PDI string parameters
pdf_get_pdi_value -- Gets some PDI numerical parameters
pdf_get_value -- Gets certain numerical value
pdf_initgraphics -- Resets graphic state
pdf_lineto -- Draws a line
pdf_makespotcolor -- Makes a spotcolor
pdf_moveto -- Sets current point
pdf_new -- Creates a new pdf object
pdf_open_CCITT -- Opens a new image file with raw CCITT data
pdf_open_file -- Opens a new pdf object
pdf_open_gif -- Deprecated: Opens a GIF image
pdf_open_image_file -- Reads an image from a file
pdf_open_image -- Versatile function for images
pdf_open_jpeg -- Deprecated: Opens a JPEG image
pdf_open_memory_image -- Opens an image created with PHP's image functions
pdf_open_pdi_page --  Prepare a page
pdf_open_pdi --  Opens a PDF file
pdf_open_png --  Deprecated: Opens a PNG image
pdf_open_tiff -- Deprecated: Opens a TIFF image
pdf_open -- Deprecated: Open a new pdf object
pdf_place_image -- Places an image on the page
pdf_place_pdi_page -- Places an image on the page
pdf_rect -- Draws a rectangle
pdf_restore -- Restores formerly saved environment
pdf_rotate -- Sets rotation
pdf_save -- Saves the current environment
pdf_scale -- Sets scaling
pdf_set_border_color -- Sets color of border around links and annotations
pdf_set_border_dash -- Sets dash style of border around links and annotations
pdf_set_border_style -- Sets style of border around links and annotations
pdf_set_char_spacing -- Deprecated: Sets character spacing
pdf_set_duration -- Deprecated: Sets duration between pages
pdf_set_font -- Deprecated: Selects a font face and size
pdf_set_horiz_scaling -- Sets horizontal scaling of text
pdf_set_info_author --  Fills the author field of the document
pdf_set_info_creator --  Fills the creator field of the document
pdf_set_info_keywords --  Fills the keywords field of the document
pdf_set_info_subject --  Fills the subject field of the document
pdf_set_info_title --  Fills the title field of the document
pdf_set_info -- Fills a field of the document information
pdf_set_leading -- Deprecated: Sets distance between text lines
pdf_set_parameter -- Sets certain parameters
pdf_set_text_matrix -- Deprecated: Sets the text matrix
pdf_set_text_pos -- Sets text position
pdf_set_text_rendering -- Deprecated: Determines how text is rendered
pdf_set_text_rise -- Deprecated: Sets the text rise
pdf_set_value -- Sets certain numerical value
pdf_set_word_spacing -- Depriciated: Sets spacing between words
pdf_setcolor -- Sets fill and stroke color
pdf_setdash -- Sets dash pattern
pdf_setflat -- Sets flatness
pdf_setfont -- Set the current font
pdf_setgray_fill -- Sets filling color to gray value
pdf_setgray_stroke -- Sets drawing color to gray value
pdf_setgray -- Sets drawing and filling color to gray value
pdf_setlinecap -- Sets linecap parameter
pdf_setlinejoin -- Sets linejoin parameter
pdf_setlinewidth -- Sets line width
pdf_setmatrix -- Sets current transformation matrix
pdf_setmiterlimit -- Sets miter limit
pdf_setpolydash -- Sets complicated dash pattern
pdf_setrgbcolor_fill -- Sets filling color to rgb color value
pdf_setrgbcolor_stroke -- Sets drawing color to rgb color value
pdf_setrgbcolor -- Sets drawing and filling color to rgb color value
pdf_show_boxed -- Output text in a box
pdf_show_xy -- Output text at given position
pdf_show -- Output text at current position
pdf_skew -- Skews the coordinate system
pdf_stringwidth -- Returns width of text using current font
pdf_stroke -- Draws line along path
pdf_translate -- Sets origin of coordinate system

pdf_add_annotation

pdf_add_annotation -- Deprecated: Adds annotation

Description

pdf_add_outline() is replaced by pdf_add_note()

See also pdf_add_note().

pdf_add_bookmark

(PHP 4 >= 4.0.1)

pdf_add_bookmark -- Adds bookmark for current page

Description

int pdf_add_bookmark ( int pdf object, string text [, int parent [, int open]])

Add a nested bookmark under parent, or a new top-level bookmark if parent = 0. Returns a bookmark descriptor which may be used as parent for subsequent nested bookmarks. If open = 1, child bookmarks will be folded out, and invisible if open = 0.

pdf_add_launchlink

(PHP 4 >= 4.0.5)

pdf_add_launchlink -- Add a launch annotation for current page

Description

int pdf_add_launchlink ( int pdf object, float llx, float lly, float urx, float ury, string filename)

Add a launch annotation (to a target of arbitrary file type).

pdf_add_locallink

(PHP 4 >= 4.0.5)

pdf_add_locallink -- Add a link annotation for current page

Description

int pdf_add_locallink ( int pdf object, float llx, float lly, float urx, float ury, int page, string dest)

Add a link annotation to a target within the current PDF file.

pdf_add_note

(PHP 4 >= 4.0.5)

pdf_add_note -- Add a note annotation for current page

Description

int pdf_add_note ( int pdf object, float llx, float lly, float urx, float ury, string contents, string title, string icon, int open)

Add a note annotation. icon is one of of "comment, "insert", "note", "paragraph", "newparagraph", "key", or "help".

pdf_add_outline

pdf_add_outline -- Deprecated: Adds bookmark for current page

Description

Deprecated.

See pdf_add_bookmark().

pdf_add_pdflink

(PHP 3>= 3.0.12, PHP 4 )

pdf_add_pdflink -- Adds file link annotation for current page

Description

int pdf_add_pdflink ( int pdf object, float llx, float lly, float urx, float ury, string filename, int page, string dest)

Add a file link annotation (to a PDF target).

pdf_add_thumbnail

(PHP 4 >= 4.0.5)

pdf_add_thumbnail -- Adds thumbnail for current page

Description

int pdf_add_thumbnail ( int pdf object, int image)

Add an existing image as thumbnail for the current page.

pdf_add_weblink

(PHP 3>= 3.0.12, PHP 4 )

pdf_add_weblink -- Adds weblink for current page

Description

int pdf_add_weblink ( int pdf object, float llx, float lly, float urx, float ury, string url)

Add a weblink annotation to a target URL on the Web.

pdf_arc

(PHP 3>= 3.0.6, PHP 4 )

pdf_arc -- Draws an arc (counterclockwise)

Description

void pdf_arc ( resource pdf object, float x, float y, float r, float alpha, float beta)

Draw a counterclockwise circular arc from alpha to beta degrees

See also: pdf_arcn()

pdf_arcn

(PHP 4 >= 4.0.5)

pdf_arcn -- Draws an arc (clockwise)

Description

void pdf_arc ( resource pdf object, float x, float y, float r, float alpha, float beta)

Draw a clockwise circular arc from alpha to beta degrees

See also: pdf_arc()

pdf_attach_file

(PHP 4 >= 4.0.5)

pdf_attach_file -- Adds a file attachement for current page

Description

int pdf_attach_file ( int pdf object, float llx, float lly, float urx, float ury, string filename, string description, string author, string mimetype, string icon)

Add a file attachment annotation. icon is one of "graph, "paperclip", "pushpin", or "tag".

pdf_begin_page

(PHP 3>= 3.0.6, PHP 4 )

pdf_begin_page -- Starts new page

Description

void pdf_begin_page ( int pdf object, float width, float height)

Add a new page to the document. The width and height are specified in points, which are 1/72 of an inch.

Tabela 1. Common Page Sizes in Points

name size
A0 2380✗3368
A1 1684✗2380
A2 1190✗1684
A3 842✗1190
A4 595✗842
A5 421✗595
A6 297✗421
B5 501✗709
letter (8.5"✗11") 612✗792
legal (8.5"✗14") 612✗1008
ledger (17"✗11") 1224✗792
11"✗17" 792✗1224

pdf_begin_pattern

(PHP 4 >= 4.0.5)

pdf_begin_pattern -- Starts new pattern

Description

int pdf_begin_pattern ( int pdf object, float width, float height, float xstep, float ystep, int painttype)

Starts a new pattern definition and returns a pattern handle. width, and height define the bounding box for the pattern. xstep and ystep give the repeated pattern offsets. painttype=1 means that the pattern has its own colour settings whereas a value of 2 indicates that the current colour is used when the pattern is applied.

pdf_begin_template

(PHP 4 >= 4.0.5)

pdf_begin_template -- Starts new template

Description

int pdf_begin_template ( int pdf object, float width, float height)

Start a new template definition.

pdf_circle

(PHP 3>= 3.0.6, PHP 4 )

pdf_circle -- Draws a circle

Description

void pdf_circle ( int pdf object, float x, float y, float r)

Draw a circle with center (x, y) and radius r.

pdf_clip

(PHP 3>= 3.0.6, PHP 4 )

pdf_clip -- Clips to current path

Description

void pdf_clip ( int pdf object)

Use the current path as clipping path.

pdf_close_image

(PHP 3>= 3.0.7, PHP 4 )

pdf_close_image -- Closes an image

Description

void pdf_close_image ( int pdf object, int image)

Close an image retrieved with one of the pdf_open_image*() functions.

pdf_close_pdi_page

(PHP 4 >= 4.0.5)

pdf_close_pdi_page --  Close the page handle

Description

void pdf_close_pdi_page ( int pdf object, int pagehandle)

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

pdf_close_pdi

(PHP 4 >= 4.0.5)

pdf_close_pdi --  Close the input PDF document

Description

void pdf_close_pdi ( int pdf object, int dochandle)

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

pdf_close

(PHP 3>= 3.0.6, PHP 4 )

pdf_close -- Closes a pdf object

Description

void pdf_close ( int pdf object)

Close the generated PDF file, and free all document-related resources.

pdf_closepath_fill_stroke

(PHP 3>= 3.0.6, PHP 4 )

pdf_closepath_fill_stroke -- Closes, fills and strokes current path

Description

void pdf_closepath_fill_stroke ( int pdf object)

Close the path, fill, and stroke it.

pdf_closepath_stroke

(PHP 3>= 3.0.6, PHP 4 )

pdf_closepath_stroke -- Closes path and draws line along path

Description

void pdf_closepath_stroke ( int pdf object)

Close the path, and stroke it.

pdf_closepath

(PHP 3>= 3.0.6, PHP 4 )

pdf_closepath -- Closes path

Description

void pdf_closepath ( int pdf object)

Close the current path.

pdf_concat

(PHP 4 >= 4.0.5)

pdf_concat -- Concatenate a matrix to the CTM

Description

void pdf_concat ( int pdf object, float a, float b, float c, float d, float e, float f)

Concatenate a matrix to the CTM.

pdf_continue_text

(PHP 3>= 3.0.6, PHP 4 )

pdf_continue_text -- Outputs text in next line

Description

void pdf_continue_text ( int pdf object, string text)

Print text at the next line. The spacing between lines is determined by the leading parameter.

pdf_curveto

(PHP 3>= 3.0.6, PHP 4 )

pdf_curveto -- Draws a curve

Description

void pdf_curveto ( int pdf object, float x1, float y1, float x2, float y2, float x3, float y3)

Draw a Bezier curve from the current point, using 3 more control points.

pdf_delete

(PHP 4 >= 4.0.5)

pdf_delete -- Deletes a PDF object

Description

void pdf_delete ( int pdf object)

Delete the PDF object, and free all internal resources.

pdf_end_page

(PHP 3>= 3.0.6, PHP 4 )

pdf_end_page -- Ends a page

Description

void pdf_end_page ( int pdf object)

Finish the page.

pdf_end_pattern

(PHP 4 >= 4.0.5)

pdf_end_pattern -- Finish pattern

Description

void pdf_end_pattern ( int pdf object)

Finish the pattern definition.

pdf_end_template

(PHP 4 >= 4.0.5)

pdf_end_template -- Finish template

Description

void pdf_end_template ( int pdf object)

Finish the template definition.

pdf_endpath

pdf_endpath -- Deprecated: Ends current path

Description

Deprecated, use one of the stroke, fill, or clip functions instead.

pdf_fill_stroke

(PHP 3>= 3.0.6, PHP 4 )

pdf_fill_stroke -- Fills and strokes current path

Description

void pdf_fill_stroke ( int pdf object)

Fill and stroke the path with the current fill and stroke color.

pdf_fill

(PHP 3>= 3.0.6, PHP 4 )

pdf_fill -- Fills current path

Description

void pdf_fill_stroke ( int pdf object)

Fill the interior of the path with the current fill color.

pdf_findfont

(PHP 4 >= 4.0.5)

pdf_findfont -- Prepare font for later use with pdf_setfont().

Description

int pdf_findfont ( int pdf object, string fontname, string encoding, int embed)

Prepare a font for later use with pdf_setfont(). The metrics will be loaded, and if embed is nonzero, the font file will be checked, but not yet used. encoding is one of "builtin", "macroman", "winansi", "host", or a user-defined encoding name, or the name of a CMap.

pdf_findfont() returns a font handle or FALSE on error.

Exemplo 1. pdf_findfont() example

<?php

$font = pdf_findfont($pdf, "Times New Roman", "winansi", 1);
if ($font) {
    pdf_setfont($pdf, $font, 10);
}

?>

pdf_get_buffer

(PHP 4 >= 4.0.5)

pdf_get_buffer -- Fetch the buffer containig the generated PDF data.

Description

string pdf_get_buffer ( int pdf object)

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

pdf_get_font

pdf_get_font -- Deprecated: font handling

Description

Deprecated.

See pdf_get_value().

pdf_get_fontname

pdf_get_fontname -- Deprecated: font handling

Description

Deprecated.

See pdf_get_parameter().

pdf_get_fontsize

pdf_get_fontsize -- Deprecated: font handling

Description

Deprecated.

See pdf_get_value().

pdf_get_image_height

(PHP 3>= 3.0.12, PHP 4 )

pdf_get_image_height -- Returns height of an image

Description

string pdf_get_image_height ( int pdf object, int image)

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

pdf_get_image_width

(PHP 3>= 3.0.12, PHP 4 )

pdf_get_image_width -- Returns width of an image

Description

string pdf_get_image_width ( int pdf object, int image)

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

pdf_get_majorversion

(PHP 4 >= 4.2.0)

pdf_get_majorversion --  Returns the major version number of the PDFlib

Description

int pdf_get_majorversion ( void)

Returns the major version number of the PDFlib.

pdf_get_minorversion

(PHP 4 >= 4.2.0)

pdf_get_minorversion --  Returns the minor version number of the PDFlib

Description

int pdf_get_majorversion ( void)

Returns the minor version number of the PDFlib.

pdf_get_parameter

(PHP 4 >= 4.0.1)

pdf_get_parameter -- Gets certain parameters

Description

string pdf_get_parameter ( int pdf object, string key [, float modifier])

Get the contents of some PDFlib parameter with string type.

pdf_get_pdi_parameter

(PHP 4 >= 4.0.5)

pdf_get_pdi_parameter -- Get some PDI string parameters

Description

string pdf_get_pdi_parameter ( int pdf object, string key, int doc, int page, int index)

Get the contents of some PDI document parameter with string type.

pdf_get_pdi_value

(PHP 4 >= 4.0.5)

pdf_get_pdi_value -- Gets some PDI numerical parameters

Description

string pdf_get_pdi_value ( int pdf object, string key, int doc, int page, int index)

Get the contents of some PDI document parameter with numerical type.

pdf_get_value

(PHP 4 >= 4.0.1)

pdf_get_value -- Gets certain numerical value

Description

float pdf_get_value ( int pdf object, string key [, float modifier])

Get the contents of some PDFlib parameter with float type.

pdf_initgraphics

(PHP 4 >= 4.0.5)

pdf_initgraphics -- Resets graphic state

Description

void pdf_initgraphics ( int pdf object)

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

pdf_lineto

(PHP 3>= 3.0.6, PHP 4 )

pdf_lineto -- Draws a line

Description

void pdf_lineto ( int pdf object, float x, float y)

Draw a line from the current point to (x, y).

pdf_makespotcolor

(PHP 4 >= 4.0.5)

pdf_makespotcolor -- Makes a spotcolor

Description

void pdf_makespotcolor ( int pdf object, string spotname)

Make a named spot color from the current color.

pdf_moveto

(PHP 3>= 3.0.6, PHP 4 )

pdf_moveto -- Sets current point

Description

void pdf_moveto ( int pdf object, float x, float y)

Set the current point.

Nota: The current point for graphics and the current text output position are maintained separately. See pdf_set_text_pos() to set the text output position.

pdf_new

(PHP 4 >= 4.0.5)

pdf_new -- Creates a new pdf object

Description

int pdf_new ( )

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

pdf_open_CCITT

(PHP 4 >= 4.0.5)

pdf_open_CCITT -- Opens a new image file with raw CCITT data

Description

int pdf_open_CCITT ( int pdf object, string filename, int width, int height, int BitReverse, int k, int Blackls1)

Open a raw CCITT image.

pdf_open_file

(PHP 4 >= 4.0.5)

pdf_open_file -- Opens a new pdf object

Description

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

Create a new PDF file using the supplied file name. If filename is empty the PDF document will be generated in memory instead of on file. The result must be fetched by the client with the pdf_get_buffer() function.

The following example shows how to create a pdf document in memory and how to output it correctly.

Exemplo 1. Creating a PDF document in memory

<?php

$pdf = pdf_new();

pdf_open_file($pdf);
pdf_begin_page($pdf, 595, 842);
pdf_set_font($pdf, "Times-Roman", 30, "host");
pdf_set_value($pdf, "textrendering", 1);
pdf_show_xy($pdf, "A PDF document created in memory!", 50, 750);
pdf_end_page($pdf);
pdf_close($pdf);

$data = pdf_get_buffer($pdf);

header("Content-type: application/pdf");
header("Content-disposition: inline; filename=test.pdf");
header("Content-length: " . strlen($data));

echo $data;

?>

pdf_open_gif

pdf_open_gif -- Deprecated: Opens a GIF image

Description

Deprecated.

See pdf_open_image(),

pdf_open_image_file

(PHP 3 CVS only, PHP 4 )

pdf_open_image_file -- Reads an image from a file

Description

int pdf_open_image_file ( int PDF-document, string imagetype, string filename [, string stringparam [, string intparam]])

Open an image file. Supported types are "jpeg", "tiff", "gif", and "png". stringparam is either "", "mask", "masked", or "page". intparamis either 0, the image id of the applied mask, or the page.

pdf_open_image

(PHP 4 >= 4.0.5)

pdf_open_image -- Versatile function for images

Description

int pdf_open_image ( int PDF-document, string imagetype, string source, string data, long length, int width, int height, int components, int bpc, string params)

Use image data from a variety of data sources. Supported types are "jpeg", "ccitt", "raw". Supported sources are "memory", "fileref", "url". len is only used for type="raw", params is only used for type="ccitt".

pdf_open_jpeg

pdf_open_jpeg -- Deprecated: Opens a JPEG image

Description

Deprecated.

See also pdf_open_image(),

pdf_open_memory_image

(PHP 3>= 3.0.10, PHP 4 )

pdf_open_memory_image -- Opens an image created with PHP's image functions

Description

int pdf_open_memory_image ( int pdf object, int image)

The pdf_open_memory_image() function takes an image created with the PHP's image functions and makes it available for the pdf object. The function returns a pdf image identifier.

Exemplo 1. Including a memory image

<?php
$im = ImageCreate(100, 100);
$col = ImageColorAllocate($im, 80, 45, 190);
ImageFill($im, 10, 10, $col);
$pim = pdf_open_memory_image($pdf, $im);
ImageDestroy($im);
pdf_place_image($pdf, $pim, 100, 100, 1);
pdf_close_image($pdf, $pim);
?>

See also pdf_close_image(), pdf_place_image().

pdf_open_pdi_page

(PHP 4 >= 4.0.5)

pdf_open_pdi_page --  Prepare a page

Description

int pdf_open_pdi_page ( int pdf object, int dochandle, int pagenumber, string pagelabel)

Prepare a page for later use with pdf_place_image()

pdf_open_pdi

(PHP 4 >= 4.0.5)

pdf_open_pdi --  Opens a PDF file

Description

int pdf_open_pdi ( int pdf object, string filename, string stringparam, int intparam)

Open an existing PDF document for later use.

pdf_open_png

pdf_open_png --  Deprecated: Opens a PNG image

Description

Deprecated.

See pdf_open_image().

pdf_open_tiff

(PHP 4 )

pdf_open_tiff -- Deprecated: Opens a TIFF image

Description

int pdf_open_tiff ( int PDF-document, string filename)

Deprecated.

See also pdf_open_image(),

pdf_open

pdf_open -- Deprecated: Open a new pdf object

Description

pdf_open() is deprecated, use pdf_new() plus pdf_open_file() instead.

See also pdf_new(), pdf_open_file().

pdf_place_image

(PHP 3>= 3.0.7, PHP 4 )

pdf_place_image -- Places an image on the page

Description

void pdf_place_image ( int pdf object, int image, float x, float y, float scale)

Place an image with the lower left corner at (x, y), and scale it.

pdf_place_pdi_page

(PHP 4 >= 4.0.6)

pdf_place_pdi_page -- Places an image on the page

Description

void pdf_place_pdi_page ( int pdf object, int page, float x, float y, float sx, float sy)

Place a PDF page with the lower left corner at (x, y), and scale it.

pdf_rect

(PHP 3>= 3.0.6, PHP 4 )

pdf_rect -- Draws a rectangle

Description

void pdf_rect ( int pdf object, float x, float y, float width, float height)

Draw a rectangle at lower left (x, y) with width and height.

pdf_restore

(PHP 3>= 3.0.6, PHP 4 )

pdf_restore -- Restores formerly saved environment

Description

void pdf_restore ( int pdf object)

Restore the most recently saved graphics state.

pdf_rotate

(PHP 3>= 3.0.6, PHP 4 )

pdf_rotate -- Sets rotation

Description

void pdf_rotate ( int pdf object, float phi)

Rotate the coordinate system by phi degrees.

pdf_save

(PHP 3>= 3.0.6, PHP 4 )

pdf_save -- Saves the current environment

Description

void pdf_save ( int pdf object)

Save the current graphics state.

pdf_scale

(PHP 3>= 3.0.6, PHP 4 )

pdf_scale -- Sets scaling

Description

void pdf_scale ( int pdf object, float x-scale, float y-scale)

Scale the coordinate system.

pdf_set_border_color

(PHP 3>= 3.0.12, PHP 4 )

pdf_set_border_color -- Sets color of border around links and annotations

Description

void pdf_set_border_color ( int pdf object, float red, float green, float blue)

Set the border color for all kinds of annotations.

pdf_set_border_dash

(PHP 4 >= 4.0.1)

pdf_set_border_dash -- Sets dash style of border around links and annotations

Description

void pdf_set_border_dash ( int pdf object, float black, float white)

Set the border dash style for all kinds of annotations. See pdf_setdash().

pdf_set_border_style

(PHP 3>= 3.0.12, PHP 4 )

pdf_set_border_style -- Sets style of border around links and annotations

Description

void pdf_set_border_style ( int pdf object, string style, float width)

Set the border style for all kinds of annotations. style is "solid" or "dashed".

pdf_set_char_spacing

pdf_set_char_spacing -- Deprecated: Sets character spacing

Description

Deprecated.

See also pdf_set_value(),

pdf_set_duration

pdf_set_duration -- Deprecated: Sets duration between pages

Description

Deprecated.

See pdf_set_value().

pdf_set_font

pdf_set_font -- Deprecated: Selects a font face and size

Description

Deprecated. You should use pdf_findfont() plus pdf_setfont() instead.

See pdf_findfont(), pdf_setfont().

pdf_set_horiz_scaling

(PHP 3>= 3.0.6, PHP 4 )

pdf_set_horiz_scaling -- Sets horizontal scaling of text

Description

void pdf_set_horiz_scaling ( int pdf object, float scale)

Deprecated.

See also pdf_set_value(),

pdf_set_info_author

(PHP 3>= 3.0.6, PHP 4 )

pdf_set_info_author --  Fills the author field of the document

Description

bool pdf_set_info_author ( int pdfdoc, string author)

This function is deprecate, use pdf_set_info() instead.

pdf_set_info_creator

(PHP 3>= 3.0.6, PHP 4 )

pdf_set_info_creator --  Fills the creator field of the document

Description

bool pdf_set_info_creator ( int pdfdoc, string creator)

This function is deprecate, use pdf_set_info() instead.

pdf_set_info_keywords

(PHP 3>= 3.0.6, PHP 4 )

pdf_set_info_keywords --  Fills the keywords field of the document

Description

bool pdf_set_info_keywords ( int pdfdoc, string keywords)

This function is deprecate, use pdf_set_info() instead.

pdf_set_info_subject

(PHP 3>= 3.0.6, PHP 4 )

pdf_set_info_subject --  Fills the subject field of the document

Description

bool pdf_set_info_subject ( int pdfdoc, string subject)

This function is deprecate, use pdf_set_info() instead.

pdf_set_info_title

(PHP 3>= 3.0.6, PHP 4 )

pdf_set_info_title --  Fills the title field of the document

Description

bool pdf_set_info_title ( int pdfdoc, string title)

This function is deprecate, use pdf_set_info() instead.

pdf_set_info

(PHP 4 >= 4.0.1)

pdf_set_info -- Fills a field of the document information

Description

void pdf_set_info ( int pdf object, string key, string value)

Fill document information field key with value. key is one of "Subject", "Title", "Creator", "Author", "Keywords", or a user-defined key.

pdf_set_leading

pdf_set_leading -- Deprecated: Sets distance between text lines

Description

Deprecated.

See also pdf_set_value(),

pdf_set_parameter

(PHP 4 )

pdf_set_parameter -- Sets certain parameters

Description

void pdf_set_parameter ( int pdf object, string key, string value)

Set some PDFlib parameter with string type.

pdf_set_text_matrix

pdf_set_text_matrix -- Deprecated: Sets the text matrix

Description

See pdf_set_paramter().

pdf_set_text_pos

(PHP 3>= 3.0.6, PHP 4 )

pdf_set_text_pos -- Sets text position

Description

void pdf_set_text_pos ( int pdf object, float x, float y)

Set the text output position.

pdf_set_text_rendering

pdf_set_text_rendering -- Deprecated: Determines how text is rendered

Description

Deprecated.

See pdf_set_value(),

pdf_set_text_rise

pdf_set_text_rise -- Deprecated: Sets the text rise

Description

Deprecated.

See pdf_set_value(),

pdf_set_value

(PHP 4 >= 4.0.1)

pdf_set_value -- Sets certain numerical value

Description

void pdf_set_value ( int pdf object, string key, float value)

Set the value of some PDFlib parameter with float type.

pdf_set_word_spacing

pdf_set_word_spacing -- Depriciated: Sets spacing between words

Description

Deprecated.

See also pdf_set_value(),

pdf_setcolor

(PHP 4 >= 4.0.5)

pdf_setcolor -- Sets fill and stroke color

Description

void pdf_setcolor ( int pdf object, string type, string colorspace, float c1 [, float c2 [, float c3 [, float c4]]])

Set the current color space and color. The parameter type can be "fill", "stroke", or "both" to specify that the color is set for filling, stroking or both filling and stroking. The parameter colorspace can be gray, rgb, cmyk, spot or pattern. The parameters c1, c2, c3 and c4 represent the color components for the color space specified by colorspace. Except as otherwise noted, the color components are floating-point values that range from 0 to 1.

For gray only c1 is used.

For rgb parameters c1, c2, and c3 specify the red, green and blue values respectively.

// Set fill and stroke colors to white.
pdf_setcolor($pdf, "both", "rgb", 1, 1, 1);

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

// Set fill and stroke colors to white.
pdf_setcolor($pdf, "both", "cmyk", 0, 0, 0, 1);

For spot, c1 should be a spot color handles returned by pdf_makespotcolor() and c2 is a tint value between 0 and 1.

For pattern, c1 should be a pattern handle returned by pdf_begin_pattern().

pdf_setdash

(PHP 3>= 3.0.6, PHP 4 )

pdf_setdash -- Sets dash pattern

Description

void pdf_setdash ( int pdf object, float b, float w)

Set the current dash pattern to b black and w white units.

pdf_setflat

(PHP 3>= 3.0.6, PHP 4 )

pdf_setflat -- Sets flatness

Description

void pdf_setflat ( int pdf object, float flatness)

Set the flatness to a value between 0 and 100 inclusive.

pdf_setfont

(PHP 4 >= 4.0.5)

pdf_setfont -- Set the current font

Description

void pdf_setfont ( int pdf object, int font, float size)

Set the current font in the given size, using a font handle returned by pdf_findfont()

See Also: pdf_findfont().

pdf_setgray_fill

(PHP 3>= 3.0.6, PHP 4 )

pdf_setgray_fill -- Sets filling color to gray value

Description

void pdf_setgray_fill ( int pdf object, float gray)

Set the current fill color to a gray value between 0 and 1 inclusive.

Nota: PDFlib V4.0: Deprecated, use pdf_setcolor() instead.

pdf_setgray_stroke

(PHP 3>= 3.0.6, PHP 4 )

pdf_setgray_stroke -- Sets drawing color to gray value

Description

void pdf_setgray_stroke ( int pdf object, float gray)

Set the current stroke color to a gray value between 0 and 1 inclusive

Nota: PDFlib V4.0: Deprecated, use pdf_setcolor() instead.

pdf_setgray

(PHP 3>= 3.0.6, PHP 4 )

pdf_setgray -- Sets drawing and filling color to gray value

Description

void pdf_setgray ( int pdf object, float gray)

Set the current fill and stroke color.

Nota: PDFlib V4.0: Deprecated, use pdf_setcolor() instead.

pdf_setlinecap

(PHP 3>= 3.0.6, PHP 4 )

pdf_setlinecap -- Sets linecap parameter

Description

void pdf_setlinecap ( int pdf object, int linecap)

Set the linecap parameter to a value between 0 and 2 inclusive.

pdf_setlinejoin

(PHP 3>= 3.0.6, PHP 4 )

pdf_setlinejoin -- Sets linejoin parameter

Description

void pdf_setlinejoin ( int pdf object, long linejoin)

Set the line join parameter to a value between 0 and 2 inclusive.

pdf_setlinewidth

(PHP 3>= 3.0.6, PHP 4 )

pdf_setlinewidth -- Sets line width

Description

void pdf_setlinewidth ( int pdf object, float width)

Set the current linewidth to width.

pdf_setmatrix

(PHP 4 >= 4.0.5)

pdf_setmatrix -- Sets current transformation matrix

Description

void pdf_setmatrix ( int pdf object, float a, float b, float c, float d, float e, float f)

Explicitly set the current transformation matrix.

pdf_setmiterlimit

(PHP 3>= 3.0.6, PHP 4 )

pdf_setmiterlimit -- Sets miter limit

Description

void pdf_setmiterlimit ( int pdf object, float miter)

Set the miter limit to a value greater than or equal to 1.

pdf_setpolydash

(PHP 4 >= 4.0.5)

pdf_setpolydash -- Sets complicated dash pattern

Description

void pdf_setpolydash ( int pdf object, float * dasharray)

Set a more complicated dash pattern defined by an array.

pdf_setrgbcolor_fill

(PHP 3>= 3.0.6, PHP 4 )

pdf_setrgbcolor_fill -- Sets filling color to rgb color value

Description

void pdf_setrgbcolor_fill ( int pdf object, float red value, float green value, float blue value)

Set the current fill color to the supplied RGB values.

Nota: PDFlib V4.0: Deprecated, use pdf_setcolor() instead.

pdf_setrgbcolor_stroke

(PHP 3>= 3.0.6, PHP 4 )

pdf_setrgbcolor_stroke -- Sets drawing color to rgb color value

Description

void pdf_setrgbcolor_stroke ( int pdf object, float red value, float green value, float blue value)

Set the current stroke color to the supplied RGB values.

Nota: PDFlib V4.0: Deprecated, use pdf_setcolor() instead.

pdf_setrgbcolor

(PHP 3>= 3.0.6, PHP 4 )

pdf_setrgbcolor -- Sets drawing and filling color to rgb color value

Description

void pdf_setrgbcolor ( int pdf object, float red value, float green value, float blue value)

Set the current fill and stroke color to the supplied RGB values.

Nota: PDFlib V4.0: Deprecated, use pdf_setcolor() instead.

pdf_show_boxed

(PHP 4 )

pdf_show_boxed -- Output text in a box

Description

int pdf_show_boxed ( int pdf object, string text, float left, float top, float width, float height, string hmode [, string feature])

Format text in the current font and size into the supplied text box according to the requested formatting mode, which must be one of "left", "right", "center", "justify", or "fulljustify". If width and height are 0, only a single line is placed at the point (left, top) in the requested mode.

Returns the number of characters that did not fit in the specified box. Returns 0 if all characters fit or the width and height parameters were set to 0 for single-line formattting.

pdf_show_xy

(PHP 3>= 3.0.6, PHP 4 )

pdf_show_xy -- Output text at given position

Description

void pdf_show_xy ( int pdf object, string text, float x, float y)

Print text in the current font at (x, y).

pdf_show

(PHP 3>= 3.0.6, PHP 4 )

pdf_show -- Output text at current position

Description

void pdf_show ( int pdf object, string text)

Print text in the current font and size at the current position.

pdf_skew

(PHP 4 )

pdf_skew -- Skews the coordinate system

Description

void pdf_skew ( int pdf object, float alpha, float beta)

Skew the coordinate system in x and y direction by alpha and beta degrees.

pdf_stringwidth

(PHP 3>= 3.0.6, PHP 4 )

pdf_stringwidth -- Returns width of text using current font

Description

float pdf_stringwidth ( int pdf object, string text [, int font [, float size]])

Returns the width of text using the last font set by pdf_setfont(). If the optional parameters font and size are specified, the width will be calculated using that font and size instead. Please note that font is a font handle returned by pdf_findfont().

Nota: Both the font and size parameters must used together.

See Also: pdf_setfont() and pdf_findfont().

pdf_stroke

(PHP 3>= 3.0.6, PHP 4 )

pdf_stroke -- Draws line along path

Description

void pdf_stroke ( int pdf object)

Stroke the path with the current color and line width, and clear it.

pdf_translate

(PHP 3>= 3.0.6, PHP 4 )

pdf_translate -- Sets origin of coordinate system

Description

void pdf_translate ( int pdf object, float tx, float ty)

Translate the origin of the coordinate system.

LXXVIII. Verisign Payflow Pro functions

Introdução

This extension allows you to process credit cards and other financial transactions using Verisign Payment Services, formerly known as Signio (http://www.verisign.com/products/payflow/pro/index.html).

When using these functions, you may omit calls to pfpro_init() and pfpro_cleanup() as this extension will do so automatically if required. However the functions are still available in case you are processing a number of transactions and require fine control over the library. You may perform any number of transactions using pfpro_process() between the two.

These functions were added in PHP 4.0.2.

Nota: These functions only provide a link to Verisign Payment Services. Be sure to read the Payflow Pro Developers Guide for full details of the required parameters.

Nota: This extension is not available on Windows platforms.


Requisitos

You will require the appropriate SDK for your platform, which may be downloaded from within the manager interface once you have registered. If you are going to use this extension in an SSL-enabled webserver or with other SSL components (such as the CURL+SSL extension) you MUST get the beta SDK.

Once you have downloaded the SDK you should copy the files from the lib directory of the distribution. Copy the header file pfpro.h to /usr/local/include and the library file libpfpro.so to /usr/local/lib.


Instalação

These functions are only available if PHP has been compiled with the --with-pfpro[=DIR] option.


Configuração durante execução

O comportamento dessas funções podem ser modificado pelas configurações do php.ini.

Tabela 1. Verisign Payflow Pro configuration options

Name Default Changeable
pfpro.defaulthost/PFPRO_VERSION < 3 "test.signio.com" PHP_INI_ALL
pfpro.defaulthost "test-payflow.verisign.com" PHP_INI_ALL
pfpro.defaultport "443" PHP_INI_ALL
pfpro.defaulttimeout "30" PHP_INI_ALL
pfpro.proxyaddress "" PHP_INI_ALL
pfpro.proxyport "" PHP_INI_ALL
pfpro.proxylogon "" PHP_INI_ALL
pfpro.proxypassword "" PHP_INI_ALL
For further details and definition of the PHP_INI_* constants see ini_set().


Tipos Resource

Esta extensão não possui nenhum tipo resource.


Constantes Predefinidas

Esta extensão não possui nenhuma constante.

Índice
pfpro_cleanup -- Shuts down the Payflow Pro library
pfpro_init -- Initialises the Payflow Pro library
pfpro_process_raw -- Process a raw transaction with Payflow Pro
pfpro_process -- Process a transaction with Payflow Pro
pfpro_version -- Returns the version of the Payflow Pro software

pfpro_cleanup

(PHP 4 >= 4.0.2)

pfpro_cleanup -- Shuts down the Payflow Pro library

Description

void pfpro_cleanup ( void)

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

See also pfpro_init().

pfpro_init

(PHP 4 >= 4.0.2)

pfpro_init -- Initialises the Payflow Pro library

Description

void pfpro_init ( void)

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

See also pfpro_cleanup().

pfpro_process_raw

(PHP 4 >= 4.0.2)

pfpro_process_raw -- Process a raw transaction with Payflow Pro

Description

string pfpro_process_raw ( string parameters [, string address [, int port [, int timeout [, string proxy address [, int proxy port [, string proxy logon [, string proxy password]]]]]]])

Returns: A string containing the response.

pfpro_process_raw() processes a raw transaction string with Payflow Pro. You should really use pfpro_process() instead, as the encoding rules of these transactions are non-standard.

The first parameter in this case is a string containing the raw transaction request. All other parameters are the same as with pfpro_process(). The return value is a string containing the raw response.

Nota: Be sure to read the Payflow Pro Developers Guide for full details of the required parameters and encoding rules. You would be well advised to use pfpro_process() instead.

Exemplo 1. Payflow Pro raw example

<?php

pfpro_init();

$response = pfpro_process_raw("USER=mylogin&PWD[5]=m&ndy&PARTNER=VeriSign&TRXTYPE=S&TENDER=C&AMT=1.50&ACCT=4111111111111111&EXPDATE=0904");

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

echo "Verisign raw response was ".$response;

pfpro_cleanup();

?>

pfpro_process

(PHP 4 >= 4.0.2)

pfpro_process -- Process a transaction with Payflow Pro

Description

array pfpro_process ( array parameters [, string address [, int port [, int timeout [, string proxy address [, int proxy port [, string proxy logon [, string proxy password]]]]]]])

Returns: An associative array containing the response

pfpro_process() processes a transaction with Payflow Pro. The first parameter is an associative array containing keys and values that will be encoded and passed to the processor.

The second parameter is optional and specifies the host to connect to. By default this is "test.signio.com", so you will certainly want to change this to "connect.signio.com" in order to process live transactions.

The third parameter specifies the port to connect on. It defaults to 443, the standard SSL port.

The fourth parameter specifies the timeout to be used, in seconds. This defaults to 30 seconds. Note that this timeout appears to only begin once a link to the processor has been established and so your script could potentially continue for a very long time in the event of DNS or network problems.

The fifth parameter, if required, specifies the hostname of your SSL proxy. The sixth parameter specifies the port to use.

The seventh and eighth parameters specify the logon identity and password to use on the proxy.

The function returns an associative array of the keys and values in the response.

Nota: Be sure to read the Payflow Pro Developers Guide for full details of the required parameters.

Exemplo 1. Payflow Pro example

<?php

pfpro_init();

$transaction = array('USER'    => 'mylogin',
                     'PWD'     => 'mypassword',
                     'PARTNER' => 'VeriSign',
                     'TRXTYPE' => 'S',
                     'TENDER'  => 'C',
                     'AMT'     => 1.50,
                     'ACCT'    => '4111111111111111',
                     'EXPDATE' => '0904'
                    );

$response = pfpro_process($transaction);

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

echo "Verisign response code was ".$response['RESULT'];
echo ", which means: ".$response['RESPMSG']."\n";

echo "\nThe transaction request: ";
print_r($transaction);

echo "\nThe response: ";
print_r($response);

pfpro_cleanup();

?>

pfpro_version

(PHP 4 >= 4.0.2)

pfpro_version -- Returns the version of the Payflow Pro software

Description

string pfpro_version ( void)

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

LXXIX. PHP Options&Information

Introdução

This functions enable you to get a lot of information about PHP itself, e.g. runtime configuration, loaded extensions, version and much more. You'll also find functions to set options for your running PHP. The probably best known function of PHP - phpinfo() - can be found here.


Requisitos

Nenhuma biblioteca externa é necessária para compilar esta extensão.


Instalação

Não há nenhuma instalação nescessária para utilizar estas funções, elas fazem parte do núcleo do PHP.


Configuração durante execução

O comportamento dessas funções podem ser modificado pelas configurações do php.ini.

Tabela 1. PHP Options/Inf Configuration Options

Name Default Changeable
assert.active "1" PHP_INI_ALL
assert.bail "0" PHP_INI_ALL
assert.warning "1" PHP_INI_ALL
assert.callback NULL PHP_INI_ALL
assert.quiet_eval "0" PHP_INI_ALL
enable_dl "1" PHP_INI_SYSTEM
max_execution_time "30" PHP_INI_ALL
magic_quotes_gpc "1" PHP_INI_PERDIR|PHP_INI_SYSTEM
magic_quotes_runtime "0" PHP_INI_ALL
For further details and definition of the PHP_INI_* constants see ini_set().

Here is a short explanation of the configuration directives.

assert.active boolean

Enable assert() evaluation.

assert.bail boolean

Terminate script execution on failed assertions.

assert.warning boolean

Issue a PHP warning for each failed assertion.

assert.callback string

user function to call on failed assertions

assert.quiet_eval boolean

Use the current setting of error_reporting() during assertion expression evaluation. If enabled, no errors are shown (implicit error_reporting(0)) while evaluation. If disabled, errors are shown according to the settings of error_reporting()

enable_dl boolean

This directive is really only useful in the Apache module version of PHP. You can turn dynamic loading of PHP extensions with dl() on and off per virtual server or per directory.

The main reason for turning dynamic loading off is security. With dynamic loading, it's possible to ignore all open_basedir restrictions. The default is to allow dynamic loading, except when using safe_mode. In safe-mode, it's always imposible to use dl().

max_execution_time integer

This sets the maximum time in seconds a script is allowed to run before it is terminated by the parser. This helps prevent poorly written scripts from tying up the server. The default setting is 30.

The maximum execution time is not affected by system calls, the sleep() function, etc. Please see the set_time_limit() function for more details.

magic_quotes_gpc boolean

Sets the magic_quotes state for GPC (Get/Post/Cookie) operations. When magic_quotes are on, all ' (single-quote), " (double quote), \ (backslash) and NUL's are escaped with a backslash automatically.

Nota: If the magic_quotes_sybase directive is also ON it will completely override magic_quotes_gpc. Having both directives enabled means only single quotes are escaped as ''. Double quotes, backslashes and NUL's will remain untouched and unescaped.

See also get_magic_quotes_gpc()

magic_quotes_runtime boolean

If magic_quotes_runtime is enabled, most functions that return data from any sort of external source including databases and text files will have quotes escaped with a backslash. If magic_quotes_sybase is also on, a single-quote is escaped with a single-quote instead of a backslash.


Tipos Resource

Esta extensão não possui nenhum tipo resource.


Constantes Predefinidas

As constantes listadas abaixo estão sempre disponíveis como parte do núcleo do PHP.

Tabela 2. Pre-defined phpcredits() constants

Constant Description
CREDITS_ALL All the credits, equivalent to using: CREDITS_DOCS + CREDITS_GENERAL + CREDITS_GROUP + CREDITS_MODULES + CREDITS_FULLPAGE. It generates a complete stand-alone HTML page with the appropriate tags.
CREDITS_DOCS The credits for the documentation team
CREDITS_FULLPAGE Usually used in combination with the other flags. Indicates that the a complete stand-alone HTML page needs to be printed including the information indicated by the other flags.
CREDITS_GENERAL General credits: Language design and concept, PHP 4.0 authors and SAPI module.
CREDITS_GROUP A list of the core developers
CREDITS_MODULES A list of the extension modules for PHP, and their authors
CREDITS_SAPI A list of the server API modules for PHP, and their authors

Tabela 3. phpinfo() constants

Constant Value Description
INFO_GENERAL 1 The configuration line, php.ini location, build date, Web Server, System and more.
INFO_CREDITS 2 PHP 4 Credits. See also phpcredits().
INFO_CONFIGURATION 4 Current Local and Master values for php directives. See also ini_get().
INFO_MODULES 8 Loaded modules and their respective settings.
INFO_ENVIRONMENT 16 Environment Variable information that's also available in $_ENV.
INFO_VARIABLES 32 Shows all predefined variables from EGPCS (Environment, GET, POST, Cookie, Server).
INFO_LICENSE 64 PHP License information. See also the license faq.
INFO_ALL -1 Shows all of the above. This is the default value.

ASSERT_ACTIVE (integer)

ASSERT_CALLBACK (integer)

ASSERT_BAIL (integer)

ASSERT_WARNING (integer)

ASSERT_QUIET_EVAL (integer)

Índice
assert_options -- Set/get the various assert flags
assert -- Checks if assertion is FALSE
dl -- Loads a PHP extension at runtime
extension_loaded -- Find out whether an extension is loaded
get_cfg_var --  Gets the value of a PHP configuration option
get_current_user --  Gets the name of the owner of the current PHP script
get_defined_constants --  Returns an associative array with the names of all the constants and their values
get_extension_funcs --  Returns an array with the names of the functions of a module
get_included_files --  Returns an array with the names of included or required files
get_loaded_extensions --  Returns an array with the names of all modules compiled and loaded
get_magic_quotes_gpc --  Gets the current active configuration setting of magic quotes gpc
get_magic_quotes_runtime --  Gets the current active configuration setting of magic_quotes_runtime
get_required_files --  Returns an array with the names of included or required files
getenv -- Gets the value of an environment variable
getlastmod -- Gets time of last page modification
getmygid -- Get PHP script owner's GID
getmyinode -- Gets the inode of the current script
getmypid -- Gets PHP's process ID
getmyuid -- Gets PHP script owner's UID
getopt -- Gets options from the command line argument list
getrusage -- Gets the current resource usages
ini_alter --  Changes the value of a configuration option
ini_get_all -- Gets all configuration options
ini_get -- Gets the value of a configuration option
ini_restore -- Restores the value of a configuration option
ini_set -- Sets the value of a configuration option
php_ini_scanned_files -- Return a list of .ini files parsed from the additional ini dir
php_logo_guid -- Gets the logo guid
php_sapi_name --  Returns the type of interface between web server and PHP
php_uname --  Returns information about the operating system PHP was built on
phpcredits -- Prints out the credits for PHP
phpinfo -- Outputs lots of PHP information
phpversion -- Gets the current PHP version
putenv -- Sets the value of an environment variable
set_magic_quotes_runtime --  Sets the current active configuration setting of magic_quotes_runtime
set_time_limit -- Limits the maximum execution time
version_compare --  Compares two "PHP-standardized" version number strings
zend_logo_guid -- Gets the zend guid
zend_version -- Gets the version of the current Zend engine

assert_options

(PHP 4 )

assert_options -- Set/get the various assert flags

Description

mixed assert_options ( int what [, mixed value])

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

Tabela 1. Assert Options

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

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

assert

(PHP 4 )

assert -- Checks if assertion is FALSE

Description

int assert ( string|bool assertion)

assert() will check the given assertion and take appropriate action if its result is FALSE.

If the assertion is given as a string it will be evaluated as PHP code by assert(). The advantages of a string assertion are less overhead when assertion checking is off and messages containing the assertion expression when an assertion fails. This means that if you pass a boolean condition as assertion this condition will not show up as parameter to the assertion function which you may have defined with the assert_options() function, the condition is converted to a string before calling that handler function, and the boolean FALSE is converted as the empty string.

Assertions should be used as a debugging feature only. You may use them for sanity-checks that test for conditions that should always be TRUE and that indicate some programming errors if not or to check for the presence of certain features like extension functions or certain system limits and features.

Assertions should not be used for normal runtime operations like input parameter checks. As a rule of thumb your code should always be able to work correctly if assertion checking is not activated.

The behavior of assert() may be configured by assert_options() or by .ini-settings described in that functions manual page.

The assert_options() function and/or ASSERT_CALLBACK configuration directive allow a callback function to be set to handle failed assertions.

assert() callbacks are particularly useful for building automated test suites because they allow you to easily capture the code passed to the assertion, along with information on where the assertion was made. While this information can be captured via other methods, using assertions makes it much faster and easier!

The callback function should accept three arguments. The first argument will contain the file the assertion failed in. The second argument will contain the line the assertion failed on and the third argument will contain the expression that failed (if any - literal values such as 1 or "two" will not be passed via this argument)

Exemplo 1. Handle a failed assertion with a custom handler

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

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

// Set up the callback
assert_options (ASSERT_CALLBACK, 'my_assert_handler');

// Make an assertion that should fail
assert ('mysql_query ("")');
?>

dl

(PHP 3, PHP 4 )

dl -- Loads a PHP extension at runtime

Description

bool dl ( string library)

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

Retorna TRUE em caso de sucesso ou FALSE em falhas. If the functionality of loading modules is not available (see Note) or has been disabled (either by turning it off enable_dl or by enabling safe_mode in php.ini) an E_ERROR is emitted and execution is stopped. If dl() fails because the specified library couldn't be loaded, in addition to FALSE an E_WARNING message is emitted.

Use extension_loaded() to test whether a given extension is already available or not. This works on both built-in extensions and dynamically loaded ones (either through php.ini or dl()).

Example:
if (!extension_loaded('gd')) {
    if (!dl('gd.so')) {
        exit;
    }
}

The directory where the extension is loaded from depends on your platform:

Windows - If not explicitly set in the php.ini, the extension is loaded from c:\php4\extensions\ by default.

Unix - If not explicitly set in the php.ini, the default extension directory depends on

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

  • whether PHP has been built with (experimental) ZTS (Zend Thread Safety) support or not

  • the current internal ZEND_MODULE_API_NO (Zend internal module API number, which is basically the date on which a major module API change happened, e.g. 20010901)

Taking into account the above, the directory then defaults to <php-install-directory>/lib/php/extension/<debug-or-not>-<zts-or-not>-ZEND_MODULE_API_NO, e.g. /usr/local/php/lib/php/extensions/debug-non-zts-20010901 or /usr/local/php/lib/php/extensions/no-debug-zts-20010901.

Nota: dl() is not supported in multithreaded Web servers. Use the extensions statement in your php.ini when operating under such an environment. However, the CGI and CLI build are not affected !

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

See also Extension Loading Directives and extension_loaded().

extension_loaded

(PHP 3>= 3.0.10, PHP 4 )

extension_loaded -- Find out whether an extension is loaded

Description

bool extension_loaded ( string name)

Returns TRUE if the extension identified by name is loaded, FALSE otherwise.

Example:
if (!extension_loaded('gd')) {
    if (!dl('gd.so')) {
        exit;
    }
}

You can see the names of various extensions by using phpinfo() or if you're usnig the CGI or CLI version of PHP you can use the -m switch to list all available extensions:
$ php -m
[PHP Modules]
xml
tokenizer
standard
sockets
session
posix
pcre
overload
mysql
mbstring
ctype

[Zend Modules]

Nota: extension_loaded() uses the internal extension name to test whether a certain extension is available or not. Most internal extension names are written in lower case but there may be extension available which also use uppercase letters. Be warned that this function compares case sensitive !

See also get_loaded_extensions(), get_extension_funcs(), phpinfo() and dl().

get_cfg_var

(PHP 3, PHP 4 )

get_cfg_var --  Gets the value of a PHP configuration option

Description

string get_cfg_var ( string varname)

Returns the current value of the PHP configuration variable specified by varname, or FALSE if an error occurs.

It will not return configuration information set when the PHP was compiled, or read from an Apache configuration file (using the php3_configuration_option directives).

To check whether the system is using a configuration file, try retrieving the value of the cfg_file_path configuration setting. If this is available, a configuration file is being used.

See also ini_get().

get_current_user

(PHP 3, PHP 4 )

get_current_user --  Gets the name of the owner of the current PHP script

Description

string get_current_user ( void)

Returns the name of the owner of the current PHP script.

See also getmyuid(), getmygid(), getmypid(), getmyinode(), and getlastmod().

get_defined_constants

(PHP 4 >= 4.1.0)

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

Description

array get_defined_constants ( void)

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

For example the line below

print_r (get_defined_constants());

will print a list like:

Array
(
    [E_ERROR] => 1
    [E_WARNING] => 2
    [E_PARSE] => 4
    [E_NOTICE] => 8
    [E_CORE_ERROR] => 16
    [E_CORE_WARNING] => 32
    [E_COMPILE_ERROR] => 64
    [E_COMPILE_WARNING] => 128
    [E_USER_ERROR] => 256
    [E_USER_WARNING] => 512
    [E_USER_NOTICE] => 1024
    [E_ALL] => 2047
    [TRUE] => 1
)

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

get_extension_funcs

(PHP 4 )

get_extension_funcs --  Returns an array with the names of the functions of a module

Description

array get_extension_funcs ( string module_name)

This function returns the names of all the functions defined in the module indicated by module_name.

For example the lines below

print_r (get_extension_funcs ("xml"));
print_r (get_extension_funcs ("gd"));

will print a list of the functions in the modules xml and gd respectively.

See also: get_loaded_extensions()

get_included_files

(PHP 4 )

get_included_files --  Returns an array with the names of included or required files

Description

array get_included_files ( void)

Returns an array of the names of all files that have been included using include(), include_once(), require() or require_once().

Files that are included or required multiple times only show up once in the returned array.

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

Exemplo 1. get_included_files() Example

<?php

include("test1.php");
include_once("test2.php");
require("test3.php");
require_once("test4.php");

$included_files = get_included_files();

foreach($included_files as $filename) {
    echo "$filename\n";
}

?>
will generate the following output:

test1.php
test2.php
test3.php
test4.php

Nota: In PHP 4.0.1pl2 and previous versions get_included_files() assumed that the required files ended in the extension .php; other extensions would not be returned. The array returned by get_included_files() was an associative array and only listed files included by include() and include_once().

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

get_loaded_extensions

(PHP 4 )

get_loaded_extensions --  Returns an array with the names of all modules compiled and loaded

Description

array get_loaded_extensions ( void)

This function returns the names of all the modules compiled and loaded in the PHP interpreter.

For example the line below

<?php
print_r (get_loaded_extensions());
?>

will print a list like:

Array
(
   [0] => xml
   [1] => wddx
   [2] => standard
   [3] => session
   [4] => posix
   [5] => pgsql
   [6] => pcre
   [7] => gd
   [8] => ftp
   [9] => db
   [10] => calendar
   [11] => bcmath
)

See also get_extension_funcs(), extension_loaded(), dl() and phpinfo().

get_magic_quotes_gpc

(PHP 3>= 3.0.6, PHP 4 )

get_magic_quotes_gpc --  Gets the current active configuration setting of magic quotes gpc

Description

int get_magic_quotes_gpc ( void)

Returns the current active configuration setting of magic_quotes_gpc (0 for off, 1 for on).

Nota: If the directive magic_quotes_sybase is ON it will completely override magic_quotes_gpc. So even when get_magic_quotes() returns TRUE neither double quotes, backslashes or NUL's will be escaped. Only single quotes will be escaped. In this case they'll look like: ''

Keep in mind that magic_quotes_gpc can not be set at runtime.

See also addslashes(), stripslashes(), get_magic_quotes_runtime(), and ini_get().

get_magic_quotes_runtime

(PHP 3>= 3.0.6, PHP 4 )

get_magic_quotes_runtime --  Gets the current active configuration setting of magic_quotes_runtime

Description

long get_magic_quotes_runtime ( void)

Returns the current active configuration setting of magic_quotes_runtime (0 for off, 1 for on).

See also get_magic_quotes_gpc() and set_magic_quotes_runtime().

get_required_files

(PHP 4 )

get_required_files --  Returns an array with the names of included or required files

Description

array get_required_files ( void)

As of PHP 4.0.4, this function is an alias for get_included_files()

In PHP 4.0.1pl2 and previous versions get_required_files() assumed that the required files ended in the extension .php, other extensions would not be returned. The array returned by get_required_files() was an associative array and only listed files included by require() and require_once().

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

getenv

(PHP 3, PHP 4 )

getenv -- Gets the value of an environment variable

Description

string getenv ( string varname)

Returns the value of the environment variable varname, or FALSE on an error.

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

You can see a list of all the environmental variables by using phpinfo(). You can find out what many of them mean by taking a look at the CGI specification, specifically the page on environmental variables.

Nota: This function does not work in ISAPI mode.

See also putenv().

getlastmod

(PHP 3, PHP 4 )

getlastmod -- Gets time of last page modification

Description

int getlastmod ( void)

Returns the time of the last modification of the current page. The value returned is a Unix timestamp, suitable for feeding to date(). Returns FALSE on error.

Exemplo 1. getlastmod() example

<?php
// outputs e.g. 'Last modified: March 04 1998 20:43:59.'
echo "Last modified: " . date ("F d Y H:i:s.", getlastmod());
?>

Nota: If you're interested in getting the last modification time of a different file, consider using filemtime().

See also date(), getmyuid(), getmygid(), get_current_user(), getmyinode(), getmypid(), and filemtime().

getmygid

(PHP 4 >= 4.1.0)

getmygid -- Get PHP script owner's GID

Description

int getmygid ( void)

Returns the group ID of the current script, or FALSE on error.

See also getmyuid(), getmypid(), get_current_user(), getmyinode(), and getlastmod().

getmyinode

(PHP 3, PHP 4 )

getmyinode -- Gets the inode of the current script

Description

int getmyinode ( void)

Returns the current script's inode, or FALSE on error.

See also getmygid(), getmyuid(), get_current_user(), getmypid(), and getlastmod().

Nota: esta função não é implementada na plataforma Windows

getmypid

(PHP 3, PHP 4 )

getmypid -- Gets PHP's process ID

Description

int getmypid ( void)

Returns the current PHP process ID, or FALSE on error.

Atenção

Process IDs are not unique, thus they are a weak entropy source. We recommend against relying on pids in security-dependent contexts.

See also getmygid(), getmyuid(), get_current_user(), getmyinode(), and getlastmod().

getmyuid

(PHP 3, PHP 4 )

getmyuid -- Gets PHP script owner's UID

Description

int getmyuid ( void)

Returns the user ID of the current script, or FALSE on error.

See also getmygid(), getmypid(), get_current_user(), getmyinode(), and getlastmod().

getopt

(PHP 4 >= 4.3.0)

getopt -- Gets options from the command line argument list

Description

string getopt ( string options)

Returns an associative array of option / argument pairs based on the options format specified in options, or FALSE on an error.

$options = getopt("f:hp:"); // parse the command line ($_GLOBALS['argv'])

The options parameter may contain the following elements: individual characters, and characters followed by a colon to indicate an option argument is to follow. For example, an option string x recognizes an option -x, and an option string x: recognizes an option and argument -x argument. It does not matter if an argument has leading white space.

This function will return an array of option / argument pairs. If an option does not have an argument, the value will be set to FALSE.

Nota: This function is currently not available on Windows

getrusage

(PHP 3>= 3.0.7, PHP 4 )

getrusage -- Gets the current resource usages

Description

array getrusage ( [int who])

This is an interface to getrusage(2). It returns an associative array containing the data returned from the system call. If who is 1, getrusage will be called with RUSAGE_CHILDREN.

All entries are accessible by using their documented field names.

Exemplo 1. Getrusage Example

$dat = getrusage();
echo $dat["ru_nswap"];         # number of swaps
echo $dat["ru_majflt"];        # number of page faults
echo $dat["ru_utime.tv_sec"];  # user time used (seconds)
echo $dat["ru_utime.tv_usec"]; # user time used (microseconds)
See your system's man page on getrusage(2) for more details.

ini_alter

(PHP 4 )

ini_alter --  Changes the value of a configuration option

Description

string ini_alter ( string varname, string newvalue)

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

Nota: This is an alias of ini_set()

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

ini_get_all

(PHP 4 >= 4.2.0)

ini_get_all -- Gets all configuration options

Description

array ini_get_all ( [string extension])

Returns all the registered configuration options as an associative array. If optional extension parameter is set, returns only options specific for that extension.

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

ini_get

(PHP 4 )

ini_get -- Gets the value of a configuration option

Description

string ini_get ( string varname)

Returns the value of the configuration option on success. Failure, such as querying for a non-existant value, will return an empty string.

When querying boolean values: A boolean ini value of off will be returned as an empty string while a boolean ini value of on will be returned as "1".

When querying memory size values: Many ini memory size values, such as upload_max_filesize are stored in the .ini file in shorthand notation. ini_get() will return the exact string stored in the php.ini file, NOT its integer equivalent. Attempting normal arithmetic functions on these values will not have otherwise expected results.

<?php
/*
Our php.ini contains the following settings:

display_errors = On
register_globals = Off
post_max_size = 8M
*/

print 'display_errors = ' . ini_get('display_errors') . "\n";
print 'register_globals = ' . ini_get('register_globals') . "\n";
print 'post_max_size = ' . ini_get('post_max_size') . "\n";
print 'post_max_size+1 = ' . (ini_get('post_max_size')+1) . "\n"; 

/*
This script will produce:

display_errors = 1
register_globals = 
post_max_size = 8M
post_max_size+1 = 9
*/
?>

See also get_cfg_var(), ini_get_all(), ini_alter(), ini_restore(), and ini_set()

ini_restore

(PHP 4 )

ini_restore -- Restores the value of a configuration option

Description

string ini_restore ( string varname)

Restores a given configuration option to its original value.

See also: ini_alter(), ini_get(), ini_get_all(), and ini_set()

ini_set

(PHP 4 )

ini_set -- Sets the value of a configuration option

Description

string ini_set ( string varname, string newvalue)

Sets the value of the given configuration option. Returns the old value on success, FALSE on failure. The configuration option will keep this new value during the script's execution, and will be restored at the script's ending.

Not all the available options can be changed using ini_set(). Below is a table with a list of all PHP options (as of PHP 4.2.0), indicating which ones can be changed/set and at what level.

Tabela 1. Configuration options

Name Default Changeable
com.allow_dcom "0" PHP_INI_SYSTEM
com.autoregister_typelib "0" PHP_INI_SYSTEM
com.autoregister_verbose "0" PHP_INI_SYSTEM
com.autoregister_casesensitive "1" PHP_INI_SYSTEM
com.typelib_file "" PHP_INI_SYSTEM
crack.default_dictionary NULL PHP_INI_SYSTEM
exif.encode_unicode "ISO-8859-15" PHP_INI_ALL
exif.decode_unicode_motorola "UCS-2BE" PHP_INI_ALL
exif.decode_unicode_intel "UCS-2LE" PHP_INI_ALL
exif.encode_jis "" PHP_INI_ALL
exif.decode_jis_motorola "JIS" PHP_INI_ALL
exif.decode_jis_intel "JIS" PHP_INI_ALL
fbsql.allow_persistent "1" PHP_INI_SYSTEM
fbsql.generate_warnings "0" PHP_INI_SYSTEM
fbsql.autocommit "1" PHP_INI_SYSTEM
fbsql.max_persistent "-1" PHP_INI_SYSTEM
fbsql.max_links "128" PHP_INI_SYSTEM
fbsql.max_connections "128" PHP_INI_SYSTEM
fbsql.max_results "128" PHP_INI_SYSTEM
fbsql.batchSize "1000" PHP_INI_SYSTEM
fbsql.default_host NULL PHP_INI_SYSTEM
fbsql.default_user "_SYSTEM" PHP_INI_SYSTEM
fbsql.default_password "" PHP_INI_SYSTEM
fbsql.default_database "" PHP_INI_SYSTEM
fbsql.default_database_password "" PHP_INI_SYSTEM
hwapi.allow_persistent "0" PHP_INI_SYSTEM
hyerwave.allow_persistent "0" PHP_INI_SYSTEM
hyperwave.default_port "418" PHP_INI_ALL
iconv.input_encoding ICONV_INPUT_ENCODING PHP_INI_ALL
iconv.output_encoding ICONV_OUTPUT_ENCODING PHP_INI_ALL
iconv.internal_encoding ICONV_INTERNAL_ENCODING PHP_INI_ALL
ifx.allow_persistent "1" PHP_INI_SYSTEM
ifx.max_persistent "-1" PHP_INI_SYSTEM
ifx.max_links "-1" PHP_INI_SYSTEM
ifx.default_host NULL PHP_INI_SYSTEM
ifx.default_user NULL PHP_INI_SYSTEM
ifx.default_password NULL PHP_INI_SYSTEM
ifx.blobinfile "1" PHP_INI_ALL
ifx.textasvarchar "0" PHP_INI_ALL
ifx.byteasvarchar "0" PHP_INI_ALL
ifx.charasvarchar "0" PHP_INI_ALL
ifx.nullformat "0" PHP_INI_ALL
ingres.allow_persistent "1" PHP_INI_SYSTEM
ingres.max_persistent "-1" PHP_INI_SYSTEM
ingres.max_links "-1" PHP_INI_SYSTEM
ingres.default_database NULL PHP_INI_ALL
ingres.default_user NULL PHP_INI_ALL
ingres.default_password NULL PHP_INI_ALL
ibase.allow_persistent "1" PHP_INI_SYSTEM
ibase.max_persistent "-1" PHP_INI_SYSTEM
ibase.max_links "-1" PHP_INI_SYSTEM
ibase.default_user NULL PHP_INI_ALL
ibase.default_password NULL PHP_INI_ALL
ibase.timestampformat "%m/%d/%Y%H:%M:%S" PHP_INI_ALL
ibase.dateformat "%m/%d/%Y" PHP_INI_ALL
ibase.timeformat "%H:%M:%S" PHP_INI_ALL
java.class.path NULL PHP_INI_ALL
java.home NULL PHP_INI_ALL
java.library.path NULL PHP_INI_ALL
java.library JAVALIB PHP_INI_ALL
java.library NULL PHP_INI_ALL
ldap.max_links "-1" PHP_INI_SYSTEM
mbstring.detect_order NULL PHP_INI_ALL
mbstring.http_input NULL PHP_INI_ALL
mbstring.http_output NULL PHP_INI_ALL
mbstring.internal_encoding NULL PHP_INI_ALL
mbstring.substitute_character NULL PHP_INI_ALL
mbstring.func_overload "0" PHP_INI_SYSTEM
mcrypt.algorithms_dir NULL PHP_INI_ALL
mcrypt.modes_dir NULL PHP_INI_ALL
mime_magic.magicfile "/usr/share/misc/magic.mime" PHP_INI_SYSTEM
mssql.allow_persistent "1" PHP_INI_SYSTEM
mssql.max_persistent "-1" PHP_INI_SYSTEM
mssql.max_links "-1" PHP_INI_SYSTEM
mssql.max_procs "25" PHP_INI_ALL
mssql.min_error_severity "10" PHP_INI_ALL
mssql.min_message_severity "10" PHP_INI_ALL
mssql.compatability_mode "0" PHP_INI_ALL
mssql.connect_timeout "5" PHP_INI_ALL
mssql.timeout "60" PHP_INI_ALL
mssql.textsize "-1" PHP_INI_ALL
mssql.textlimit "-1" PHP_INI_ALL
mssql.batchsize "0" PHP_INI_ALL
mssql.datetimeconvert "1" PHP_INI_ALL
mysql.allow_persistent "1" PHP_INI_SYSTEM
mysql.max_persistent "-1" PHP_INI_SYSTEM
mysql.max_links "-1" PHP_INI_SYSTEM
mysql.default_host NULL PHP_INI_ALL
mysql.default_user NULL PHP_INI_ALL
mysql.default_password NULL PHP_INI_ALL
mysql.default_port NULL PHP_INI_ALL
mysql.default_socket NULL PHP_INI_ALL
ncurses.value "42" PHP_INI_ALL
ncurses.string "foobar" PHP_INI_ALL
odbc.allow_persistent "1" PHP_INI_SYSTEM
odbc.max_persistent "-1" PHP_INI_SYSTEM
odbc.max_links "-1" PHP_INI_SYSTEM
odbc.default_db NULL PHP_INI_ALL
odbc.default_user NULL PHP_INI_ALL
odbc.default_pw NULL PHP_INI_ALL
odbc.defaultlrl "4096" PHP_INI_ALL
odbc.defaultbinmode "1" PHP_INI_ALL
odbc.check_persistent "1" PHP_INI_SYSTEM
pfpro.defaulthost "test.signio.com"  
pfpro.defaulthost "test-payflow.verisign.com"  
pfpro.defaultport "443" PHP_INI_ALL
pfpro.defaulttimeout "30" PHP_INI_ALL
pfpro.proxyaddress "" PHP_INI_ALL
pfpro.proxyport "" PHP_INI_ALL
pfpro.proxylogon "" PHP_INI_ALL
pfpro.proxypassword "" PHP_INI_ALL
pgsql.allow_persistent "1" PHP_INI_SYSTEM
pgsql.max_persistent "-1" PHP_INI_SYSTEM
pgsql.max_links "-1" PHP_INI_SYSTEM
pgsql.auto_reset_persistent "0" PHP_INI_SYSTEM
pgsql.ignore_notice "0" PHP_INI_ALL
pgsql.log_notice "0" PHP_INI_ALL
session.save_path "/tmp" PHP_INI_ALL
session.name "PHPSESSID" PHP_INI_ALL
session.save_handler "files" PHP_INI_ALL
session.auto_start "0" PHP_INI_ALL
session.gc_probability "1" PHP_INI_ALL
session.gc_maxlifetime "1440" PHP_INI_ALL
session.serialize_handler "php" PHP_INI_ALL
session.cookie_lifetime "0" PHP_INI_ALL
session.cookie_path "/" PHP_INI_ALL
session.cookie_domain "" PHP_INI_ALL
session.cookie_secure "" PHP_INI_ALL
session.use_cookies "1" PHP_INI_ALL
session.use_only_cookies "0" PHP_INI_ALL
session.referer_check "" PHP_INI_ALL
session.entropy_file "" PHP_INI_ALL
session.entropy_length "0" PHP_INI_ALL
session.cache_limiter "nocache" PHP_INI_ALL
session.cache_expire "180" PHP_INI_ALL
session.use_trans_sid "1" PHP_INI_SYSTEM|PHP_INI_PERDIR
session.encode_sources "globals,track" PHP_INI_ALL
assert.active "1" PHP_INI_ALL
assert.bail "0" PHP_INI_ALL
assert.warning "1" PHP_INI_ALL
assert.callback NULL PHP_INI_ALL
assert.quiet_eval "0" PHP_INI_ALL
safe_mode_protected_env_vars SAFE_MODE_PROTECTED_ENV_VARS PHP_INI_SYSTEM
safe_mode_allowed_env_vars SAFE_MODE_ALLOWED_ENV_VARS PHP_INI_SYSTEM
url_rewriter.tags "a=href,area=href,frame=src,form=fakeentry" PHP_INI_ALL
sybct.allow_persistent "1" PHP_INI_SYSTEM
sybct.max_persistent "-1" PHP_INI_SYSTEM
sybct.max_links "-1" PHP_INI_SYSTEM
sybct.min_server_severity "10" PHP_INI_ALL
sybct.min_client_severity "10" PHP_INI_ALL
sybct.hostname NULL PHP_INI_ALL
vpopmail.directory "" PHP_INI_ALL
zlib.output_compression "0" PHP_INI_SYSTEM|PHP_INI_PERDIR
zlib.output_compression_level "-1" PHP_INI_ALL
define_syslog_variables "0" PHP_INI_ALL
highlight.bg HL_BG_COLOR PHP_INI_ALL
highlight.comment HL_COMMENT_COLOR PHP_INI_ALL
highlight.default HL_DEFAULT_COLOR PHP_INI_ALL
highlight.html HL_HTML_COLOR PHP_INI_ALL
highlight.keyword HL_KEYWORD_COLOR PHP_INI_ALL
highlight.string HL_STRING_COLOR PHP_INI_ALL
allow_call_time_pass_reference "1" PHP_INI_SYSTEM|PHP_INI_PERDIR
asp_tags "0" PHP_INI_SYSTEM|PHP_INI_PERDIR
display_errors "1" PHP_INI_ALL
display_startup_errors "0" PHP_INI_ALL
enable_dl "1" PHP_INI_SYSTEM
expose_php "1" PHP_INI_SYSTEM
html_errors "1" PHP_INI_SYSTEM
xmlrpc_errors "0" PHP_INI_SYSTEM
xmlrpc_error_number "0" PHP_INI_ALL
ignore_user_abort "0" PHP_INI_ALL
implicit_flush "0" PHP_INI_PERDIR|PHP_INI_SYSTEM
log_errors "0" PHP_INI_ALL
log_errors_max_len "1024" PHP_INI_ALL
ignore_repeated_errors "0" PHP_INI_ALL
ignore_repeated_source "0" PHP_INI_ALL
magic_quotes_gpc "1" PHP_INI_PERDIR|PHP_INI_SYSTEM
magic_quotes_runtime "0" PHP_INI_ALL
magic_quotes_sybase "0" PHP_INI_ALL
output_buffering "0" PHP_INI_PERDIR|PHP_INI_SYSTEM
output_handler NULL PHP_INI_PERDIR|PHP_INI_SYSTEM
register_argc_argv "1" PHP_INI_PERDIR|PHP_INI_SYSTEM
register_globals "0" PHP_INI_PERDIR|PHP_INI_SYSTEM
safe_mode "1" PHP_INI_SYSTEM
safe_mode "0" PHP_INI_SYSTEM
safe_mode_include_dir NULL PHP_INI_SYSTEM
safe_mode_gid "0" PHP_INI_SYSTEM
short_open_tag DEFAULT_SHORT_OPEN_TAG PHP_INI_SYSTEM|PHP_INI_PERDIR
sql.safe_mode "0" PHP_INI_SYSTEM
track_errors "0" PHP_INI_ALL
y2k_compliance "0" PHP_INI_ALL
unserialize_callback_func NULL PHP_INI_ALL
arg_separator.output "&" PHP_INI_ALL
arg_separator.input "&" PHP_INI_SYSTEM|PHP_INI_PERDIR
auto_append_file NULL PHP_INI_SYSTEM|PHP_INI_PERDIR
auto_prepend_file NULL PHP_INI_SYSTEM|PHP_INI_PERDIR
doc_root NULL PHP_INI_SYSTEM
default_charset SAPI_DEFAULT_CHARSET PHP_INI_ALL
default_mimetype SAPI_DEFAULT_MIMETYPE PHP_INI_ALL
error_log NULL PHP_INI_ALL
extension_dir PHP_EXTENSION_DIR PHP_INI_SYSTEM
gpc_order "GPC" PHP_INI_ALL
include_path PHP_INCLUDE_PATH PHP_INI_ALL
max_execution_time "30" PHP_INI_ALL
open_basedir NULL PHP_INI_SYSTEM
safe_mode_exec_dir "1" PHP_INI_SYSTEM
upload_max_filesize "2M" PHP_INI_SYSTEM
file_uploads "1" PHP_INI_SYSTEM
post_max_size "8M" PHP_INI_SYSTEM
upload_tmp_dir NULL PHP_INI_SYSTEM
user_dir NULL PHP_INI_SYSTEM
variables_order NULL PHP_INI_ALL
error_append_string NULL PHP_INI_ALL
error_prepend_string NULL PHP_INI_ALL
SMTP "localhost" PHP_INI_ALL
smtp_port 25 PHP_INI_ALL
browscap NULL PHP_INI_SYSTEM
error_reporting NULL PHP_INI_ALL
memory_limit "8M" PHP_INI_ALL
precision "14" PHP_INI_ALL
sendmail_from NULL PHP_INI_ALL
sendmail_path DEFAULT_SENDMAIL_PATH PHP_INI_SYSTEM
disable_functions "" PHP_INI_SYSTEM
allow_url_fopen "1" PHP_INI_ALL
always_populate_raw_post_data "0" PHP_INI_ALL
xbithack "0" PHP_INI_ALL
engine "1" PHP_INI_ALL
last_modified "0" PHP_INI_ALL
child_terminate "0" PHP_INI_ALL
async_send "0" PHP_INI_ALL

Tabela 2. Definition of PHP_INI_* constants

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

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

php_ini_scanned_files

(PHP 4 >= 4.3.0)

php_ini_scanned_files -- Return a list of .ini files parsed from the additional ini dir

Description

string php_ini_scanned_files ( void)

php_ini_scanned_files() returns a comma-separated list of configuration files parsed after php.ini. These files are found in a directory defined by the --with-config-file-scan-dir. option which is set during compilation.

Returns a comma-separated string of .ini files on success. If the directive --with-config-files-scan-dir wasn't set, FALSE is returned. If it was set and the directory was empty, an empty string is returned. If a file is unreconizable, the file will still make it into the returned string but a PHP error will also result. This PHP error will be seen both at compile time and while using php_ini_scanned_files().

The returned configuration files also include the path as declared in the --with-config-file-scan-dir directive. Also, each comma is followed by a newline.

Exemplo 1. A simple example to list the returned ini files

<?php

if ($filelist = php_ini_scanned_files()) {

    if (strlen($filelist) > 0) {
    
        $files = explode(',', $filelist);
  
        foreach ($files as $file) {
            echo "<li>" . trim($file) . "</li>\n";
        }
    }
}
?>

See also ini_set() and phpinfo().

php_logo_guid

(PHP 4 )

php_logo_guid -- Gets the logo guid

Description

string php_logo_guid ( void)

Nota: This functionality was added in PHP 4.0.0.

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

php_sapi_name

(PHP 4 >= 4.0.1)

php_sapi_name --  Returns the type of interface between web server and PHP

Description

string php_sapi_name ( void)

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

Exemplo 1. php_sapi_name() Example

$sapi_type = php_sapi_name();
if ($sapi_type == "cgi")
    print "You are using CGI PHP\n";
else
    print "You are not using CGI PHP\n";

php_uname

(PHP 4 >= 4.0.2)

php_uname --  Returns information about the operating system PHP was built on

Description

string php_uname ( void)

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

Exemplo 1. php_uname() Example

if (substr(php_uname(), 0, 7) == "Windows") {
   die ("Sorry, this script doesn't run on Windows.\n");
}

phpcredits

(PHP 4 )

phpcredits -- Prints out the credits for PHP

Description

void phpcredits ( [int flag])

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

...
phpcredits(CREDITS_GENERAL);
...

And if you want to print the core developers and the documentation group, in a page of its own, you will use:

<?php
phpcredits(CREDITS_GROUP + CREDITS_DOCS + CREDITS_FULLPAGE);
?>

And if you feel like embedding all the credits in your page, then code like the one below will do it:

<html>
 <head>
  <title>My credits page</title>
 </head>
 <body>
  <?php
 // some code of your own
 phpcredits(CREDITS_ALL);
 // some more code
 ?>
 </body>
</html>

Tabela 1. Pre-defined phpcredits() flags

name description
CREDITS_ALL All the credits, equivalent to using: CREDITS_DOCS + CREDITS_GENERAL + CREDITS_GROUP + CREDITS_MODULES + CREDITS_FULLPAGE. It generates a complete stand-alone HTML page with the appropriate tags.
CREDITS_DOCS The credits for the documentation team
CREDITS_FULLPAGE Usually used in combination with the other flags. Indicates that the a complete stand-alone HTML page needs to be printed including the information indicated by the other flags.
CREDITS_GENERAL General credits: Language design and concept, PHP 4.0 authors and SAPI module.
CREDITS_GROUP A list of the core developers
CREDITS_MODULES A list of the extension modules for PHP, and their authors
CREDITS_SAPI A list of the server API modules for PHP, and their authors

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

phpinfo

(PHP 3, PHP 4 )

phpinfo -- Outputs lots of PHP information

Description

int phpinfo ( [int what])

Outputs a large amount of information about the current state of PHP. This includes information about PHP compilation options and extensions, the PHP version, server information and environment (if compiled as a module), the PHP environment, OS version information, paths, master and local values of configuration options, HTTP headers, and the PHP License.

Because every system is setup differently, phpinfo() is commonly used to check configuration settings and for available predefined variables on a given system. Also, phpinfo() is a valuable debugging tool as it contains all EGPCS (Environment, GET, POST, Cookie, Server) data.

The output may be customized by passing one or more of the following constants bitwise values summed together in the optional what parameter. One can also combine the respective constants or bitwise values together with the or operator.

Tabela 1. phpinfo() options

Name (constant) Value Description
INFO_GENERAL 1 The configuration line, php.ini location, build date, Web Server, System and more.
INFO_CREDITS 2 PHP 4 Credits. See also phpcredits().
INFO_CONFIGURATION 4 Current Local and Master values for php directives. See also ini_get().
INFO_MODULES 8 Loaded modules and their respective settings.
INFO_ENVIRONMENT 16 Environment Variable information that's also available in $_ENV.
INFO_VARIABLES 32 Shows all predefined variables from EGPCS (Environment, GET, POST, Cookie, Server).
INFO_LICENSE 64 PHP License information. See also the license faq.
INFO_ALL -1 Shows all of the above. This is the default value.

Exemplo 1. phpinfo() examples

<?php

// Show all information, defaults to INFO_ALL
phpinfo();

// Show just the module information.
// phpinfo(8) yields identical results.
phpinfo(INFO_MODULES);

?>

Nota: Parts of the information displayed are disabled when the expose_php configuration setting is set to off. This includes the PHP and Zend logos, and the credits.

See also: phpversion(), phpcredits(), php_logo_guid(), ini_get(), ini_set(), and the section on Predefined Variables.

phpversion

(PHP 3, PHP 4 )

phpversion -- Gets the current PHP version

Description

string phpversion ( void)

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

Nota: This information is also available in the predefined constant PHP_VERSION.

Exemplo 1. phpversion() Example

<?php
// prints e.g. 'Current PHP version: 4.1.1'
echo 'Current PHP version: ' . phpversion();
?>

See also version_compare(), phpinfo(), phpcredits(), php_logo_guid(), and zend_version().

putenv

(PHP 3, PHP 4 )

putenv -- Sets the value of an environment variable

Description

void putenv ( string setting)

Adds setting to the server environment. The environment variable will only exist for the duration of the current request. At the end of the request the environment is restored to its original state.

Setting certain environment variables may be a potential security breach. The safe_mode_allowed_env_vars directive contains a comma-delimited list of prefixes. In Safe Mode, the user may only alter environment variables whose names begin with the prefixes supplied by this directive. By default, users will only be able to set environment variables that begin with PHP_ (e.g. PHP_FOO=BAR). Note: if this directive is empty, PHP will let the user modify ANY environment variable!

The safe_mode_protected_env_vars directive contains a comma-delimited list of environment variables, that the end user won't be able to change using putenv(). These variables will be protected even if safe_mode_allowed_env_vars is set to allow to change them.

Atenção

These directives have only effect when safe-mode itself is enabled!

Exemplo 1. Setting an Environment Variable

putenv ("UNIQID=$uniqid");

See also getenv().

set_magic_quotes_runtime

(PHP 3>= 3.0.6, PHP 4 )

set_magic_quotes_runtime --  Sets the current active configuration setting of magic_quotes_runtime

Description

long set_magic_quotes_runtime ( int new_setting)

Set the current active configuration setting of magic_quotes_runtime (0 for off, 1 for on).

See also: get_magic_quotes_gpc() and get_magic_quotes_runtime().

set_time_limit

(PHP 3, PHP 4 )

set_time_limit -- Limits the maximum execution time

Description

void set_time_limit ( int seconds)

Set the number of seconds a script is allowed to run. If this is reached, the script returns a fatal error. The default limit is 30 seconds or, if it exists, the max_execution_time value defined in the configuration file. If seconds is set to zero, no time limit is imposed.

When called, set_time_limit() restarts the timeout counter from zero. In other words, if the timeout is the default 30 seconds, and 25 seconds into script execution a call such as set_time_limit(20) is made, the script will run for a total of 45 seconds before timing out.

set_time_limit() has no effect when PHP is running in safe mode. There is no workaround other than turning off safe mode or changing the time limit in the configuration file.

Nota: The set_time_limit() function and the configuration directive max_execution_time only affect the execution time of the script itself. Any time spent on activity that happens outside the execution of the script such as system calls using system(), the sleep() function, database queries, etc. is not included when determining the maximum time that the script has been running.

version_compare

(PHP 4 >= 4.1.0)

version_compare --  Compares two "PHP-standardized" version number strings

Description

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

version_compare() compares two "PHP-standardized" version number strings. This is useful if you would like to write programs working only on some versions of PHP.

version_compare() returns -1 if the first version is lower than the second, 0 if they are equal, and +1 if the second is lower.

If you specify the third optional operator argument, you can test for a particular relationship. The possible operators are: <, lt, <=, le, >, gt, >=, ge, ==, =, eq, !=, <>, ne respectively. Using this argument, the function will return 1 if the relationship is the one specified by the operator, 0 otherwise.

Exemplo 1. version_compare() Example

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

// these all print 1
echo version_compare("4.0.4", "4.0.6", "<");
echo version_compare("4.0.6", "4.0.6", "eq");

zend_logo_guid

(PHP 4 )

zend_logo_guid -- Gets the zend guid

Description

string zend_logo_guid ( void)

Nota: This functionality was added in PHP 4.0.0.

zend_version

(PHP 4 )

zend_version -- Gets the version of the current Zend engine

Description

string zend_version ( void)

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

Exemplo 1. zend_version() Example

// prints e.g. 'Zend engine version: 1.0.4'
echo "Zend engine version: " . zend_version();

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

LXXX. POSIX functions

Introdução

This module contains an interface to those functions defined in the IEEE 1003.1 (POSIX.1) standards document which are not accessible through other means. POSIX.1 for example defined the open(), read(), write() and close() functions, too, which traditionally have been part of PHP 3 for a long time. Some more system specific functions have not been available before, though, and this module tries to remedy this by providing easy access to these functions.

Atenção

Sensitive data can be retrieved with the POSIX functions, e.g. posix_getpwnam() and friends. None of the POSIX function perform any kind of access checking when safe mode is enabled. It's therefore strongly advised to disable the POSIX extension at all (use --disable-posix in your configure line) if you're operating in such an environment.

Nota: This extension is not available on Windows platforms.


Instalação

POSIX functions are enabled by default. You can disable POSIX-like functions with --disable-posix.


Veja Também

The section about Process Control Functions maybe of interest for you.

Índice
posix_ctermid -- Get path name of controlling terminal
posix_getcwd -- Pathname of current directory
posix_getegid --  Return the effective group ID of the current process
posix_geteuid --  Return the effective user ID of the current process
posix_getgid --  Return the real group ID of the current process
posix_getgrgid -- Return info about a group by group id
posix_getgrnam -- Return info about a group by name
posix_getgroups --  Return the group set of the current process
posix_getlogin -- Return login name
posix_getpgid -- Get process group id for job control
posix_getpgrp --  Return the current process group identifier
posix_getpid -- Return the current process identifier
posix_getppid -- Return the parent process identifier
posix_getpwnam -- Return info about a user by username
posix_getpwuid -- Return info about a user by user id
posix_getrlimit -- Return info about system ressource limits
posix_getsid -- Get the current sid of the process
posix_getuid --  Return the real user ID of the current process
posix_isatty --  Determine if a file descriptor is an interactive terminal
posix_kill -- Send a signal to a process
posix_mkfifo --  Create a fifo special file (a named pipe)
posix_setegid --  Set the effective GID of the current process
posix_seteuid --  Set the effective UID of the current process
posix_setgid --  Set the GID of the current process
posix_setpgid -- set process group id for job control
posix_setsid -- Make the current process a session leader
posix_setuid --  Set the UID of the current process
posix_times -- Get process times
posix_ttyname -- Determine terminal device name
posix_uname -- Get system name

posix_ctermid

(PHP 3>= 3.0.13, PHP 4 )

posix_ctermid -- Get path name of controlling terminal

Description

string posix_ctermid ( void)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

posix_getcwd

(PHP 3>= 3.0.13, PHP 4 )

posix_getcwd -- Pathname of current directory

Description

string posix_getcwd ( void)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

posix_getegid

(PHP 3>= 3.0.10, PHP 4 )

posix_getegid --  Return the effective group ID of the current process

Description

int posix_getegid ( void)

Return the numeric effective group ID of the current process. See also posix_getgrgid() for information on how to convert this into a useable group name.

posix_geteuid

(PHP 3>= 3.0.10, PHP 4 )

posix_geteuid --  Return the effective user ID of the current process

Description

int posix_geteuid ( void)

Return the numeric effective user ID of the current process. See also posix_getpwuid() for information on how to convert this into a useable username.

posix_getgid

(PHP 3>= 3.0.10, PHP 4 )

posix_getgid --  Return the real group ID of the current process

Description

int posix_getgid ( void)

Return the numeric real group ID of the current process. See also posix_getgrgid() for information on how to convert this into a useable group name.

posix_getgrgid

(PHP 3>= 3.0.13, PHP 4 )

posix_getgrgid -- Return info about a group by group id

Description

array posix_getgrgid ( int gid)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

posix_getgrnam

(PHP 3>= 3.0.13, PHP 4 )

posix_getgrnam -- Return info about a group by name

Description

array posix_getgrnam ( string name)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

posix_getgroups

(PHP 3>= 3.0.10, PHP 4 )

posix_getgroups --  Return the group set of the current process

Description

array posix_getgroups ( void)

Returns an array of integers containing the numeric group ids of the group set of the current process. See also posix_getgrgid() for information on how to convert this into useable group names.

posix_getlogin

(PHP 3>= 3.0.13, PHP 4 )

posix_getlogin -- Return login name

Description

string posix_getlogin ( void)

Returns the login name of the user owning the current process. See posix_getpwnam() for information how to get more information about this user.

posix_getpgid

(PHP 3>= 3.0.10, PHP 4 )

posix_getpgid -- Get process group id for job control

Description

int posix_getpgid ( int pid)

Returns the process group identifier of the process pid.

This is not a POSIX function, but is common on BSD and System V systems. If your system does not support this function at system level, this PHP function will always return FALSE.

posix_getpgrp

(PHP 3>= 3.0.10, PHP 4 )

posix_getpgrp --  Return the current process group identifier

Description

int posix_getpgrp ( void)

Return the process group identifier of the current process. See POSIX.1 and the getpgrp(2) manual page on your POSIX system for more information on process groups.

posix_getpid

(PHP 3>= 3.0.10, PHP 4 )

posix_getpid -- Return the current process identifier

Description

int posix_getpid ( void)

Return the process identifier of the current process.

posix_getppid

(PHP 3>= 3.0.10, PHP 4 )

posix_getppid -- Return the parent process identifier

Description

int posix_getppid ( void)

Return the process identifier of the parent process of the current process.

posix_getpwnam

(PHP 3>= 3.0.13, PHP 4 )

posix_getpwnam -- Return info about a user by username

Description

array posix_getpwnam ( string username)

Returns an associative array containing information about a user referenced by an alphanumeric username, passed in the username parameter.

The array elements returned are:

Tabela 1. The user information array

Element Description
name The name element contains the username of the user. This is a short, usually less than 16 character "handle" of the user, not her real, full name. This should be the same as the username parameter used when calling the function, and hence redundant.
passwd The passwd element contains the user's password in an encrypted format. Often, for example on a system employing "shadow" passwords, an asterisk is returned instead.
uid User ID of the user in numeric form.
gid The group ID of the user. Use the function posix_getgrgid() to resolve the group name and a list of its members.
gecos GECOS is an obsolete term that refers to the finger information field on a Honeywell batch processing system. The field, however, lives on, and its contents have been formalized by POSIX. The field contains a comma separated list containing the user's full name, office phone, office number, and home phone number. On most systems, only the user's full name is available.
dir This element contains the absolute path to the home directory of the user.
shell The shell element contains the absolute path to the executable of the user's default shell.

posix_getpwuid

(PHP 3>= 3.0.13, PHP 4 )

posix_getpwuid -- Return info about a user by user id

Description

array posix_getpwuid ( int uid)

Returns an associative array containing information about a user referenced by a numeric user ID, passed in the uid parameter.

The array elements returned are:

Tabela 1. The user information array

Element Description
name The name element contains the username of the user. This is a short, usually less than 16 character "handle" of the user, not her real, full name.
passwd The passwd element contains the user's password in an encrypted format. Often, for example on a system employing "shadow" passwords, an asterisk is returned instead.
uid User ID, should be the same as the uid parameter used when calling the function, and hence redundant.
gid The group ID of the user. Use the function posix_getgrgid() to resolve the group name and a list of its members.
gecos GECOS is an obsolete term that refers to the finger information field on a Honeywell batch processing system. The field, however, lives on, and its contents have been formalized by POSIX. The field contains a comma separated list containing the user's full name, office phone, office number, and home phone number. On most systems, only the user's full name is available.
dir This element contains the absolute path to the home directory of the user.
shell The shell element contains the absolute path to the executable of the user's default shell.

posix_getrlimit

(PHP 3>= 3.0.10, PHP 4 )

posix_getrlimit -- Return info about system ressource limits

Description

array posix_getrlimit ( void)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

posix_getsid

(PHP 3>= 3.0.10, PHP 4 )

posix_getsid -- Get the current sid of the process

Description

int posix_getsid ( int pid)

Return the sid of the process pid. If pid is 0, the sid of the current process is returned.

This is not a POSIX function, but is common on System V systems. If your system does not support this function at system level, this PHP function will always return FALSE.

posix_getuid

(PHP 3>= 3.0.10, PHP 4 )

posix_getuid --  Return the real user ID of the current process

Description

int posix_getuid ( void)

Return the numeric real user ID of the current process. See also posix_getpwuid() for information on how to convert this into a useable username.

posix_isatty

(PHP 3>= 3.0.13, PHP 4 )

posix_isatty --  Determine if a file descriptor is an interactive terminal

Description

bool posix_isatty ( int fd)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

posix_kill

(PHP 3>= 3.0.13, PHP 4 )

posix_kill -- Send a signal to a process

Description

bool posix_kill ( int pid, int sig)

Send the signal sig to the process with the process identifier pid. Returns FALSE, if unable to send the signal, TRUE otherwise.

See also the kill(2) manual page of your POSIX system, which contains additional information about negative process identifiers, the special pid 0, the special pid -1, and the signal number 0.

posix_mkfifo

(PHP 3>= 3.0.13, PHP 4 )

posix_mkfifo --  Create a fifo special file (a named pipe)

Description

bool posix_mkfifo ( string pathname, int mode)

posix_mkfifo() creates a special FIFO file which exists in the file system and acts as a bidirectional communication endpoint for processes.

The second parameter mode has to be given in octal notation (e.g. 0644). The permission of the newly created FIFO also depends on the setting of the current umask(). The permissions of the created file are (mode & ~umask).

Nota: Quando o safe-mode está ativo, o PHP verifica se o diretório que será afetado por essa operação tem o mesmo UID (proprietário) do script que está sendo executado.

posix_setegid

(PHP 4 >= 4.0.2)

posix_setegid --  Set the effective GID of the current process

Description

bool posix_setegid ( int gid)

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

Returns TRUE on success, FALSE otherwise.

posix_seteuid

(PHP 4 >= 4.0.2)

posix_seteuid --  Set the effective UID of the current process

Description

bool posix_seteuid ( int uid)

Set the real user ID of the current process. This is a privileged function and you need appropriate privileges (usually root) on your system to be able to perform this function.

Returns TRUE on success, FALSE otherwise. See also posix_setgid().

posix_setgid

(PHP 3>= 3.0.13, PHP 4 )

posix_setgid --  Set the GID of the current process

Description

bool posix_setgid ( int gid)

Set the real group ID of the current process. This is a privileged function and you need appropriate privileges (usually root) on your system to be able to perform this function. The appropriate order of function calls is posix_setgid() first, posix_setuid() last.

Returns TRUE on success, FALSE otherwise.

posix_setpgid

(PHP 3>= 3.0.13, PHP 4 )

posix_setpgid -- set process group id for job control

Description

int posix_setpgid ( int pid, int pgid)

Let the process pid join the process group pgid. See POSIX.1 and the setsid(2) manual page on your POSIX system for more informations on process groups and job control. Returns TRUE on success, FALSE otherwise.

posix_setsid

(PHP 3>= 3.0.13, PHP 4 )

posix_setsid -- Make the current process a session leader

Description

int posix_setsid ( void)

Make the current process a session leader. See POSIX.1 and the setsid(2) manual page on your POSIX system for more informations on process groups and job control. Returns the session id.

posix_setuid

(PHP 3>= 3.0.13, PHP 4 )

posix_setuid --  Set the UID of the current process

Description

bool posix_setuid ( int uid)

Set the real user ID of the current process. This is a privileged function and you need appropriate privileges (usually root) on your system to be able to perform this function.

Returns TRUE on success, FALSE otherwise. See also posix_setgid().

posix_times

(PHP 3>= 3.0.13, PHP 4 )

posix_times -- Get process times

Description

array posix_times ( void)

Returns a hash of strings with information about the current process CPU usage. The indices of the hash are

  • ticks - the number of clock ticks that have elapsed since reboot.

  • utime - user time used by the current process.

  • stime - system time used by the current process.

  • cutime - user time used by current process and children.

  • cstime - system time used by current process and children.

posix_ttyname

(PHP 3>= 3.0.13, PHP 4 )

posix_ttyname -- Determine terminal device name

Description

string posix_ttyname ( int fd)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

posix_uname

(PHP 3>= 3.0.10, PHP 4 )

posix_uname -- Get system name

Description

array posix_uname ( void)

Returns a hash of strings with information about the system. The indices of the hash are

  • sysname - operating system name (e.g. Linux)

  • nodename - system name (e.g. valiant)

  • release - operating system release (e.g. 2.2.10)

  • version - operating system version (e.g. #4 Tue Jul 20 17:01:36 MEST 1999)

  • machine - system architecture (e.g. i586)

  • domainname - DNS domainname (e.g. php.net)

domainname is a GNU extension and not part of POSIX.1, so this field is only available on GNU systems or when using the GNU libc.

Posix requires that you must not make any assumptions about the format of the values, e.g. you cannot rely on three digit version numbers or anything else returned by this function.

LXXXI. Funções para PostgreSQL

Introdução

O banco de dados PostgreSQL é um produto de código aberto e disponível gratuitamente. O Postgres, desenvolvido originalmente no Departamento de Ciência de Computação da Universidade de Berkeley, foi pioneiro em muitos dos conceitos objeto-relacionais que agora estão disponíveis em alguns bancos de dados comerciais. Fornece suporte a linguagem SQL92/SQL99, integridade de transações e extensibilidade de tipos. O PostgreSQL é um descendente com código aberto do código original desenvolvido em Berkeley.


Requisitos

Para usar usar as funções para PostgreSQL, você precisa do PostgreSQL 6.5 ou superior e PostgreSQL 7.0 ou superior para habilitar todos os recursos deste módulo. PostgreSQL suporta inúmeros tipos de codificação de caracteres incluindo a codificação de caracteres multibyte. A versão mais atual e mais informações sobre PostgreSQL estão disponíveis em http://www.postgresql.org/.


Instalação

Para habilitar o módulo de funções para PostgreSQL, a opção de configuração --with-pgsql[=DIR] deve ser usada no momento da compilação do PHP. Se o módulo PostgreSQL estiver disponível como objeto compartilhado, poderá ser carregado usando a diretiva extension no php.ini ou a função dl().


Configuração durante execução

O comportamento dessas funções podem ser modificado pelas configurações do php.ini.

Tabela 1. Opções de configuração do PostgreSQL

Nome Padrão Alterável
pgsql.allow_persistent "1" PHP_INI_SYSTEM
pgsql.max_persistent "-1" PHP_INI_SYSTEM
pgsql.max_links "-1" PHP_INI_SYSTEM
pgsql.auto_reset_persistent "0" PHP_INI_SYSTEM
pgsql.ignore_notice "0" PHP_INI_ALL
pgsql.log_notice "0" PHP_INI_ALL
Para mais detalhes e definições das constantes PHP_INI_* veja ini_set().

Aqui está uma pequena explicação sobre as diretivas de configuração.

pgsql.allow_persistent boolean

Se quer ou não permitir conexões persistentes com o PostgreSQL.

pgsql.max_persistent integer

O número máximo de conexões persistentes com PostgreSQL por processo.

pgsql.max_links integer

O número máximo de conexões PostgreSQL por processo, incluindo as persistentes.


Como usar e algumas dicas

Atenção

Usar o módulo PostgreSQL com o PHP 4.0.6 não é recomendado devido a um bug no código de manipulação de notificações. Use o 4.1.0 ou superior.

Atenção

Os nomes das funções PostgreSQL serão alterados na versão 4.2.0 para confirmar os padrões de programação atuais. A maioria dos novos nomes terão sublinhados (underscore) adicionais, por exemplo, pg_lo_open(). Algumas funções foram renomeadas para uma maior consistência, por exemplo, pg_exec() mudou para pg_query(). Os nomes antigos podem ser usados na 4.2.0 e em algumas poucas outras versões após esta, mas eles serão removidos futuramente.

Tabela 2. Nomes de funções alterados

pg_exec() pg_query()
pg_getlastoid() pg_last_oid()
pg_cmdtuples() pg_affected_rows()
pg_numrows() pg_num_rows()
pg_numfields() pg_num_fields()
pg_fieldname() pg_field_name()
pg_fieldsize() pg_field_size()
pg_fieldnum() pg_field_num()
pg_fieldprtlen() pg_field_prtlen()
pg_fieldisnull() pg_field_is_null()
pg_freeresult() pg_free_result()
pg_result() pg_fetch_result()
pg_loreadall() pg_lo_read_all()
pg_locreate() pg_lo_create()
pg_lounlink() pg_lo_unlink()
pg_loopen() pg_lo_unlink()
pg_loclose() pg_lo_close()
pg_loread() pg_lo_read()
pg_lowrite() pg_lo_write()
pg_loimport() pg_lo_import()
pg_loexport() pg_lo_export()

A antiga sintaxe pg_connect()/pg_pconnect() ficará obsoleta para suportar conexões assíncronas no futuro. Por favor, use a string de conexão para pg_connect() e pg_pconnect().

Nem todas as funções são suportadas por todas as compilações. Isso vai depender da versão da libpq (A interface cliente em C para PostgreSQL) e como esta foi compilada. Se há alguma função ausente, é porque a libpq não suporta a característica exigida por esta função.

Também é importante que você use uma versão da libpq mais nova do que a que o servidor exige. Se você usar uma versão mais antiga do que a que o servidor espera, você poderá ter problemas.

Desde a versão 6.3 (03/02/1998), o PostgreSQL usa sockets de domínio unix por padrão. A porta TCP não ficará aberta por padrão. Uma tabela é mostrada abaixo descrevendo essas novas possibilidades de conexão. Este socket será encontrado em /tmp/.s.PGSQL.5432. Esta opção pode ser habilitada com o parâmetro '-i' para o postmaster e seu significado é: "escute em sockets TCP/IP assim como em sockets de domínio Unix".

Tabela 3. Postmaster e PHP

Postmaster PHP Status
postmaster & pg_connect("dbname=MyDbName"); OK
postmaster -i & pg_connect("dbname=MyDbName"); OK
postmaster & pg_connect("host=localhost dbname=MyDbName"); Unable to connect to PostgreSQL server: connectDB() failed: Is the postmaster running and accepting TCP/IP (with -i) connection at 'localhost' on port '5432'? in /path/to/file.php on line 20.
postmaster -i & pg_connect("host=localhost dbname=MyDbName"); OK

Uma conexão com o servidor PostgreSQL pode ser estabelecida com os seguintes pares de valores definidos na string de comando: $conn = pg_connect("host=seuHost port=suaPorta tty=seuTTY options=suasOpcoes dbname=seuDB user=seuUsuario password=suaSenha");

A sintaxe anterior: $conn = pg_connect ("host", "porta", "opcoes", "tty", "nomebd") ficará obsoleta.

Variáveis de ambiente afetam o comportamento do servidor/cliente PostgreSQL. Por exemplo, o módulo PostgreSQL irá procurar pela variável de ambiente PGHOST quando o nome de host é omitido na string de conexão. As variáveis de ambiente suportadas variam de versão para versão. Vide o Manual de Programador do PostgreSQL (Programmer´s Manual, na seção libpq - Enviroment Variables) para maiores detalhes.

Certifique-se que você definiu as variáveis de ambiente para o usuário apropriado. Use $_ENV ou getenv() para verificar se as variáveis de ambiente estão disponíveis para o processo atual.

Exemplo 1. Definindo os parâmetros padrão

PGHOST=psgql.example.com
PGPORT=7890
PGDATABASE=web-system
PGUSER=web-user
PGPASSWORD=secret
PGDATESTYLE=ISO
PGTZ=JST
PGCLIENTENCODING=EUC-JP

export PGHOST PGPORT PGDATABASE PGUSER PGPASSWORD PGDATESTYLE PGTZ PGCLIENTENCODING

Constantes Predefinidas

As contantes abaixo são definidas por esta extensão e somente estarão disponíveis quando a extensão foi compilada com o PHP ou carregada dinamicamente durante a execução.

PGSQL_ASSOC (integer)

PGSQL_NUM (integer)

PGSQL_BOTH (integer)

PGSQL_CONNECTION_BAD (integer)

PGSQL_CONNECTION_OK (integer)

PGSQL_SEEK_SET (integer)

PGSQL_SEEK_CUR (integer)

PGSQL_SEEK_END (integer)

PGSQL_ESCAPE_STRING (integer)

PGSQL_ESCAPE_BYTEA (integer)

PGSQL_EMPTY_QUERY (integer)

PGSQL_COMMAND_OK (integer)

PGSQL_TUPLES_OK (integer)

PGSQL_COPY_OUT (integer)

PGSQL_COPY_IN (integer)

PGSQL_BAD_RESPONSE (integer)

PGSQL_NONFATAL_ERROR (integer)

PGSQL_FATAL_ERROR (integer)


Exemplos

A partir do PostgreSQL 7.1.0, você pode armazenar até 1GB dentro de um campo do tipo texto. Em versões mais antigas, isto era limitado ao tamanho do bloco (o padrão era 8KB e o máximo era 32KB, definido em tempo de compilação).

Para usar a interface de objetos grandes (large objects), é exigido que se encapsule as funções de objetos grandes em um bloco de transação. Um bloco de transação inicia-se com a declaração SQL BEGIN e, se a transação for válida, termina com COMMIT ou END. Se a transação falhar, ela deve ser fechada com ROLLBACK ou ABORT.

Exemplo 2. Usando Objetos Grandes (large objects)

<?php
    $database = pg_connect ("dbname=jacarta");
    pg_query ($database, "begin");
    $oid = pg_lo_create ($database);
    echo "$oid\n";
    $handle = pg_lo_open ($database, $oid, "w");
    echo "$handle\n";
    pg_lo_write ($handle, "large object data");
    pg_lo_close ($handle);
    pg_query ($database, "commit");
?>
Você não deve fechar a conexão com o servidor PostgreSQL antes de fechar o objeto grande.

Índice
pg_affected_rows -- Retorna o número de registros afetados (linhas)
pg_cancel_query --  Cancela uma consulta (query) assíncrona
pg_client_encoding --  Retorna a codificação do cliente
pg_close -- Fecha uma conexão PostgreSQL
pg_connect -- Abre uma conexão PostgreSQL
pg_connection_busy --  Verifica se a conexão está ocupada ou não
pg_connection_reset --  Reinicia uma conexão (reconecta)
pg_connection_status --  Retorna o status da conexão
pg_convert --  Converte os valores de um array associativo em uma declaração SQL apropriada.
pg_copy_from --  Insere registros em uma tabela a partir de um array
pg_copy_to --  Copia uma tabela em um array
pg_dbname -- Retorna o nome do banco de dados
pg_delete --  Remove registros.
pg_end_copy -- Sincroniza com o backend PostgreSQL
pg_escape_bytea --  Gera binários para o tipo bytea
pg_escape_string --  Gera string para o tipo text/char
pg_fetch_all -- Retorna todas as linhas (registros) como um array
pg_fetch_array -- Retorna uma linha (registro) como um array
pg_fetch_assoc -- Retorna uma linha (registro) como um array
pg_fetch_object -- Retorna uma linha (registro) como um objeto
pg_fetch_result -- Retorna valores a partir de um recurso (resource) de resultado
pg_fetch_row -- Retorna uma linha como um array enumerado
pg_field_is_null -- Testa se o campo é NULL
pg_field_name -- Retorna o nome de um campo
pg_field_num -- Retorna o número do campo referido
pg_field_prtlen -- Retorna o comprimento impresso
pg_field_size --  Retorna o tamanho de armazenamento interno de um campo
pg_field_type --  Retorna o nome do tipo para o campo de nome correspondente
pg_free_result -- Libera a memória usada pelo resultado
pg_get_notify -- Ping database connection
pg_get_pid -- Ping database connection
pg_get_result --  Retorna o resultado de uma consulta (query) assíncrona
pg_host --  Retorna o nome da máquina associada a uma conexão
pg_insert --  Insere um array na tabela
pg_last_error -- Retorna a string da última mensagem de erro de uma conexão
pg_last_notice --  Retorna a última notificação do servidor PostgreSQL
pg_last_oid -- Retorna o último oid do objeto
pg_lo_close -- Fecha um objeto grande (large object)
pg_lo_create -- Cria um objeto grande (large object)
pg_lo_export -- Exporta um objeto grande (large object) para um arquivo
pg_lo_import -- Importa um objeto grande (large object) a partir de um arquivo
pg_lo_open -- Abre um objeto grande (large object)
pg_lo_read_all --  Lê um objeto grande (large object) inteiro e o envia diretamente para o navegador
pg_lo_read -- Lê um objeto grande (large object)
pg_lo_seek --  Procura uma posição em um objeto grande (large object)
pg_lo_tell --  Retorna a posição atual de um objeto grande (large object)
pg_lo_unlink -- Remove um objeto grande (large object)
pg_lo_write -- Escreve em um objeto grande (large object)
pg_metadata --  Retorna os metadados da tabela.
pg_num_fields -- Retorna o número de campos
pg_num_rows -- Retorna o número de linhas
pg_options -- Retorna as opções associadas com a conexão
pg_pconnect -- Abre uma conexão PostgreSQL persistente
pg_ping -- Faz um ping na conexão com o banco de dados
pg_port --  Retorna o número da porta associada com a conexão.
pg_put_line -- Envia uma string terminada em NULL para o backend PostgreSQL
pg_query -- Executa uma consulta (query)
pg_result_error --  Retorna a mensagem de erro associada a um resultado
pg_result_seek -- Altera a posição do ponteiro interno de um recurso (resource) de resultado
pg_result_status --  Retorna o status do resultado da consulta (query)
pg_select --  Seleciona registros.
pg_send_query --  Envia uma consulta (query) assincrona
pg_set_client_encoding --  Define a codificação do cliente
pg_trace -- Habilita rastreamento em uma conexão PostgreSQL
pg_tty --  Retorna o nome da tty associada com a conexão
pg_unescape_bytea --  Faz escape binário para o tipo bytea
pg_untrace -- Desabilita o rastreamento de uma conexão PostgreSQL
pg_update --  Atualiza uma tabela.

pg_affected_rows

(PHP 4 >= 4.2.0)

pg_affected_rows -- Retorna o número de registros afetados (linhas)

Descrição

int pg_affected_rows ( resource result)

pg_affected_rows() retorna o número de linhas (instâncias/registros/linhas) afetados por consultas (queries) INSERT, UPDATE e DELETE executados por pg_query(). Se nenhuma linha foi afetada, ela retornará 0.

Exemplo 1. pg_affected_rows()

<?php
     $result = pg_query ($conn, "INSERT INTO publisher VALUES ('Author')");
     $cmdtuples = pg_affected_rows ($result);
     echo $cmdtuples . " linhas foram afetadas.";
?>

Nota: Esta função costumava ser chamada de pg_cmdtuples().

Veja também pg_query() e pg_num_rows().

pg_cancel_query

(PHP 4 >= 4.2.0)

pg_cancel_query --  Cancela uma consulta (query) assíncrona

Descrição

bool pg_cancel_query ( resource connection)

pg_cancel_query() cancela uma consulta (query) assíncrona enviada por pg_send_query(). Você não pode cancelar uma consulta executada por pg_query().

Veja também pg_send_query() e pg_connection_busy()

pg_client_encoding

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

pg_client_encoding --  Retorna a codificação do cliente

Descrição

string pg_client_encoding ( [resource connection])

pg_client_encoding() retorna a codificação do cliente como uma string. A string de retorno pode ser SQL_ASCII, EUC_JP, EUC_CN, EUC_KR, EUC_TW, UNICODE, MULE_INTERNAL, LATINX (X=1...9), KOI8, WIN, ALT, SJIS, BIG5, WIN1250.

Nota: Esta função requer PHP 4.0.3 ou maior e PostgreSQL 7.0 ou maior Se a libpq foi compilada sem suporte a codificação multibyte, pg_set_client_encoding() sempre retornará "SQL_ASCII". As codificações suportadas dependem da versão do PostgreSQL. Vide o manual do PostgreSQL para mais detalhes sobre como habilitar o suporte a multibyte e outras codificações.

Esta função costumava ser chamada pg_clientencoding().

Veja também pg_set_client_encoding().

pg_close

(PHP 3, PHP 4 )

pg_close -- Fecha uma conexão PostgreSQL

Descrição

bool pg_close ( resource connection)

pg_close() fecha a conexão não persistente com servidor de banco de dados PostgreSQL associado ao recurso (resource) connection dado. Retorna TRUE em caso de sucesso ou FALSE em falhas.

Nota: Normalmente, o uso de pg_close() não é necessário já que conexões não persistentes abertas são automaticamente fechadas ao final do processamento do script.

Se existem recursos (resource) de objetos grandes (large objects) abertos na conexão, não feche a conexão antes de fechar todos os recursos relacionados com estes objetos.

pg_connect

(PHP 3, PHP 4 )

pg_connect -- Abre uma conexão PostgreSQL

Descrição

resource pg_connect ( string connection_string)

pg_connect() retorna um recurso (resource) de conexão que é necessário para outras funções para PostgreSQL.

pg_connect() abre uma conexão com um servidor de banco de dados PostgreSQL especificado por connection_string. Retorna um recurso (resource) de conexão em caso de sucesso. Retorna FALSE se a conexão não pôde ser estabelecida. connection_string deve ser uma string entre aspas duplas.

Exemplo 1. Usando pg_connect

<?php
$bdcon = pg_connect ("dbname=flavia");
//conecta a um banco de dados chamado "flavia"
$bdcon2 = pg_connect ("host=localhost port=5432 dbname=flavia");
// conecta a um banco de dados chamado "flavia" em "localhost" na porta "5432"
$bdcon3 = pg_connect ("host=ovelha port=5432 dbname=flavia user=ze password=buu");
//conecta a um banco de dados chamado "flavia" na máquina "ovelha" com um usuário e senha
$con_string = "host=ovelha port=5432 dbname=flavia user=ze password=buu";
$bdcon4 = pg_connect ($con_string);
//coneta a um banco de dados chamado "flavia" na máquina "ovelha" com um usuário e senha
?>
Os argumentos disponíveis para connection_string incluem host, port, tty, options, dbname, user e password.

Se uma segunda chamada é feita para pg_connect() com a mesma connection_string, nenhuma nova conexão será estabelecida, ao invés disso, o recurso (resource) de conexão da conexão que já está aberta será retornado. Você pode ter multiplas conexões para o mesmo banco de dados se você usar diferentes strings de conexão.

A sintaxe antiga com parâmetros múltiplos $con = pg_connect ("host", "port", "options", "tty", "dbname") se tornou obsoleta.

Veja também pg_pconnect(), pg_close(), pg_host(), pg_port(), pg_tty(), pg_options() e pg_dbname().

pg_connection_busy

(PHP 4 >= 4.2.0)

pg_connection_busy --  Verifica se a conexão está ocupada ou não

Descrição

bool pg_connection_busy ( resource connection)

pg_connection_busy() retorna TRUE se a conexão está ocupada. Se estiver ocupada, significa que uma consulta (query) anterior ainda está sendo executada. Se pg_get_result() for chamada, será bloqueada.

Veja também pg_connection_status() e pg_get_result()

pg_connection_reset

(PHP 4 >= 4.2.0)

pg_connection_reset --  Reinicia uma conexão (reconecta)

Descrição

bool pg_connection_reset ( resource connection)

pg_connection_reset() reinicia uma conexão. É útil para recuperação de erros. Retorna TRUE em caso de sucesso ou FALSE em falhas.

Veja também pg_connect(), pg_pconnect() e pg_connection_status()

pg_connection_status

(PHP 4 >= 4.2.0)

pg_connection_status --  Retorna o status da conexão

Descrição

int pg_connection_status ( resource connection)

pg_connection_status() retorna o status da conexão. Os status possíveis são PGSQL_CONNECTION_OK e PGSQL_CONNECTION_BAD.

Veja também pg_connection_busy().

pg_convert

(PHP 4 >= 4.3.0)

pg_convert --  Converte os valores de um array associativo em uma declaração SQL apropriada.

Descrição

array pg_convert ( resource connection, string table_name, array assoc_array [, int options])

pg_convert() checa e converte assoc_array em uma declaração SQL apropriada.

Nota: Esta função é experimental.

Veja também pg_metadata()

pg_copy_from

(PHP 4 >= 4.2.0)

pg_copy_from --  Insere registros em uma tabela a partir de um array

Descrição

bool pg_copy_from ( resource connection, string table_name, array rows [, string delimiter [, string null_as]])

pg_copy_from() insere registros em uma tabela a partir de rows. Usa o comando interno COPY FROM para inserir registros. Retorna TRUE em caso de sucesso ou FALSE em falhas.

Veja também pg_copy_to()

pg_copy_to

(PHP 4 >= 4.2.0)

pg_copy_to --  Copia uma tabela em um array

Descrição

int pg_copy_to ( resource connection, string table_name [, string delimiter [, string null_as]])

pg_copy_to() copia uma tabela em um array. Utiliza internamente o comando SQL COPY TO para inserir os registros. Seu retorno é o array resultante. Caso haja falhas, FALSE é retornado.

Veja também pg_copy_from()

pg_dbname

(PHP 3, PHP 4 )

pg_dbname -- Retorna o nome do banco de dados

Descrição

string pg_dbname ( resource connection)

pg_dbname() retorna o nome do banco de dados para um dado recurso (resource) de conexão connection. Retorna FALSE, se connection não é um recurso de conexão PostgreSQL válido.

pg_delete

(PHP 4 >= 4.3.0)

pg_delete --  Remove registros.

Descrição

long pg_delete ( resource connection, string table_name, array assoc_array [, int options])

pg_delete() remove registros que seguem a condição especificada por assoc_array que tem o formato campo => valor. Se options for especificado, pg_convert() é aplicada a assoc_array com a opção especificada.

Exemplo 1. pg_delete

<?php 
    $db = pg_connect ('dbname=flavia');
    // Isto é seguro, já que $_POST é convertido automaticamente
    $res = pg_delete($db, 'post_log', $_POST);
    if ($res) {
        echo "Dados de POST foram removidos: $res\n";
    } else {
        echo "O usuário deve ter enviado parâmetros inválidos\n";
    }
?>

Nota: Esta função é experimental.

Veja também pg_convert()

pg_end_copy

(PHP 4 >= 4.0.3)

pg_end_copy -- Sincroniza com o backend PostgreSQL

Descrição

bool pg_end_copy ( [resource connection])

pg_end_copy() sincroniza o frontend PostgreSQL (geralmente um processo de servidor HTTP) com o servidor PostgreSQL depois de fazer uma operação de cópia usando pg_put_line(). pg_end_copy() deve ser chamada, caso contrário o servidor PostgreSQL pode perder a sincronia com o frontend fazendo com que o servidor gere um erro. Retorna TRUE em caso de sucesso ou FALSE em falhas.

Para maiores detalhes e um exemplo, veja também pg_put_line().

pg_escape_bytea

(PHP 4 >= 4.2.0)

pg_escape_bytea --  Gera binários para o tipo bytea

Descrição

string pg_escape_bytea ( string data)

pg_escape_bytea() gera uma string do tipo bytea. Retorna uma string com escapes.

Nota: Quando você usa SELECT bytea type, o PostgreSQL retorna valores de byte octais prefixados por \ (ex.: \032). Usuários devem converter de volta para binários por si mesmos.

Esta função exige PostgreSQL 7.2 ou superior. Com PostgreSQL 7.2.0 e 7.2.1, o tipo de dados bytea deve ser criado quando você habilita o suporte a multi-byte. Por exemplo, INSERT INTO tabela_teste (imagem) VALUES ('$imagem_escaped'::bytea); PostgreSQL 7.2.2 ou superior não precisa de coerção (cast). A exceção é quando a codificação de caracteres do cliente e do backend não combinam, então pode haver erro de fluxo de multi-byte. O usuário deve fazer a coerção (cast) para bytea para evitar este erro.

Versões do PostgreSQL mais novas suportarão a função unescape. Suporte para a função interna unescape será adicionada assim que estiver disponível.

Veja também pg_escape_string()

pg_escape_string

(PHP 4 >= 4.2.0)

pg_escape_string --  Gera string para o tipo text/char

Descrição

string pg_escape_string ( string data)

pg_escape_string() gera strings do tipo text/chat. Retorna uma string com escapes para PostgreSQL. O uso desta função é recomendado no lugar de addslashes().

Nota: Esta função exige PostgreSQL 7.2 ou superior.

Veja também pg_escape_bytea()

pg_fetch_all

(PHP 4 >= 4.3.0)

pg_fetch_all -- Retorna todas as linhas (registros) como um array

Descrição

array pg_fetch_all ( resource result [, int row])

pg_fetch_all() retorna uma array que contém todas as linhas (registros) do recurso (resourse) de resultado. Retorna FALSE, se não existem mais registros.

Veja também pg_fetch_row(), pg_fetch_array(), pg_fetch_object() e pg_fetch_result().

Exemplo 1. Retornando linhas (registros) no PostgreSQL

<?php 
$conn = pg_pconnect ("dbname=escritor");
if (!$conn) {
    echo "Ocorreu um erro!\n";
    exit;
}

$result = pg_query ($conn, "SELECT * FROM authors");
if (!$result) {
    echo "Ocorreu um erro!\n";
    exit;
}

$arr = pg_fetch_all ($result, 0, PGSQL_NUM);

var_dump($arr);

?>

pg_fetch_array

(PHP 3>= 3.0.1, PHP 4 )

pg_fetch_array -- Retorna uma linha (registro) como um array

Descrição

array pg_fetch_array ( resource result [, int row [, int result_type]])

pg_fetch_array() retorna um array que corresponde à linha (registro). Retorna FALSE se não existem mais linhas.

pg_fetch_array() é uma versão extendida de pg_fetch_row(). Além de armazenar os dados em índices numéricos (índice) no array resultante, também armazena os dados em chaves associativas (nome do campo) por padrão.

row é o número da linha (registro) a ser recuperado. A primeira linha é 0.

result_type é um parâmetro opcional que controla como o valor de retorno é iniciado. result_type é uma constante e pode ter os seguintes valores: PGSQL_ASSOC, PGSQL_NUM, e PGSQL_BOTH. pg_fetch_array() retorna um array associativo que tem o nome de campo como chave para PGSQL_ASSOC. Índice de campo como chave com PGSQL_NUM e ambos nome/índice numérico como chave com PGSQL_BOTH. O valor padrão é PGSQL_BOTH.

Nota: O parâmetro result_type foi adicionado no PHP 4.0.

pg_fetch_array() NÃO é significativamente mais lenta que pg_fetch_row(), e ainda fornece uma significativa facilidade de uso.

Veja também pg_fetch_row(), pg_fetch_object() e pg_fetch_result().

Exemplo 1. Retornando linhas (registros) no PostgreSQL

<?php 
$conn = pg_pconnect ("dbname=publicar");
if (!$conn) {
    echo "Um erro ocorreu.\n";
    exit;
}

$result = pg_query ($conn, "SELECT * FROM autores");
if (!$result) {
    echo "Um erro ororreu.\n";
    exit;
}

$arr = pg_fetch_array ($result, 0, PGSQL_NUM);
echo $arr[0] . " <- array\n";

$arr = pg_fetch_array ($result, 1, PGSQL_ASSOC);
echo $arr["autor"] . " <- array\n";
?>

Nota: A partir do PHP 4.1.0, row tornou-se opcional. A chamada pg_fetch_array() irá incrementar o contador de linha interno em 1.

pg_fetch_assoc

(PHP 4 >= 4.3.0)

pg_fetch_assoc -- Retorna uma linha (registro) como um array

Descrição

array pg_fetch_assoc ( resource result [, int row])

pg_fetch_assoc() retorna um array associativo que corresponde à linha (registro) recuperado. Retorna FALSE, se não houver mais registros.

pg_fetch_assoc() é uma versão extendida de pg_fetch_row(). Além de guardar em índices numéricos, no array resultante, também guarda dados em arrays com chaves associativas (nome do campo) por padrão.

row é o número da linha (registro) a ser recuperado. A primeira linha é 0.

pg_fetch_assoc() NÃO é significativamente mais lenta que pg_fetch_row(), e ainda fornece uma significativa facilidade de uso.

Veja também pg_fetch_row(), pg_fetch_array(), pg_fetch_object() e pg_fetch_result().

Exemplo 1. Retornando linhas (registros) no PostgreSQL

<?php 
$conn = pg_pconnect ("dbname=revista");
if (!$conn) {
    echo "Ocorreu um erro.\n";
    exit;
}

$result = pg_query ($conn, "SELECT * FROM authors");
if (!$result) {
    echo "Ocorreu um erro.\n";
    exit;
}

$arr = pg_fetch_assoc ($result, 1, PGSQL_ASSOC);
echo $arr["author"] . " <- array\n";
?>

pg_fetch_object

(PHP 3>= 3.0.1, PHP 4 )

pg_fetch_object -- Retorna uma linha (registro) como um objeto

Descrição

objeto pg_fetch_object ( resource result, int row [, int result_type])

pg_fetch_object() retorna um objeto com propriedades que correspondem à linha recuperada. Retorna FALSE se não existem mais linhas ou no caso de erro.

pg_fetch_object() é similar a pg_fetch_array(), com uma diferença - um objeto é retornado, ao invés de um array. Indiretamente, isto significa que você pode acessar os dados somente através dos nomes de campos, e não por seus índices (números são nomes inválidos de propriedades).

row é o número da linha (registro) a ser recuperada. A primeira linha é 0.

Em termos de performance, a função é idêntica a pg_fetch_array(), e quase tão rápida quanto pg_fetch_row() (a diferença é insignificante).

Nota: A partir do PHP 4.1.0, row é opcional.

A partir do PHP 4.3.0, result_type tem PGSQL_ASSOC como valor padrão, enquanto em outras versões mais antigas o padrão é PGSQL_BOTH. Não há utilidade para a propriedade numérica, já que nomes de propriedades numéricas são inválidas em PHP.

O parâmetro result_type deverá ser removido em versões futuras.

Veja também pg_query(), pg_fetch_array(), pg_fetch_row() e pg_fetch_result().

Exemplo 1. Postgres fetch object

<?php 
$database = "verlag";
$db_conn = pg_connect ("host=localhost port=5432 dbname=$database");
if (!$db_conn): ?>
    <H1>Falha ao conectar com o banco de dados PostgreSQL <?php echo $database ?></H1> <?php
    exit;
endif;

$qu = pg_query ($db_conn, "SELECT * FROM verlag ORDER BY autor");
$row = 0; // postgresql precisa de um contador de linha, outros dbs talvez não precisem

while ($data = pg_fetch_object ($qu, $row)) {
    echo $data->autor." (";
    echo $data->jahr ."): ";
    echo $data->titel."<BR>";
    $row++;
}
?>
<PRE>
<?php
$fields[] = Array ("autor", "Autor");
$fields[] = Array ("jahr",  "  Ano");
$fields[] = Array ("titel", " Título");

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

Nota: A partir do PHP 4.1.0, row tornou-se opcional. Ao chamar pg_fetch_object() o contador de linhas interno será acrescentado de 1.

pg_fetch_result

(PHP 4 >= 4.2.0)

pg_fetch_result -- Retorna valores a partir de um recurso (resource) de resultado

Descrição

misto pg_fetch_result ( resource result, int row, mixed field)

pg_fetch_result() retorna valores a partir de um recurso (resource) de resultado result criado por pg_query(). row é um inteiro. field é um nome de campo (string) ou um índice de campo (inteiro). row e field especificam que célula da tabela deve ser recuperada. A numeração de linhas começa de 0. Ao invés de nomear o campo, você pode usar o índice numérico de campo sem aspas. Índices de campo iniciam-se em 0.

PostgreSQL tem muitos tipos internos mas apenas os tipos básicos são suportados. Todas as formas de tipo integer são retornadas como valores integer. Todas as formas de tipos reais (ponto flutuante) são retornados como valores float. Boolean é retornado como "t" ou "f". Todos os outros tipos, incluindo arrays, são retornados como strings formatadas na mesma maneira padrão que o PostgreSQL retornaria com o programa psql.

pg_fetch_row

(PHP 3>= 3.0.1, PHP 4 )

pg_fetch_row -- Retorna uma linha como um array enumerado

Descrição

array pg_fetch_row ( resource result, int row)

pg_fetch_row() retorna uma linha de dados a partir do resultado associado com o recurso (resource) de resultado result. A linha (registro) é recuperada como um array. Cada coluna do resultado é armazenada em um índice do array, iniciando-se no índice 0.

Retorna um array que corresponde à linha carregada, ou FALSE se não existem mais linhas.

Veja também pg_query(), pg_fetch_array(), pg_fetch_object() e pg_fetch_result().

Exemplo 1. Retornando linhas (registros) no PostgreSQL

<?php 
$conn = pg_pconnect ("dbname=editora");
if (!$conn) {
    echo "Um erro ocorreu.\n";
    exit;
}

$result = pg_query ($conn, "SELECT * FROM autores");
if (!$result) {
    echo "Um erro ocorreu.\n";
    exit;
}

$num = pg_num_rows($result); 

for ($i=0; $i < $num; $i++) {
  $r = pg_fetch_row($result, $i);

  for ($j=0; $j < count($r); $j++) {
    echo "$r[$j]&nbsp;";
  }

  echo "<BR>";

}
 
?>

Nota: A partir do PHP 4.1.0, row tornou-se opcional. Ao chamar pg_fetch_row(), o contador de linha interno será incrementado em 1.

pg_field_is_null

(PHP 4 >= 4.2.0)

pg_field_is_null -- Testa se o campo é NULL

Descrição

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

pg_field_is_null() testa se um campo é NULL ou não. Retorna 1 se o campo na linha dada é NULL. Retorna 0 se o campo na linha dada NÃO é NULL. O campo pode ser especificado como um índice de coluna (número) ou como o nome de um campo (string). A numeração de linhas inicia-se em 0.

Nota: Esta função era chamada pg_fieldisnull().

pg_field_name

(PHP 4 >= 4.2.0)

pg_field_name -- Retorna o nome de um campo

Descrição

string pg_field_name ( resource result, int field_number)

pg_field_name() retorna o nome do campo ocupando o campo de número igual a field_number no recurso (resource) de resultado result. A numeração de campo inicia-se em 0.

Nota: Esta função era chamada pg_fieldname().

Veja também pg_field_num().

pg_field_num

(PHP 4 >= 4.2.0)

pg_field_num -- Retorna o número do campo referido

Descrição

int pg_field_num ( resource result, string field_name)

pg_field_num() irá retornar o número da vaga (slot) da coluna (campo) que corresponde a field_name no recurso (resource) de resultado result. A numeração de campo inicia-se em 0. Esta função retornará -1 em caso de erro.

Nota: Esta função era chamada pg_fieldnum().

Veja também pg_field_name().

pg_field_prtlen

(PHP 4 >= 4.2.0)

pg_field_prtlen -- Retorna o comprimento impresso

Descrição

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

pg_field_prtlen() retorna o comprimento atual impresso (número de caracteres) de um valor especificado em um recurso (resource) de resultado result. A numeração de linha inicia-se em 0. Esta função retornará -1 em caso de erro.

Nota: Esta função era chamada pg_field_prtlen().

Veja também pg_field_size().

pg_field_size

(PHP 4 >= 4.2.0)

pg_field_size --  Retorna o tamanho de armazenamento interno de um campo

Descrição

int pg_field_size ( resource result, int field_number)

pg_field_size() retorna o tamanho de armazenamento interno (em bytes) do número de campo do recurso (resource) de resultado result. A numeração de campo inicia-se em 0. Um campo de tamanho -1 indica um campo de tamanho variável. Esta função retornará FALSE em caso de erro.

Nota: Esta função era chamada pg_fieldsize().

Veja também pg_field_len() e pg_field_type().

pg_field_type

(PHP 4 >= 4.2.0)

pg_field_type --  Retorna o nome do tipo para o campo de nome correspondente

Descrição

string pg_field_type ( resource result, int field_number)

pg_field_type() retorna uma string contendo o nome do tipo do campo de número field_number dado no recurso (resource) de resultado result. A numeração de campo inicia-se em 0.

Nota: Esta função era chamada pg_fieldtype().

Veja também pg_field_len() e pg_field_name().

pg_free_result

(PHP 4 >= 4.2.0)

pg_free_result -- Libera a memória usada pelo resultado

Descrição

bool pg_free_result ( resource result)

pg_free_result() precisa ser usada apenas se você está preocupado em usar muita memória enquanto seu script está rodando. Todos os resultados serão liberados da memória automaticamente assim que o script terminar de executar. Mas, se você tem certeza que não precisará mais dos dados do resultado em um script, você pode chamar pg_free_result() com o recurso (resource) de resultado result como argumento e a memória ocupada pelo resultado associado será liberada. Retorna TRUE em caso de sucesso ou FALSE em falhas.

Nota: Esta função era chamada pg_field_len().

Veja também pg_query().

pg_get_notify

(PHP 4 >= 4.3.0)

pg_get_notify -- Ping database connection

Description

array pg_get_notify ( resource connection [, int result_type])

pg_get_notify() gets notify message sent by NOTIFY SQL command. To recieve nofigy messages, LISTEN SQL command must be issued. If there is notify message on the connection, array contains message name and backend PID is returned. If there is no message, FALSE is returned.

See also pg_get_pid()

Exemplo 1. PostgreSQL NOTIFY message

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

// Listen 'author_updated' message from other processes
pq_query($conn, 'LISTEN author_updated;');
$notify = pg_get_notify($conn);
if (!$notify)
    print("No messages\n");
else
    print_r($notify);
?>

pg_get_pid

(PHP 4 >= 4.3.0)

pg_get_pid -- Ping database connection

Description

int pg_get_pid ( resource connection)

pg_get_pid() gets backend (database server process) PID. PID is useful to check if NOTIFY message is sent from other process or not.

See also pg_get_notify()

Exemplo 1. PostgreSQL backend PID

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

// Backend process PID. Use PID with pg_get_notify()
$pid = pg_get_pid($conn);
?>

pg_get_result

(PHP 4 >= 4.2.0)

pg_get_result --  Retorna o resultado de uma consulta (query) assíncrona

Descrição

resource pg_get_result ( [resource connection])

pg_get_result() retorna o recurso (resource) de resultado de uma consulta (query) executada por ps_send_query(). pg_send_query() pode enviar múltiplas consultas (queries) ao servidor PostgreSQL e pg_get_result() é usada para carregar os resultados das consultas, um por um. Retorna o recurso (resource) de resultado. Se não houverem mais resultados, retorna FALSE.

pg_host

(PHP 3, PHP 4 )

pg_host --  Retorna o nome da máquina associada a uma conexão

Descrição

string pg_host ( resource connection)

pg_host() retorna o nome da máquina com a qual o recurso (resource) de conexão connection está conectado.

Veja também pg_connect() e pg_pconnect().

pg_insert

(PHP 4 >= 4.3.0)

pg_insert --  Insere um array na tabela

Descrição

bool pg_insert ( resource connection, string table_name, array assoc_array [, int options])

pg_insert() insere o array assoc_array, que contém os pares campo => valor, na tabela especificada pelo parâmetro table_name. Se options for especificado, pg_convert() será aplicada à assoc_array com a opção especificada.

Exemplo 1. pg_insert

<?php 
    $db = pg_connect ('dbname=meubanco');
    // Isto é seguro uma vez que $_POST é convertido automaticamente 
    $res = pg_insert($db, 'post_log', $_POST);
    if ($res) {
        echo "Dados POST arquivados com sucesso\n";
    }
    else {
        echo "O usuário deve ter inserido entradas inválidas\n";
    }
?>

Nota: Esta função é experimental.

Veja também pg_convert()

pg_last_error

(PHP 4 >= 4.2.0)

pg_last_error -- Retorna a string da última mensagem de erro de uma conexão

Descrição

string pg_last_error ( resource connection)

pg_last_error() retorna a última mensagem de erro para a conexão representada por connection.

As mensagens de erro podem ser sobrescritas por chamadas internas ao PostgreSQL(libpq). Se múltiplos erros ocorrerem dentro de um módulo de função do PostgreSQL, pode não retornar a mensagem de erro correta.

Use pg_result_error(), pg_result_status() e pg_connection_status() para um melhor tratamento de erros.

Nota: Esta função era chamada pg_errormessage().

Veja também pg_result_error().

pg_last_notice

(PHP 4 >= 4.0.6)

pg_last_notice --  Retorna a última notificação do servidor PostgreSQL

Descrição

string pg_last_notice ( resource connection)

pg_last_notice() retorna a última notificação do servidor PostgreSQL especificada por connection. O servidor PostgreSQL envia notificações em diversas situações, por exemplo, se as transações não puderem continuar. Com pg_last_notice() você pode evitar a chamada de consultas (queries) inúteis, checando quando a notificação está relacionada ou não com a transação.

Atenção

Esta função é EXPERIMENTAL e ainda não está completamente implementada. pg_last_notice() foi adicionada no PHP 4.0.6. Entretanto o PHP 4.0.6 tem problemas com a manipulação de mensagens. O uso do módulo PostgreSQL com o PHP 4.0.6 não é recomendada, mesmo se você não estiver usando pg_last_notice().

Esta função está totalmente implementada no PHP 4.3.0. Versões do PHP mais recentes que a 4.3.0 ignoram o parâmetro de conexão com o banco de dados.

O rastreamento de notificações pode ser definido como opcional definindo 1 para a diretiva pgsql.ignore_notice do PHP 4.3.0.

O arquivamento (log) de mensagems pode ser pode ser definido como opcional mudando para 0 a diretiva pgsql.log_notice no PHP 4.3.0. A não ser que pgsql.ignore_notice estiver definida para 0, notificações não podem ser arquivadas.

Veja também pg_query() e pg_last_error().

pg_last_oid

(PHP 4 >= 4.2.0)

pg_last_oid -- Retorna o último oid do objeto

Descrição

int pg_last_oid ( resource result)

pg_last_oid() é usado para recuperar o oid designado a uma linha (registro) se o recurso (resource) de resultado é usado a partir do último comando enviado através de pq_query() se este comando era um INSERT do SQL. Retorna um inteiro positivo se havia um oid válido. Retorna FALSE se um erro ocorrer ou o último comando enviado através de pg_query() não foi INSERT ou se o INSERT falhou.

O campo OID tornou-se opcional a partir do PostgreSQL 7.2. Quando um campo OID não é definido em uma tabela, o programador deve usar pg_result_status() para checar se o registro foi inserido com sucesso ou não.

Nota: Esta função era chamada pg_getlastoid().

Veja também pg_query() e pg_result_status()

pg_lo_close

(PHP 4 >= 4.2.0)

pg_lo_close -- Fecha um objeto grande (large object)

Descrição

bool pg_lo_close ( resource large_object)

pg_lo_close() fecha um Objeto Grande (Large Object, daí vem o "lo" que integra o nome da função). large_object é um recurso (resource) para o objeto grande gerado a partir de pg_lo_open().

Para usar a interface de objetos grandes (lo), é necessário encapsulá-lo em um bloco de transação.

Nota: Esta função era chamada pg_loclose().

Veja também pg_lo_open(), pg_lo_create() e pg_lo_import().

pg_lo_create

(PHP 4 >= 4.2.0)

pg_lo_create -- Cria um objeto grande (large object)

Descrição

int pg_lo_create ( resource connection)

pg_lo_create() cria um Objeto Grande (Large Object) e retorna o seu oid. connection especifica uma conexão a um banco de dados válida aberta por pg_connect() ou pg_pconnect(). Os modos de acesso INV_READ, INV_WRITE e INV_ARCHIVE não são suportados, o objeto é criado sempre com acesso a leitura e escrita. INV_ARCHIVE foi removido do próprio PostgreSQL (a partir da 6.3). Retorna o oid do objeto. Retorna FALSE se um erro ocorrer.

Para usar a interface de objetos grandes (lo), é necessário encapsulá-lo em um bloco de transação.

Nota: Esta função era chamada pg_locreate().

pg_lo_export

(PHP 4 >= 4.2.0)

pg_lo_export -- Exporta um objeto grande (large object) para um arquivo

Descrição

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

O argumento oid especifica o oid do objeto grande (large object) a exportar e o argumento pathname especifica o caminho até o arquivo. Retorna FALSE se um erro ocorrer, caso contrário retorna TRUE.

Para usar a interface de objetos grandes (lo), é necessário encapsulá-lo em um bloco de transação.

Nota: Esta função era chamada pg_loexport().

Veja também pg_lo_import().

pg_lo_import

(PHP 4 >= 4.2.0)

pg_lo_import -- Importa um objeto grande (large object) a partir de um arquivo

Descrição

int pg_lo_import ( [resource connection, string pathname])

Em versões anteriores a 4.2.0, a sintaxe desta função é diferente, veja a seguinte definição:

int pg_lo_import ( string pathname [, resource connection])

O argumento pathname especifica o caminho do arquivo a ser importado como um objeto grande (large object). Retorna FALSE se um erro ocorrer, caso contrário, retorna o oid do objeto recém criado.

Para usar a interface de objetos grandes (lo) é necessário encapsulá-lo em um bloco de transação.

Nota: Quando o safe-mode está ativo, o PHP verifica se o(s) arquivo(s) e/ou diretório(s) que serão afetados por esta operação tem o mesmo UID (proprietário) do script que está sendo executado.

Nota: Esta função era chamada pg_loimport().

Veja também pg_lo_export() e pg_lo_open().

pg_lo_open

(PHP 4 >= 4.2.0)

pg_lo_open -- Abre um objeto grande (large object)

Descrição

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

pg_lo_open() abre um Objeto Grande (Large Object em inglês, daí o "lo"). O recurso (resource) encapsula informações sobre a conexão. oid especifica um oid de objeto grande válido e o parâmetro mode pode ser "r", "w" ou "rw". A função retorna FALSE se houver algum erro.

Atenção

Não feche a conexão com o banco de dados sem antes fechar a conexão com o objeto grande.

Para usar a interface de objetos grandes (lo) é necessário encapsulá-lo em um bloco de transação.

Nota: Esta função era chamada pg_loopen().

Veja também pg_lo_close() e pg_lo_create().

pg_lo_read_all

(PHP 4 >= 4.2.0)

pg_lo_read_all --  Lê um objeto grande (large object) inteiro e o envia diretamente para o navegador

Descrição

int pg_lo_read_all ( resource large_object)

pg_lo_read_all() lê um objeto grande (large object) e passa-o diretamente para o navegador depois de enviar todos os cabeçalhos pendentes. A intenção principal é enviar dados binários como imagens ou som. Retorna o número de bytes lidos ou FALSE se ocorrer algum erro.

Para usar a interface de objetos grandes (lo) é necessário encapsulá-lo em um bloco de transação.

Nota: Esta função era chamada pg_loreadall().

Veja também pg_lo_read().

pg_lo_read

(PHP 4 >= 4.2.0)

pg_lo_read -- Lê um objeto grande (large object)

Descrição

string pg_lo_read ( resource large_object, int len)

pg_lo_read() lê o número de bytes equivalente ao valor de len de um objeto grande (large object) e retorna-o como uma string. large_object especifica um recurso (resource) válido de objeto e len especifica o tamanho máximo permitido do segmento do objeto grande. Retorna FALSE se algum erro acontecer.

Para usar a interface de objetos grandes (lo) é necessário encapsulá-lo em um bloco de transação.

Nota: Esta função era chamada pg_loread().

Veja também pg_lo_read_all().

pg_lo_seek

(PHP 4 >= 4.2.0)

pg_lo_seek --  Procura uma posição em um objeto grande (large object)

Descrição

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

pg_lo_seek() procura uma posição em um recurso (resource) de um objeto grande (large objet). whence pode ser PGSQL_SEEK_SET, PGSQL_SSEK_CUR ou PGSQL_SEEK_END.

Veja também pg_lo_tell().

pg_lo_tell

(PHP 4 >= 4.2.0)

pg_lo_tell --  Retorna a posição atual de um objeto grande (large object)

Descrição

int pg_lo_tell ( resource large_object)

pg_lo_tell() retorna a posição atual (deslocamento a partir do início do objeto grande).

Veja também pg_lo_seek().

pg_lo_unlink

(PHP 4 >= 4.2.0)

pg_lo_unlink -- Remove um objeto grande (large object)

Descrição

bool pg_lo_unlink ( resource connection, int oid)

pg_lo_unlink() remove um objeto grande (large object) com um determinado oid. Retorna TRUE em caso de sucesso ou FALSE em falhas.

Para usar a interface de objetos grandes (lo) é necessário encapsulá-lo em um bloco de transação.

Nota: Esta função era chamada pg_lo_unlink().

Veja também pg_lo_create() e pg_lo_import().

pg_lo_write

(PHP 4 >= 4.2.0)

pg_lo_write -- Escreve em um objeto grande (large object)

Descrição

int pg_lo_write ( resource large_object, string data)

pg_lo_write() escreve em um objeto grande (large object) a partir de uma variável data e retorna o número de bytes escritos, ou FALSE em caso de erro. large_object é um recurso (resource) de objeto grande criado a partir de pg_lo_open().

Para usar a interface de objetos grandes (lo) é necessário encapsulá-lo em um bloco de transação.

Nota: Esta função era chamada pg_lo_write().

Veja também pg_lo_create() e pg_lo_open().

pg_metadata

(no version information, might be only in CVS)

pg_metadata --  Retorna os metadados da tabela.

Descrição

array pg_metadata ( resource connection, string table_name)

pg_metadata() retorna a definição da tabela com o nome igual ao valor de table_name como um array. Se houver algum erro, retorna FALSE.

Nota: Esta função é experimental.

Veja também pg_convert()

pg_num_fields

(PHP 4 >= 4.2.0)

pg_num_fields -- Retorna o número de campos

Descrição

int pg_num_fields ( resource result)

pg_num_fields() retorna o número de campos (colunas) do recurso (resource) de resultado result. O argumento é um recurso (resource) de resultado criado a partir de pg_query(). Esta função irá retornar -1 em caso de erro.

Nota: Esta função era chamada pg_numfields().

Veja também pg_num_rows() e pg_affected_rows().

pg_num_rows

(PHP 4 >= 4.2.0)

pg_num_rows -- Retorna o número de linhas

Descrição

int pg_num_rows ( resource result)

pg_num_rows() irá retornar o número de linhas do recurso de resultado result. result é um recurso (resource) de resultado de consulta (query) feito por pg_query(). Esta função retornará -1 em caso de erro.

Nota: Use pg_affected_rows() para obter o número de linhas afetadas por consultas do tipo INSERT, UPDATE e DELETE.

Nota: Esta função era chamada pg_numrows().

Veja também pg_num_fields() e pg_affected_rows().

pg_options

(PHP 3, PHP 4 )

pg_options -- Retorna as opções associadas com a conexão

Descrição

string pg_options ( resource connection)

pg_options() retornará uma string contendo as opções especificadas no recurso (resource) de conexão PostgreSQL connection.

pg_pconnect

(PHP 3, PHP 4 )

pg_pconnect -- Abre uma conexão PostgreSQL persistente

Descrição

int pg_pconnect ( string connection_string)

pg_pconnect() abre uma conexão a um banco de dados PostgreSQL. Retorna um recurso (resource) de conexão que é necessário para outras funções PostgreSQL.

Para uma descrição do parâmetro connection_string veja pg_connect().

Para habilitar uma conexão persistente, a diretiva pgsql.allow_persistent do php.ini deve ser definida como "On" (que é o padrão). O número máximo de conexões persistentes pode ser definida com a diretiva pgsql.max_persistent do php.ini (o padrão é -1 para sem limite). O número total de conexões pode ser definido com a diretiva pgsql.max_links do php.ini.

pg_close() não fechará links persistentes gerados por pg_pconnect().

Veja também pg_connect().

pg_ping

(PHP 4 >= 4.3.0)

pg_ping -- Faz um ping na conexão com o banco de dados

Description

array pg_ping ( resource connection)

pg_ping() faz um ping na conexão com o banco de dados, tenta reconectar se a conexão foi quebrada. Retorna TRUE se a conexão está ativa, do contrário, retorna FALSE.

Veja também pg_connection_status() e pg_connection_reset().

Exemplo 1. Testando uma conexão PostgreSQL

<?php 
$conn = pg_pconnect ("dbname=publicacao");
if (!$conn) {
    echo "Ocorreu um erro.\n";
    exit;
}

if (!pg_ping($conn))
    die("Conexão quebrada\n");
?>

pg_port

(PHP 3, PHP 4 )

pg_port --  Retorna o número da porta associada com a conexão.

Descrição

int pg_port ( resource connection)

pg_port() retorna o número da porta a qual o recurso de conexão PostgreSQL connection está conectado.

pg_put_line

(PHP 4 >= 4.0.3)

pg_put_line -- Envia uma string terminada em NULL para o backend PostgreSQL

Descrição

bool pg_put_line ( [resource connection, string data])

pg_put_line() envia uma string terminada em NULL para o servidor backend PostgreSQL. Isso é útil, por exemplo, para a inserção de dados em uma tabela em alta velocidade, iniciada através de uma operação de cópia PostgreSQL. O caractere NULL final é adicionado automaticamente. Retorna TRUE em caso de sucesso ou FALSE em falhas.

Nota: A aplicação deve enviar os dois caracteres "\." explicitamente na última linha para indicar ao backend que ela terminou de enviar seus dados.

Veja também pg_end_copy().

Exemplo 1. Inserção de dados na tabela em alta velocidade

<?php 
    $conn = pg_pconnect ("nomebd=meubanco");
    pg_query($conn, "create table bar (a int4, b char(16), d float8)");
    pg_query($conn, "copy bar from stdin");
    pg_put_line($conn, "3\tola mundo\t4.5\n");
    pg_put_line($conn, "4\ttchau mundo\t7.11\n");
    pg_put_line($conn, "\\.\n");
    pg_end_copy($conn);
?>

pg_query

(PHP 4 >= 4.2.0)

pg_query -- Executa uma consulta (query)

Descrição

resource pg_query ( resource connection, string query)

pg_query() retorna um recurso (resource) de resultado da consulta (query) se a consulta pôde ser executada. Retorna FALSE em caso de falha ou se a conexão não é uma conexão válida. Detalhes sobre os erros podem ser recuperados usando a função pg_last_error() se a conexão é válida. pg_last_error() envia uma declaração SQL para o banco de dados PostgreSQL especificado pelo recurso de conexão connection. connection deve ser uma conexão válida que foi criado por pg_connect(). O valor de retorno dessa função é um recurso (resource) de resultado de consulta (query) para ser usado para acessar os resultados de outras funções PostgreSQL como pg_fetch_array().

Nota: connection é um parâmetro opcional para pg_query(). Se connection não for definido, a conexão padrão será usada. A conexão padrão é a última conexão feita por pg_connect() ou pg_pconnect().

Apesar de connection poder ser omitido, isso não é recomendado já que pode ser uma causa de erros difíceis de encontrar no seu script.

Nota: Esta função era chamada pg_exec(). pg_exec() ainda está disponível por razões de compatibilidade, mas os usuários são encorajados a usar o novo nome.

Veja também pg_connect(), pg_pconnect(), pg_fetch_array(), pg_fetch_object(), pg_num_rows(), e pg_affected_rows().

pg_result_error

(PHP 4 >= 4.2.0)

pg_result_error --  Retorna a mensagem de erro associada a um resultado

Descrição

string pg_result_error ( resource result)

pg_result_error() retorna a mensagem de erro associada ao recurso (resource) de resultado result. Deste modo, o usuário tem melhores chances de ter uma mensagem de erro melhor que a retornada por pg_last_error().

Veja também pg_query(), pg_send_query(), pg_get_result(), pg_last_error() e pg_last_notice()

pg_result_seek

(PHP 4 >= 4.3.0)

pg_result_seek -- Altera a posição do ponteiro interno de um recurso (resource) de resultado

Descrição

array pg_result_seek ( resource result, int offset)

pg_result_seek() altera a posição do ponteiro interno de um recurso (resource) de resultado. Retorna FALSE em caso de erro.

Veja também pg_fetch_row(), pg_fetch_assoc(), pg_fetch_array(), pg_fetch_object() e pg_fetch_result().

pg_result_status

(PHP 4 >= 4.2.0)

pg_result_status --  Retorna o status do resultado da consulta (query)

Descrição

int pg_result_status ( resource result)

pg_result_status() retorna o status do recurso (resource) de resultado. Os valores de retorno possíveis são: PGSQL_EMPTY_QUERY, PGSQL_COMMAND_OK, PGSQL_TUPLES_OK, PGSQL_COPY_TO, PGSQL_COPY_FROM, PGSQL_BAD_RESPONSE, PGSQL_NONFATAL_ERROR e PGSQL_FATAL_ERROR.

Veja também pg_connection_status().

pg_select

(PHP 4 >= 4.3.0)

pg_select --  Seleciona registros.

Descrição

array pg_select ( resource connection, string table_name, array assoc_array [, int options])

pg_select() seleciona registros especificados por assoc_array, que contém pares do tipo campo=>valor. Para uma consulta (query) válida, retorna um array que contém todos os registros e campos que combinam com a condição especificada por assoc_array. Se options for especificado, pg_convert() será aplicada à assoc_array com as opções especificadas.

Exemplo 1. pg_select

<?php 
    $db = pg_connect ('nomebd=meubanco');
    // Isto é seguro já que $_POST é convertida automaticamente
    $rec = pg_select($bd, 'post_log', $_POST);
    if ($rec) {
        echo "Registros selecionados\n";
        var_dump($rec);
    }
    else {
    echo "O usuário deve ter inserido dados errados\n";
    }
?>

Nota: Esta função é experimental.

Veja também pg_convert()

pg_send_query

(PHP 4 >= 4.2.0)

pg_send_query --  Envia uma consulta (query) assincrona

Descrição

bool pg_send_query ( resource connection, string query)

bool pg_send_query ( string query)

pg_send_query() envia uma consulta (query) assíncrona para connection. Diferente de pg_query(), ela pode enviar consultas múltiplas para o PostgreSQL e carregar os resultados, um por um, usando pg_get_result(). A execução do script não é bloqueada enquanto as consultas estão sendo executadas. Use pg_connection_busy() para checar se a conexão está ocupada. (por exemplo, se uma consulta está sendo executada). A consulta pode ser cancelada chamando pg_cancel_query().

Apesar de ser possível enviar multiplas consultas de uma vez, você não pode enviar múltiplas consultas para uma conexão ocupada. Se a consulta é enviada enquando a conexão está ocupada ela espera até que a última cosulta seja finalizada e descarta todos os resultados.

Veja também pg_query(), pg_cancel_query(), pg_get_result() e pg_connection_busy()

pg_set_client_encoding

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

pg_set_client_encoding --  Define a codificação do cliente

Descrição

int pg_set_client_encoding ( [resource connection, string encoding])

pg_set_client_encoding() define a codificação do cliente e retorna 0 caso haja sucesso e -1 se houver erro.

encoding é a codificação do cliente e pode ter os valores: SQL_ASCII, EUC_JP, EUC_CN, EUC_KR, EUC_TW, UNICODE, MULE_INTERNAL, LATINX (X=1...9), KOI8, WIN, ALT, SJIS, BIG5, WIN1250. As codificações disponíveis dependem da versão do PostgreSQL e libpq. Vide o manual PostgreSQL para saber das codificações disponíveis para o seu PostgreSQL.

Nota: Esta função exige o PHP 4.0.3 ou maior e PostgreSQL 7.0 ou maior. As codificações suportadas dependem da versão do PostgreSQL. Vide o manual PostgreSQL para detalhes.

Esta função era chamada pg_setclientencoding().

Veja também pg_client_encoding().

pg_trace

(PHP 4 >= 4.0.1)

pg_trace -- Habilita rastreamento em uma conexão PostgreSQL

Descrição

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

pg_trace() habilita o rastreamento da comunicação frontend/backend do PostgreSQL para um arquivo de depuração especificado pelo parâmetro pathname. Para entender completamente estes resultados, você deve estar familiarizado com o protocolo de comunicação interno do PostgreSQL. Para aqueles que não estão, isso ainda pode ser útil para rastrear erros em consultas (queries) enviadas ao servidor, você poderia fazer por exemplo grep '^Para backend' rastro.log. Para maiores informações vide o manual PostgreSQL.

pathname e mode são os mesmos que na função fopen() (o mode padrão é 'w'), connection especifica a conexão a ser rastreada e seu padrão é a última conexão aberta.

Retorna TRUE se o pathname pode ser aberto para escrita, FALSE caso contrário.

Veja também fopen() e pg_untrace().

pg_tty

(PHP 3, PHP 4 )

pg_tty --  Retorna o nome da tty associada com a conexão

Descrição

string pg_tty ( resource connection)

pg_tty() retorna o nome da tty que a saída do lado do servidor é enviada no recurso (resource) de conexão connection.

pg_unescape_bytea

(PHP 4 >= 4.3.0)

pg_unescape_bytea --  Faz escape binário para o tipo bytea

Descrição

string pg_unescape_bytea ( string data)

pg_unescape_bytea() faz uma versão binária da string do tipo bytea. Retorna a string em binário(binary).

Nota: Quando você faz SELECT bytea type, PostgreSQL returna um valor em octal prefixado por \ (por exemplo: \032). Usuários devem fazer a transformação em binário por si próprios.

Esta função exige PostgreSQL 7.2 ou superior. Com PostgreSQL 7.2.0 e 7.2.1, o tipo de dados bytea deve ser criado quando você habilita o suporte a multi-byte. Por exemplo, INSERT INTO tabela_teste (imagem) VALUES ('$imagem_escaped'::bytea); PostgreSQL 7.2.2 ou superior não precisa de coerção (cast). A exceção é quando a codificação de caracteres do cliente e do backend não combinam, então pode haver erro de fluxo de multi-byte. O usuário deve fazer a coerção (cast) para bytea para evitar este erro.

Veja também pg_escape_bytea() e pg_escape_string()

pg_untrace

(PHP 4 >= 4.0.1)

pg_untrace -- Desabilita o rastreamento de uma conexão PostgreSQL

Descrição

bool pg_untrace ( [resource connection])

Pára o rastreamento iniciado por pg_trace(). connection especifica a conexão que está sendo rastreada e seu padrão é a última conexão aberta.

Sempre retorna TRUE.

Veja também pg_trace().

pg_update

(PHP 4 >= 4.3.0)

pg_update --  Atualiza uma tabela.

Descrição

long pg_update ( resource connection, string table_name, array condition, array data [, int options])

pg_update() atualiza registros que combinam com a condição especificada pelo argumento condition com os dados do parâmetro data. Se options for especificado, pg_convert() será aplicada a data com as opções especificadas.

Exemplo 1. pg_update

<?php 
    $bd = pg_connect ('dbname=meubanco');
    $dados = array('campo1'=>'AA', 'campo2'=>'BB');
    // Isto é seguro já que $_POST é convertido automaticamente
    $res = pg_update($bd, 'post_log', $_POST, $dados);
    if ($res) {
        echo "Dados atualizados: $res\n";
    }
    else {
        echo "Usuário deve ter enviado entradas inválidas\n";
    }
?>

Nota: Esta função é experimental.

Veja também pg_convert()

LXXXII. Process Control Functions

Introdução

Process Control support in PHP implements the Unix style of process creation, program execution, signal handling and process termination. Process Control should not be enabled within a webserver environment and unexpected results may happen if any Process Control functions are used within a webserver environment.

This documentation is intended to explain the general usage of each of the Process Control functions. For detailed information about Unix process control you are encouraged to consult your systems documentation including fork(2), waitpid(2) and signal(2) or a comprehensive reference such as Advanced Programming in the UNIX Environment by W. Richard Stevens (Addison-Wesley).

PCNTL now uses ticks as the signal handle callback mechanism, which is much faster than the previous mechanism. This change follows the same semantics as using "user ticks". You use the declare() statement to specify the locations in your program where callbacks are allowed to occur. This allows you to minimize the overhead of handling asynchronous events. In the past, compiling PHP with pcntl enabled would always incur this overhead, whether or not your script actually used pcntl.

There is one adjustment that all pcntl scripts prior to PHP 4.3.0 must make for them to work which is to either to use declare() on a section where you wish to allow callbacks or to just enable it across the entire script using the new global syntax of declare().

Nota: This extension is not available on Windows platforms.


Requisitos

Nenhuma biblioteca externa é necessária para compilar esta extensão.


Instalação

Process Control support in PHP is not enabled by default. You have to compile the CGI or CLI version of PHP with --enable-pcntl configuration option when compiling PHP to enable Process Control support.

Nota: Currently, this module will not function on non-Unix platforms (Windows).


Configuração durante execução

Esta extenção não define nenhum parâmetro de configuração no php.ini.


Tipos Resource

Esta extensão não possui nenhum tipo resource.


Constantes Predefinidas

The following list of signals are supported by the Process Control functions. Please see your systems signal(7) man page for details of the default behavior of these signals.

WNOHANG (integer)

WUNTRACED (integer)

SIG_IGN (integer)

SIG_DFL (integer)

SIG_ERR (integer)

SIGHUP (integer)

SIGINT (integer)

SIGQUIT (integer)

SIGILL (integer)

SIGTRAP (integer)

SIGABRT (integer)

SIGIOT (integer)

SIGBUS (integer)

SIGFPE (integer)

SIGKILL (integer)

SIGUSR1 (integer)

SIGSEGV (integer)

SIGUSR2 (integer)

SIGPIPE (integer)

SIGALRM (integer)

SIGTERM (integer)

SIGSTKFLT (integer)

SIGCLD (integer)

SIGCHLD (integer)

SIGCONT (integer)

SIGSTOP (integer)

SIGTSTP (integer)

SIGTTIN (integer)

SIGTTOU (integer)

SIGURG (integer)

SIGXCPU (integer)

SIGXFSZ (integer)

SIGVTALRM (integer)

SIGPROF (integer)

SIGWINCH (integer)

SIGPOLL (integer)

SIGIO (integer)

SIGPWR (integer)

SIGSYS (integer)

SIGBABY (integer)


Exemplos

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

Exemplo 1. Process Control Example

<?php
declare(ticks=1);

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

// detatch from the controlling terminal
if (!posix_setsid()) {
    die("could not detach from terminal");
}

// setup signal handlers
pcntl_signal(SIGTERM, "sig_handler");
pcntl_signal(SIGHUP, "sig_handler");

// loop forever performing tasks
while(1) {

    // do something interesting here

}

function sig_handler($signo) {

     switch($signo) {
         case SIGTERM:
             // handle shutdown tasks
             exit;
             break;
         case SIGHUP:
             // handle restart tasks
             break;
         default:
             // handle all other signals
     }

}

?>

Veja Também

A look at the section about POSIX functions may be useful.

Índice
pcntl_exec --  Executes specified program in current process space
pcntl_fork -- Forks the currently running process
pcntl_signal -- Installs a signal handler
pcntl_waitpid -- Waits on or returns the status of a forked child
pcntl_wexitstatus --  Returns the return code of a terminated child
pcntl_wifexited --  Returns TRUE if status code represents a successful exit
pcntl_wifsignaled --  Returns TRUE if status code represents a termination due to a signal
pcntl_wifstopped --  Returns TRUE if child process is currently stopped
pcntl_wstopsig --  Returns the signal which caused the child to stop
pcntl_wtermsig --  Returns the signal which caused the child to terminate

pcntl_exec

(PHP 4 >= 4.2.0)

pcntl_exec --  Executes specified program in current process space

Description

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

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

pcntl_fork

(PHP 4 >= 4.1.0)

pcntl_fork -- Forks the currently running process

Description

int pcntl_fork ( void)

The pcntl_fork() function creates a child process that differs from the parent process only in it's PID and PPID. Please see your system's fork(2) man page for specific details as to how fork works on your system.

On success, the PID of the child process is returned in the parent's thread of execution, and a 0 is returned in the child's thread of execution. On failure, a -1 will be returned in the parent's context, no child process will be created, and a PHP error is raised.

Exemplo 1. pcntl_fork() Example

<?php

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

?>

See also pcntl_waitpid() and pcntl_signal().

pcntl_signal

(PHP 4 >= 4.1.0)

pcntl_signal -- Installs a signal handler

Description

bool pcntl_signal ( int signo, mixed handle [, bool restart_syscalls])

The pcntl_signal() function installs a new signal handler for the signal indicated by signo. The signal handler is set to handler which may be the name of a user created function, or either of the two global constants SIG_IGN or SIG_DFL. The optional restart_syscalls specifies whether system call restarting should be used when this signal arrives and defaults to TRUE.

Retorna TRUE em caso de sucesso ou FALSE em falhas.

Nota: The optional restart_syscalls parameter became available in PHP 4.3.0.

Nota: The ability to use an object method as a callback became available in PHP 4.3.0. Note that when you set a handler to an object method, that object's reference count is increased which makes it persist until you either change the handler to something else, or your script ends.

Exemplo 1. pcntl_signal() Example

<?php
// tick use required as of PHP 4.3.0
declare (ticks = 1);

// signal handler function
function sig_handler($signo) {

     switch($signo) {
         case SIGTERM:
             // handle shutdown tasks
             exit;
             break;
         case SIGHUP:
             // handle restart tasks
             break;
         case SIGUSR1:
             print "Caught SIGUSR1...\n";
             break;
         default:
             // handle all other signals
     }

}

print "Installing signal handler...\n";

// setup signal handlers
pcntl_signal(SIGTERM, "sig_handler");
pcntl_signal(SIGHUP,  "sig_handler");
pcntl_signal(SIGUSR1, "sig_handler");

// or use an object, available as of PHP 4.3.0
// pcntl_signal(SIGUSR1, array($obj, "do_something");

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

// send SIGUSR1 to current process id
posix_kill(posix_getpid(), SIGUSR1);

print "Done\n"

?>

See also pcntl_fork() and pcntl_waitpid().

pcntl_waitpid

(PHP 4 >= 4.1.0)

pcntl_waitpid -- Waits on or returns the status of a forked child

Description

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

The pcntl_waitpid() function suspends execution of the current process until a child as specified by the pid argument has exited, or until a signal is delivered whose action is to terminate the current process or to call a signal handling function. If a child as requested by pid has already exited by the time of the call (a so-called "zombie" process), the function returns immediately. Any system resources used by the child are freed. Please see your system's waitpid(2) man page for specific details as to how waitpid works on your system.

pcntl_waitpid() returns the process ID of the child which exited, -1 on error or zero if WNOHANG was used and no child was available

The value of pid can be one of the following:

Tabela 1. possible values for pid

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

pcntl_waitpid() will store status information in the status parameter which can be evaluated using the following functions: pcntl_wifexited(), pcntl_wifstopped(), pcntl_wifsignaled(), pcntl_wexitstatus(), pcntl_wtermsig() and pcntl_wstopsig().

The value of options is the value of zero or more of the following two global constants OR'ed together:

Tabela 2. possible values for options

WNOHANG return immediately if no child has exited.
WUNTRACED return for children which are stopped, and whose status has not been reported.

See also pcntl_fork(), pcntl_signal(), pcntl_wifexited(), pcntl_wifstopped(), pcntl_wifsignaled(), pcntl_wexitstatus(), pcntl_wtermsig() and pcntl_wstopsig().

pcntl_wexitstatus

(PHP 4 >= 4.1.0)

pcntl_wexitstatus --  Returns the return code of a terminated child

Description

int pcntl_wexitstatus ( int status)

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

The parameter status is the status parameter supplied to a successfull call to pcntl_waitpid().

See also pcntl_waitpid() and pcntl_wifexited().

pcntl_wifexited

(PHP 4 >= 4.1.0)

pcntl_wifexited --  Returns TRUE if status code represents a successful exit

Description

int pcntl_wifexited ( int status)

Returns TRUE if the child status code represents a successful exit.

The parameter status is the status parameter supplied to a successfull call to pcntl_waitpid().

See also pcntl_waitpid() and pcntl_wexitstatus().

pcntl_wifsignaled

(PHP 4 >= 4.1.0)

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

Description

int pcntl_wifsignaled ( int status)

Returns TRUE if the child process exited because of a signal which was not caught.

The parameter status is the status parameter supplied to a successfull call to pcntl_waitpid().

See also pcntl_waitpid() and pcntl_signal().

pcntl_wifstopped

(PHP 4 >= 4.1.0)

pcntl_wifstopped --  Returns TRUE if child process is currently stopped

Description

int pcntl_wifstopped ( int status)

Returns TRUE if the child process which caused the return is currently stopped; this is only possible if the call to pcntl_waitpid() was done using the option WUNTRACED.

The parameter status is the status parameter supplied to a successfull call to pcntl_waitpid().

See also pcntl_waitpid().

pcntl_wstopsig

(PHP 4 >= 4.1.0)

pcntl_wstopsig --  Returns the signal which caused the child to stop

Description

int pcntl_wstopsig ( int status)

Returns the number of the signal which caused the child to stop. This function is only useful if pcntl_wifstopped() returned TRUE.

The parameter status is the status parameter supplied to a successfull call to pcntl_waitpid().

See also pcntl_waitpid() and pcntl_wifstopped().

pcntl_wtermsig

(PHP 4 >= 4.1.0)

pcntl_wtermsig --  Returns the signal which caused the child to terminate

Description

int pcntl_wtermsig ( int status)

Returns the number of the signal that caused the child process to terminate. This function is only useful if pcntl_wifsignaled() returned TRUE.

The parameter status is the status parameter supplied to a successfull call to pcntl_waitpid().

See also pcntl_waitpid(), pcntl_signal() and pcntl_wifsignaled().

LXXXIII. Program Execution functions

Introdução

Those functions provides means to executes commands on the system itself, and means secure such commands.


Requisitos

Nenhuma biblioteca externa é necessária para compilar esta extensão.


Instalação

Não há nenhuma instalação nescessária para utilizar estas funções, elas fazem parte do núcleo do PHP.


Configuração durante execução

Esta extenção não define nenhum parâmetro de configuração no php.ini.


Tipos Resource

Esta extensão não possui nenhum tipo resource.


Constantes Predefinidas

Esta extensão não possui nenhuma constante.


Veja Também

These functions are also closely related to the backtick operator. Also, while in Safe Mode you must consider the safe_mode_exec_dir directive.

Índice
escapeshellarg -- escape a string to be used as a shell argument
escapeshellcmd -- escape shell metacharacters
exec -- Execute an external program
passthru --  Execute an external program and display raw output
proc_close --  Close a process opened by proc_open and return the exit code of that process.
proc_open --  Execute a command and open file pointers for input/output
shell_exec --  Execute command via shell and return complete output as string
system -- Execute an external program and display output

escapeshellarg

(PHP 4 >= 4.0.3)

escapeshellarg -- escape a string to be used as a shell argument

Description

string escapeshellarg ( string arg)

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

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

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

escapeshellcmd

(PHP 3, PHP 4 )

escapeshellcmd -- escape shell metacharacters

Description

string escapeshellcmd ( string command)

escapeshellcmd() escapes any characters in a string that might be used to trick a shell command into executing arbitrary commands. This function should be used to make sure that any data coming from user input is escaped before this data is passed to the exec() or system() functions, or to the backtick operator. A standard use would be:

$e = escapeshellcmd($userinput);
system("echo $e"); // here we don't care if $e has spaces
$f = escapeshellcmd($filename);
system("touch \"/tmp/$f\"; ls -l \"/tmp/$f\""); // and here we do, so we use quotes

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

exec

(PHP 3, PHP 4 )

exec -- Execute an external program

Description

string exec ( string command [, array output [, int return_var]])

exec() executes the given command, however it does not output anything. It simply returns the last line from the result of the command. If you need to execute a command and have all the data from the command passed directly back without any interference, use the passthru() function.

If the array argument is present, then the specified array will be filled with every line of output from the command. Line endings, such as \n, are not included in this array. Note that if the array already contains some elements, exec() will append to the end of the array. If you do not want the function to append elements, call unset() on the array before passing it to exec().

If the return_var argument is present along with the array argument, then the return status of the executed command will be written to this variable.

Atenção

If you are going to allow data coming from user input to be passed to this function, then you should be using escapeshellarg() or escapeshellcmd() to make sure that users cannot trick the system into executing arbitrary commands.

Nota: If you start a program using this function and want to leave it running in the background, you have to make sure that the output of that program is redirected to a file or some other output stream or else PHP will hang until the execution of the program ends.

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

passthru

(PHP 3, PHP 4 )

passthru --  Execute an external program and display raw output

Description

void passthru ( string command [, int return_var])

The passthru() function is similar to the exec() function in that it executes a command. If the return_var argument is present, the return status of the Unix command will be placed here. This function should be used in place of exec() or system() when the output from the Unix command is binary data which needs to be passed directly back to the browser. A common use for this is to execute something like the pbmplus utilities that can output an image stream directly. By setting the Content-type to image/gif and then calling a pbmplus program to output a gif, you can create PHP scripts that output images directly.

Atenção

If you are going to allow data coming from user input to be passed to this function, then you should be using escapeshellarg() or escapeshellcmd() to make sure that users cannot trick the system into executing arbitrary commands.

Nota: If you start a program using this function and want to leave it running in the background, you have to make sure that the output of that program is redirected to a file or some other output stream or else PHP will hang until the execution of the program ends.

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

proc_close

(PHP 4 >= 4.3.0)

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

Description

int proc_close ( resource process)

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

proc_open

(PHP 4 >= 4.3.0)

proc_open --  Execute a command and open file pointers for input/output

Description

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

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

$descriptorspec = array(
   0 => array("pipe", "r"),  // stdin is a pipe that the child will read from
   1 => array("pipe", "w"),  // stdout is a pipe that the child will write to
   2 => array("file", "/tmp/error-output.txt", "a"), // stderr is a file to write to
);
$process = proc_open("php", $descriptorspec, $pipes);
if (is_resource($process)) {
    // $pipes now looks like this:
    // 0 => writeable handle connected to child stdin
    // 1 => readable handle connected to child stdout
    // Any error output will be appended to /tmp/error-output.txt

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

    while(!feof($pipes[1])) {
        echo fgets($pipes[1], 1024);
    }
    fclose($pipes[1]);
    // It is important that you close any pipes before calling
    // proc_close in order to avoid a deadlock
    $return_value = proc_close($process);

    echo "command returned $return_value\n";
}

The file descriptor numbers in descriptorspec are not limited to 0, 1 and 2 - you may specify any valid file descriptor number and it will be passed to the child process. This allows your script to interoperate with other scripts that run as "co-processes". In particular, this is useful for passing passphrases to programs like PGP, GPG and openssl in a more secure manner. It is also useful for reading status information provided by those programs on auxillary file descriptors.

Nota: Windows compatibility: Descriptors beyond 2 (stderr) are made available to the child process as inheritable handles, but since the Windows architecture does not associate file descriptor numbers with low-level handles, the child process does not (yet) have a means of accessing those handles. Stdin, stdout and stderr work as expected.

Nota: This function was introduced in PHP 4.3.0.

Nota: If you only need a uni-directional (one-way) process pipe, use popen() instead, as it is much easier to use.

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

shell_exec

(PHP 4 )

shell_exec --  Execute command via shell and return complete output as string

Description

string shell_exec ( string cmd)

This function is identical to the backtick operator.

system

(PHP 3, PHP 4 )

system -- Execute an external program and display output

Description

string system ( string command [, int return_var])

system() is just like the C version of the function in that it executes the given command and outputs the result. If a variable is provided as the second argument, then the return status code of the executed command will be written to this variable.

Atenção

If you are going to allow data coming from user input to be passed to this function, then you should be using escapeshellarg() or escapeshellcmd() to make sure that users cannot trick the system into executing arbitrary commands.

Nota: If you start a program using this function and want to leave it running in the background, you have to make sure that the output of that program is redirected to a file or some other output stream or else PHP will hang until the execution of the program ends.

The system() call also tries to automatically flush the web server's output buffer after each line of output if PHP is running as a server module.

Returns the last line of the command output on success, and FALSE on failure.

If you need to execute a command and have all the data from the command passed directly back without any interference, use the passthru() function.

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

LXXXIV. Printer functions

Introdução

These functions are only available under Windows 9.x, ME, NT4 and 2000. They have been added in PHP 4.0.4.


Instalação

Add the line extension=php_printer.dll to your php.ini file.


Configuração durante execução

O comportamento dessas funções podem ser modificado pelas configurações do php.ini.

Tabela 1. Printer configuration options

Name Default Changeable
printer.default_printer "" PHP_INI_ALL
For further details and definition of the PHP_INI_* constants see ini_set().

Índice
printer_abort -- Deletes the printer's spool file
printer_close -- Close an open printer connection
printer_create_brush -- Create a new brush
printer_create_dc -- Create a new device context
printer_create_font -- Create a new font
printer_create_pen -- Create a new pen
printer_delete_brush -- Delete a brush
printer_delete_dc -- Delete a device context
printer_delete_font -- Delete a font
printer_delete_pen -- Delete a pen
printer_draw_bmp -- Draw a bmp
printer_draw_chord -- Draw a chord
printer_draw_elipse -- Draw an ellipse
printer_draw_line -- Draw a line
printer_draw_pie -- Draw a pie
printer_draw_rectangle -- Draw a rectangle
printer_draw_roundrect -- Draw a rectangle with rounded corners
printer_draw_text -- Draw text
printer_end_doc -- Close document
printer_end_page -- Close active page
printer_get_option -- Retrieve printer configuration data
printer_list -- Return an array of printers attached to the server
printer_logical_fontheight -- Get logical font height
printer_open -- Open connection to a printer
printer_select_brush -- Select a brush
printer_select_font -- Select a font
printer_select_pen -- Select a pen
printer_set_option -- Configure the printer connection
printer_start_doc -- Start a new document
printer_start_page -- Start a new page
printer_write -- Write data to the printer

printer_abort

(no version information, might be only in CVS)

printer_abort -- Deletes the printer's spool file

Description

void printer_abort ( resource handle)

This function deletes the printers spool file.

handle must be a valid handle to a printer.

Exemplo 1. printer_abort() example

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

printer_close

(no version information, might be only in CVS)

printer_close -- Close an open printer connection

Description

void printer_close ( resource handle)

This function closes the printer connection. printer_close() also closes the active device context.

handle must be a valid handle to a printer.

Exemplo 1. printer_close() example

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

printer_create_brush

(no version information, might be only in CVS)

printer_create_brush -- Create a new brush

Description

mixed printer_create_brush ( int style, string color)

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

  • PRINTER_BRUSH_SOLID: creates a brush with a solid color.

  • PRINTER_BRUSH_DIAGONAL: creates a brush with a 45-degree upward left-to-right hatch ( / ).

  • PRINTER_BRUSH_CROSS: creates a brush with a cross hatch ( + ).

  • PRINTER_BRUSH_DIAGCROSS: creates a brush with a 45 cross hatch ( x ).

  • PRINTER_BRUSH_FDIAGONAL: creates a brush with a 45-degree downward left-to-right hatch ( \ ).

  • PRINTER_BRUSH_HORIZONTAL: creates a brush with a horizontal hatch ( - ).

  • PRINTER_BRUSH_VERTICAL: creates a brush with a vertical hatch ( | ).

  • PRINTER_BRUSH_CUSTOM: creates a custom brush from an BMP file. The second parameter is used to specify the BMP instead of the RGB color code.

printer_create_dc

(no version information, might be only in CVS)

printer_create_dc -- Create a new device context

Description

void printer_create_dc ( resource handle)

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

Exemplo 1. printer_create_dc() example

$handle = printer_open();
printer_start_doc($handle);
printer_start_page($handle);

printer_create_dc($handle);
/* do some stuff with the dc */
printer_set_option($handle, PRINTER_TEXT_COLOR, "333333");
printer_draw_text($handle, 1, 1, "text");
printer_delete_dc($handle);

/* create another dc */
printer_create_dc($handle);
printer_set_option($handle, PRINTER_TEXT_COLOR, "000000");
printer_draw_text($handle, 1, 1, "text");
/* do some stuff with the dc */

printer_delete_dc($handle);

printer_endpage($handle);
printer_end_doc($handle);
printer_close($handle);

printer_create_font

(no version information, might be only in CVS)

printer_create_font -- Create a new font

Description

mixed printer_create_font ( string face, int height, int width, int font_weight, bool italic, bool underline, bool strikeout, int orientaton)

The function creates a new font and returns a handle to it. A font is used to draw text. For an example see printer_select_font(). face must be a string specifying the font face. height specifies the font height, and width the font width. The font_weight specifies the font weight (400 is normal), and can be one of the following predefined constants.

  • PRINTER_FW_THIN: sets the font weight to thin (100).

  • PRINTER_FW_ULTRALIGHT: sets the font weight to ultra light (200).

  • PRINTER_FW_LIGHT: sets the font weight to light (300).

  • PRINTER_FW_NORMAL: sets the font weight to normal (400).

  • PRINTER_FW_MEDIUM: sets the font weight to medium (500).

  • PRINTER_FW_BOLD: sets the font weight to bold (700).

  • PRINTER_FW_ULTRABOLD: sets the font weight to ultra bold (800).

  • PRINTER_FW_HEAVY: sets the font weight to heavy (900).

italic can be TRUE or FALSE, and sets whether the font should be italic.

underline can be TRUE or FALSE, and sets whether the font should be underlined.

strikeout can be TRUE or FALSE, and sets whether the font should be striked out.

orientation specifies a rotation. For an example see printer_select_font().

printer_create_pen

(no version information, might be only in CVS)

printer_create_pen -- Create a new pen

Description

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

The function creates a new pen and returns a handle to it. A pen is used to draw lines and curves. For an example see printer_select_pen(). color must be a color in RGB hex format, i.e. "000000" for black, width specifies the width of the pen whereas style must be one of the following constants:

  • PRINTER_PEN_SOLID: creates a solid pen.

  • PRINTER_PEN_DASH: creates a dashed pen.

  • PRINTER_PEN_DOT: creates a dotted pen.

  • PRINTER_PEN_DASHDOT: creates a pen with dashes and dots.

  • PRINTER_PEN_DASHDOTDOT: creates a pen with dashes and double dots.

  • PRINTER_PEN_INVISIBLE: creates an invisible pen.

printer_delete_brush

(no version information, might be only in CVS)

printer_delete_brush -- Delete a brush

Description

bool printer_delete_brush ( resource handle)

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

printer_delete_dc

(no version information, might be only in CVS)

printer_delete_dc -- Delete a device context

Description

bool printer_delete_dc ( resource handle)

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

printer_delete_font

(no version information, might be only in CVS)

printer_delete_font -- Delete a font

Description

bool printer_delete_font ( resource handle)

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

printer_delete_pen

(no version information, might be only in CVS)

printer_delete_pen -- Delete a pen

Description

bool printer_delete_pen ( resource handle)

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

printer_draw_bmp

(no version information, might be only in CVS)

printer_draw_bmp -- Draw a bmp

Description

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

The function simply draws an bmp the bitmap filename at position x, y. handle must be a valid handle to a printer.

The function returns TRUE on success, or otherwise FALSE.

Exemplo 1. printer_draw_bmp() example

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

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

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

printer_draw_chord

(no version information, might be only in CVS)

printer_draw_chord -- Draw a chord

Description

void printer_draw_chord ( resource handle, int rec_x, int rec_y, int rec_x1, int rec_y1, int rad_x, int rad_y, int rad_x1, int rad_y1)

The function simply draws an chord. handle must be a valid handle to a printer.

rec_x is the upper left x coordinate of the bounding rectangle.

rec_y is the upper left y coordinate of the bounding rectangle.

rec_x1 is the lower right x coordinate of the bounding rectangle.

rec_y1 is the lower right y coordinate of the bounding rectangle.

rad_x is x coordinate of the radial defining the beginning of the chord.

rad_y is y coordinate of the radial defining the beginning of the chord.

rad_x1 is x coordinate of the radial defining the end of the chord.

rad_y1 is y coordinate of the radial defining the end of the chord.

Exemplo 1. printer_draw_chord() example

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

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

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

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

printer_delete_brush($brush);
printer_delete_pen($pen);

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

printer_draw_elipse

(no version information, might be only in CVS)

printer_draw_elipse -- Draw an ellipse

Description

void printer_draw_elipse ( resource handle, int ul_x, int ul_y, int lr_x, int lr_y)

The function simply draws an ellipse. handle must be a valid handle to a printer.

ul_x is the upper left x coordinate of the ellipse.

ul_y is the upper left y coordinate of the ellipse.

lr_x is the lower right x coordinate of the ellipse.

lr_y is the lower right y coordinate of the ellipse.

Exemplo 1. printer_draw_elipse() example

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

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

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

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

printer_delete_brush($brush);
printer_delete_pen($pen);

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

printer_draw_line

(no version information, might be only in CVS)

printer_draw_line -- Draw a line

Description

void printer_draw_line ( resource printer_handle, int from_x, int from_y, int to_x, int to_y)

The function simply draws a line from position from_x, from_y to position to_x, to_y using the selected pen. printer_handle must be a valid handle to a printer.

Exemplo 1. printer_draw_line() example

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

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

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

printer_delete_pen($pen);

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

printer_draw_pie

(no version information, might be only in CVS)

printer_draw_pie -- Draw a pie

Description

void printer_draw_pie ( resource handle, int rec_x, int rec_y, int rec_x1, int rec_y1, int rad1_x, int rad1_y, int rad2_x, int rad2_y)

The function simply draws an pie. handle must be a valid handle to a printer.

rec_x is the upper left x coordinate of the bounding rectangle.

rec_y is the upper left y coordinate of the bounding rectangle.

rec_x1 is the lower right x coordinate of the bounding rectangle.

rec_y1 is the lower right y coordinate of the bounding rectangle.

rad1_x is x coordinate of the first radial's ending.

rad1_y is y coordinate of the first radial's ending.

rad2_x is x coordinate of the second radial's ending.

rad2_y is y coordinate of the second radial's ending.

Exemplo 1. printer_draw_pie() example

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

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

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

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

printer_delete_brush($brush);
printer_delete_pen($pen);

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

printer_draw_rectangle

(no version information, might be only in CVS)

printer_draw_rectangle -- Draw a rectangle

Description

void printer_draw_rectangle ( resource handle, int ul_x, int ul_y, int lr_x, int lr_y)

The function simply draws a rectangle.

handle must be a valid handle to a printer.

ul_x is the upper left x coordinate of the rectangle.

ul_y is the upper left y coordinate of the rectangle.

lr_x is the lower right x coordinate of the rectangle.

lr_y is the lower right y coordinate of the rectangle.

Exemplo 1. printer_draw_rectangle() example

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

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

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

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

printer_delete_brush($brush);
printer_delete_pen($pen);

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

printer_draw_roundrect

(no version information, might be only in CVS)

printer_draw_roundrect -- Draw a rectangle with rounded corners

Description

void printer_draw_roundrect ( resource handle, int ul_x, int ul_y, int lr_x, int lr_y, int width, int height)

The function simply draws a rectangle with rounded corners.

handle must be a valid handle to a printer.

ul_x is the upper left x coordinate of the rectangle.

ul_y is the upper left y coordinate of the rectangle.

lr_x is the lower right x coordinate of the rectangle.

lr_y is the lower right y coordinate of the rectangle.

width is the width of the ellipse.

height is the height of the ellipse.

Exemplo 1. printer_draw_roundrect() example

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

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

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

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

printer_delete_brush($brush);
printer_delete_pen($pen);

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

printer_draw_text

(no version information, might be only in CVS)

printer_draw_text -- Draw text

Description

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

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

Exemplo 1. printer_draw_text() example

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

$font = printer_create_font("Arial",72,48,400,false,false,false,0);
printer_select_font($handle, $font);
printer_draw_text($handle, "test", 10, 10);
printer_delete_font($font);

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

printer_end_doc

(no version information, might be only in CVS)

printer_end_doc -- Close document

Description

bool printer_end_doc ( resource handle)

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

printer_end_page

(no version information, might be only in CVS)

printer_end_page -- Close active page

Description

bool printer_end_page ( resource handle)

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

printer_get_option

(no version information, might be only in CVS)

printer_get_option -- Retrieve printer configuration data

Description

mixed printer_get_option ( resource handle, string option)

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

  • PRINTER_DEVICENAME returns the devicename of the printer.

  • PRINTER_DRIVERVERSION returns the printer driver version.

Exemplo 1. printer_get_option() example

$handle = printer_open();
print printer_get_option($handle, PRINTER_DRIVERVERSION);
printer_close($handle);

printer_list

(no version information, might be only in CVS)

printer_list -- Return an array of printers attached to the server

Description

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

The function enumerates available printers and their capabilities. level sets the level of information request. Can be 1,2,4 or 5. enumtype must be one of the following predefined constants:

  • PRINTER_ENUM_LOCAL: enumerates the locally installed printers.

  • PRINTER_ENUM_NAME: enumerates the printer of name, can be a server, domain or print provider.

  • PRINTER_ENUM_SHARED: this parameter can't be used alone, it has to be OR'ed with other parameters, i.e. PRINTER_ENUM_LOCAL to detect the locally shared printers.

  • PRINTER_ENUM_DEFAULT: (Win9.x only) enumerates the default printer.

  • PRINTER_ENUM_CONNECTIONS: (WinNT/2000 only) enumerates the printers to which the user has made connections.

  • PRINTER_ENUM_NETWORK: (WinNT/2000 only) enumerates network printers in the computer's domain. Only valid if level is 1.

  • PRINTER_ENUM_REMOTE: (WinNT/2000 only) enumerates network printers and print servers in the computer's domain. Only valid if level is 1.

Exemplo 1. printer_list() example

/* detect locally shared printer */
var_dump( printer_list(PRINTER_ENUM_LOCAL | PRINTER_ENUM_SHARED) );

printer_logical_fontheight

(no version information, might be only in CVS)

printer_logical_fontheight -- Get logical font height

Description

int printer_logical_fontheight ( resource handle, int height)

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

Exemplo 1. printer_logical_fontheight() example

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

printer_open

(no version information, might be only in CVS)

printer_open -- Open connection to a printer

Description

mixed printer_open ( [string devicename])

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

If no parameter was given it tries to open a connection to the default printer (if not specified in php.ini as printer.default_printer, php tries to detect it).

printer_open() also starts a device context.

Exemplo 1. printer_open() example

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

printer_select_brush

(no version information, might be only in CVS)

printer_select_brush -- Select a brush

Description

void printer_select_brush ( resource printer_handle, resource brush_handle)

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

Exemplo 1. printer_select_brush() example

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

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

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

printer_delete_brush($brush);

$brush = printer_create_brush(PRINTER_BRUSH_SOLID, "000000");
printer_select_brush($handle, $brush);
printer_draw_rectangle($handle, 1,501,500,1001);
printer_delete_brush($brush);

printer_delete_pen($pen);

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

printer_select_font

(no version information, might be only in CVS)

printer_select_font -- Select a font

Description

void printer_select_font ( resource printer_handle, resource font_handle)

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

Exemplo 1. printer_select_font() example

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

$font = printer_create_font("Arial", 148, 76, PRINTER_FW_MEDIUM, false, false, false, -50);
printer_select_font($handle, $font);
printer_draw_text($handle, "PHP is simply cool", 40, 40);
printer_delete_font($font);

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

printer_select_pen

(no version information, might be only in CVS)

printer_select_pen -- Select a pen

Description

void printer_select_pen ( resource printer_handle, resource pen_handle)

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

Exemplo 1. printer_select_pen() example

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

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

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

printer_delete_pen($pen);

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

printer_set_option

(no version information, might be only in CVS)

printer_set_option -- Configure the printer connection

Description

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

The function sets the following options for the current connection. handle must be a valid handle to a printer. For option can be one of the following constants:

  • PRINTER_COPIES: sets how many copies should be printed, value must be an integer.

  • PRINTER_MODE: specifies the type of data (text, raw or emf), value must be a string.

  • PRINTER_TITLE: specifies the name of the document, value must be a string.

  • PRINTER_ORIENTATION: specifies the orientation of the paper, value can be either PRINTER_ORIENTATION_PORTRAIT or PRINTER_ORIENTATION_LANDSCAPE

  • PRINTER_RESOLUTION_Y: specifies the y-resolution in DPI, value must be an integer.

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

  • PRINTER_PAPER_FORMAT: specifies the a predefined paper format, set value to PRINTER_FORMAT_CUSTOM if you want to specify a custom format with PRINTER_PAPER_WIDTH and PRINTER_PAPER_LENGTH. value can be one of the following constants.

    • PRINTER_FORMAT_CUSTOM: let's you specify a custom paper format.

    • PRINTER_FORMAT_LETTER: specifies standard letter format (8 1/2- by 11-inches).

    • PRINTER_FORMAT_LETTER: specifies standard legal format (8 1/2- by 14-inches).

    • PRINTER_FORMAT_A3: specifies standard A3 format (297- by 420-millimeters).

    • PRINTER_FORMAT_A4: specifies standard A4 format (210- by 297-millimeters).

    • PRINTER_FORMAT_A5: specifies standard A5 format (148- by 210-millimeters).

    • PRINTER_FORMAT_B4: specifies standard B4 format (250- by 354-millimeters).

    • PRINTER_FORMAT_B5: specifies standard B5 format (182- by 257-millimeter).

    • PRINTER_FORMAT_FOLIO: specifies standard FOLIO format (8 1/2- by 13-inch).

  • PRINTER_PAPER_LENGTH: if PRINTER_PAPER_FORMAT is set to PRINTER_FORMAT_CUSTOM, PRINTER_PAPER_LENGTH specifies a custom paper length in mm, value must be an integer.

  • PRINTER_PAPER_WIDTH: if PRINTER_PAPER_FORMAT is set to PRINTER_FORMAT_CUSTOM, PRINTER_PAPER_WIDTH specifies a custom paper width in mm, value must be an integer.

  • PRINTER_SCALE: specifies the factor by which the printed output is to be scaled. the page size is scaled from the physical page size by a factor of scale/100. for example if you set the scale to 50, the output would be half of it's original size. value must be an integer.

  • PRINTER_BACKGROUND_COLOR: specifies the background color for the actual device context, value must be a string containing the rgb information in hex format i.e. "005533".

  • PRINTER_TEXT_COLOR: specifies the text color for the actual device context, value must be a string containing the rgb information in hex format i.e. "005533".

  • PRINTER_TEXT_ALIGN: specifies the text alignment for the actual device context, value can be combined through OR'ing the following constants:

    • PRINTER_TA_BASELINE: text will be aligned at the base line.

    • PRINTER_TA_BOTTOM: text will be aligned at the bottom.

    • PRINTER_TA_TOP: text will be aligned at the top.

    • PRINTER_TA_CENTER: text will be aligned at the center.

    • PRINTER_TA_LEFT: text will be aligned at the left.

    • PRINTER_TA_RIGHT: text will be aligned at the right.

Exemplo 1. printer_set_option() example

$handle = printer_open();
printer_set_option($handle, PRINTER_SCALE, 75);
printer_set_option($handle, PRINTER_TEXT_ALIGN, PRINTER_TA_LEFT);
printer_close($handle);

printer_start_doc

(no version information, might be only in CVS)

printer_start_doc -- Start a new document

Description

bool printer_start_doc ( resource handle [, string document])

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

Exemplo 1. printer_start_doc() example

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

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

printer_start_page

(no version information, might be only in CVS)

printer_start_page -- Start a new page

Description

bool printer_start_page ( resource handle)

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

printer_write

(no version information, might be only in CVS)

printer_write -- Write data to the printer

Description

bool printer_write ( resource handle, string content)

Writes content directly to the printer, and returns TRUE on success or FALSE if it failed.

handle must be a valid handle to a printer.

Exemplo 1. printer_write() example

$handle = printer_open();
printer_write($handle, "Text to print");
printer_close($handle);

LXXXV. Pspell Functions

Introdução

These functions allow you to check the spelling of a word and offer suggestions.

Nota: This extension is not available on Windows platforms.


Requisitos

To compile PHP with pspell support, you need the aspell and pspell libraries, available from http://aspell.sourceforge.net/ and http://aspell.net/ respectively.


Instalação

If you have the libraries needed add the --with-pspell[=dir] option when compiling PHP.


Configuração durante execução

Esta extenção não define nenhum parâmetro de configuração no php.ini.


Tipos Resource

Esta extensão não possui nenhum tipo resource.


Constantes Predefinidas

As contantes abaixo são definidas por esta extensão e somente estarão disponíveis quando a extensão foi compilada com o PHP ou carregada dinamicamente durante a execução.

PSPELL_FAST (integer)

PSPELL_NORMAL (integer)

PSPELL_BAD_SPELLERS (integer)

PSPELL_RUN_TOGETHER (integer)

Índice
pspell_add_to_personal -- Add the word to a personal wordlist
pspell_add_to_session -- Add the word to the wordlist in the current session
pspell_check -- Check a word
pspell_clear_session -- Clear the current session
pspell_config_create -- Create a config used to open a dictionary
pspell_config_ignore -- Ignore words less than N characters long
pspell_config_mode -- Change the mode number of suggestions returned
pspell_config_personal -- Set a file that contains personal wordlist
pspell_config_repl -- Set a file that contains replacement pairs
pspell_config_runtogether -- Consider run-together words as valid compounds
pspell_config_save_repl -- Determine whether to save a replacement pairs list along with the wordlist
pspell_new_config -- Load a new dictionary with settings based on a given config
pspell_new_personal -- Load a new dictionary with personal wordlist
pspell_new -- Load a new dictionary
pspell_save_wordlist -- Save the personal wordlist to a file
pspell_store_replacement -- Store a replacement pair for a word
pspell_suggest -- Suggest spellings of a word

pspell_add_to_personal

(PHP 4 >= 4.0.2)

pspell_add_to_personal -- Add the word to a personal wordlist

Description

int pspell_add_to_personal ( int dictionary_link, string word)

pspell_add_to_personal() adds a word to the personal wordlist. If you used pspell_new_config() with pspell_config_personal() to open the dictionary, you can save the wordlist later with pspell_save_wordlist(). Please, note that this function will not work unless you have pspell .11.2 and aspell .32.5 or later.

Exemplo 1. pspell_add_to_personal()

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

pspell_add_to_personal ($pspell_link, "Vlad");
pspell_save_wordlist ($pspell_link);

pspell_add_to_session

(PHP 4 >= 4.0.2)

pspell_add_to_session -- Add the word to the wordlist in the current session

Description

int pspell_add_to_session ( int dictionary_link, string word)

pspell_add_to_session() adds a word to the wordlist associated with the current session. It is very similar to pspell_add_to_personal()

pspell_check

(PHP 4 >= 4.0.2)

pspell_check -- Check a word

Description

bool pspell_check ( int dictionary_link, string word)

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

Exemplo 1. pspell_check()

$pspell_link = pspell_new ("en");

if (pspell_check ($pspell_link, "testt")) {
    echo "This is a valid spelling";
} else {
    echo "Sorry, wrong spelling";
}

pspell_clear_session

(PHP 4 >= 4.0.2)

pspell_clear_session -- Clear the current session

Description

int pspell_clear_session ( int dictionary_link)

pspell_clear_session() clears the current session. The current wordlist becomes blank, and, for example, if you try to save it with pspell_save_wordlist(), nothing happens.

Exemplo 1. pspell_add_to_personal()

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

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

pspell_config_create

(PHP 4 >= 4.0.2)

pspell_config_create -- Create a config used to open a dictionary

Description

int pspell_config_create ( string language [, string spelling [, string jargon [, string encoding]]])

pspell_config_create() has a very similar syntax to pspell_new(). In fact, using pspell_config_create() immediatelly followed by pspell_new_config() will produce the exact same result. However, after creating a new config, you can also use pspell_config_*() functions before calling pspell_new_config() to take advantage of some advanced functionality.

The language parameter is the language code which consists of the two letter ISO 639 language code and an optional two letter ISO 3166 country code after a dash or underscore.

The spelling parameter is the requested spelling for languages with more than one spelling such as English. Known values are 'american', 'british', and 'canadian'.

The jargon parameter contains extra information to distinguish two different words lists that have the same language and spelling parameters.

The encoding parameter is the encoding that words are expected to be in. Valid values are 'utf-8', 'iso8859-*', 'koi8-r', 'viscii', 'cp1252', 'machine unsigned 16', 'machine unsigned 32'. This parameter is largely untested, so be careful when using.

The mode parameter is the mode in which spellchecker will work. There are several modes available:

  • PSPELL_FAST - Fast mode (least number of suggestions)

  • PSPELL_NORMAL - Normal mode (more suggestions)

  • PSPELL_BAD_SPELLERS - Slow mode (a lot of suggestions)

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

Exemplo 1. pspell_config_create()

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

pspell_config_ignore

(PHP 4 >= 4.0.2)

pspell_config_ignore -- Ignore words less than N characters long

Description

int pspell_config_ignore ( int dictionary_link, int n)

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

Exemplo 1. pspell_config_ignore()

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

pspell_config_mode

(PHP 4 >= 4.0.2)

pspell_config_mode -- Change the mode number of suggestions returned

Description

int pspell_config_mode ( int dictionary_link, int mode)

pspell_config_mode() should be used on a config before calling pspell_new_config(). This function determines how many suggestions will be returned by pspell_suggest().

The mode parameter is the mode in which spellchecker will work. There are several modes available:

  • PSPELL_FAST - Fast mode (least number of suggestions)

  • PSPELL_NORMAL - Normal mode (more suggestions)

  • PSPELL_BAD_SPELLERS - Slow mode (a lot of suggestions)

Exemplo 1. pspell_config_mode()

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

pspell_config_personal

(PHP 4 >= 4.0.2)

pspell_config_personal -- Set a file that contains personal wordlist

Description

int pspell_config_personal ( int dictionary_link, string file)

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

Exemplo 1. pspell_config_personal()

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

pspell_config_repl

(PHP 4 >= 4.0.2)

pspell_config_repl -- Set a file that contains replacement pairs

Description

int pspell_config_repl ( int dictionary_link, string file)

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

Exemplo 1. pspell_config_repl()

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

pspell_config_runtogether

(PHP 4 >= 4.0.2)

pspell_config_runtogether -- Consider run-together words as valid compounds

Description

int pspell_config_runtogether ( int dictionary_link, bool flag)

pspell_config_runtogether() should be used on a config before calling pspell_new_config(). This function determines whether run-together words will be treated as legal compounds. That is, "thecat" will be a legal compound, athough there should be a space between the two words. Changing this setting only affects the results returned by pspell_check(); pspell_suggest() will still return suggestions.

Exemplo 1. pspell_config_runtogether()

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

pspell_config_save_repl

(PHP 4 >= 4.0.2)

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

Description

int pspell_config_save_repl ( int dictionary_link, bool flag)

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

pspell_new_config

(PHP 4 >= 4.0.2)

pspell_new_config -- Load a new dictionary with settings based on a given config

Description

int pspell_new_config ( int config)

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

The config parameter is the one returned by pspell_config_create() when the config was created.

Exemplo 1. pspell_new_config()

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

pspell_new_personal

(PHP 4 >= 4.0.2)

pspell_new_personal -- Load a new dictionary with personal wordlist

Description

int pspell_new_personal ( string personal, string language [, string spelling [, string jargon [, string encoding [, int mode]]]])

pspell_new_personal() opens up a new dictionary with a personal wordlist and returns the dictionary link identifier for use in other pspell functions. The wordlist can be modified and saved with pspell_save_wordlist(), if desired. However, the replacement pairs are not saved. In order to save replacement pairs, you should create a config using pspell_config_create(), set the personal wordlist file with pspell_config_personal(), set the file for replacement pairs with pspell_config_repl(), and open a new dictionary with pspell_new_config().

The personal parameter specifies the file where words added to the personal list will be stored. It should be an absolute filename beginning with '/' because otherwise it will be relative to $HOME, which is "/root" for most systems, and is probably not what you want.

The language parameter is the language code which consists of the two letter ISO 639 language code and an optional two letter ISO 3166 country code after a dash or underscore.

The spelling parameter is the requested spelling for languages with more than one spelling such as English. Known values are 'american', 'british', and 'canadian'.

The jargon parameter contains extra information to distinguish two different words lists that have the same language and spelling parameters.

The encoding parameter is the encoding that words are expected to be in. Valid values are 'utf-8', 'iso8859-*', 'koi8-r', 'viscii', 'cp1252', 'machine unsigned 16', 'machine unsigned 32'. This parameter is largely untested, so be careful when using.

The mode parameter is the mode in which spellchecker will work. There are several modes available:

  • PSPELL_FAST - Fast mode (least number of suggestions)

  • PSPELL_NORMAL - Normal mode (more suggestions)

  • PSPELL_BAD_SPELLERS - Slow mode (a lot of suggestions)

  • PSPELL_RUN_TOGETHER - Consider run-together words as legal compounds. That is, "thecat" will be a legal compound, athough there should be a space between the two words. Changing this setting only affects the results returned by pspell_check(); pspell_suggest() will still return suggestions.

Mode is a bitmask constructed from different constants listed above. However, PSPELL_FAST, PSPELL_NORMAL and PSPELL_BAD_SPELLERS are mutually exclusive, so you should select only one of them.

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

Exemplo 1. pspell_new_personal()

$pspell_link = pspell_new_personal ("/var/dictionaries/custom.pws", 
        "en", "", "", "", PSPELL_FAST|PSPELL_RUN_TOGETHER));

pspell_new

(PHP 4 >= 4.0.2)

pspell_new -- Load a new dictionary

Description

int pspell_new ( string language [, string spelling [, string jargon [, string encoding [, int mode]]]])

pspell_new() opens up a new dictionary and returns the dictionary link identifier for use in other pspell functions.

The language parameter is the language code which consists of the two letter ISO 639 language code and an optional two letter ISO 3166 country code after a dash or underscore.

The spelling parameter is the requested spelling for languages with more than one spelling such as English. Known values are 'american', 'british', and 'canadian'.

The jargon parameter contains extra information to distinguish two different words lists that have the same language and spelling parameters.

The encoding parameter is the encoding that words are expected to be in. Valid values are 'utf-8', 'iso8859-*', 'koi8-r', 'viscii', 'cp1252', 'machine unsigned 16', 'machine unsigned 32'. This parameter is largely untested, so be careful when using.

The mode parameter is the mode in which spellchecker will work. There are several modes available:

  • PSPELL_FAST - Fast mode (least number of suggestions)

  • PSPELL_NORMAL - Normal mode (more suggestions)

  • PSPELL_BAD_SPELLERS - Slow mode (a lot of suggestions)

  • PSPELL_RUN_TOGETHER - Consider run-together words as legal compounds. That is, "thecat" will be a legal compound, athough there should be a space between the two words. Changing this setting only affects the results returned by pspell_check(); pspell_suggest() will still return suggestions.

Mode is a bitmask constructed from different constants listed above. However, PSPELL_FAST, PSPELL_NORMAL and PSPELL_BAD_SPELLERS are mutually exclusive, so you should select only one of them.

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

Exemplo 1. pspell_new()

$pspell_link = pspell_new ("en", "", "", "", 
                           (PSPELL_FAST|PSPELL_RUN_TOGETHER));

pspell_save_wordlist

(PHP 4 >= 4.0.2)

pspell_save_wordlist -- Save the personal wordlist to a file

Description

int pspell_save_wordlist ( int dictionary_link)

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

Exemplo 1. pspell_add_to_personal()

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

pspell_add_to_personal ($pspell_link, "Vlad");
pspell_save_wordlist ($pspell_link);

pspell_store_replacement

(PHP 4 >= 4.0.2)

pspell_store_replacement -- Store a replacement pair for a word

Description

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

pspell_store_replacement() stores a replacement pair for a word, so that replacement can be returned by pspell_suggest() later. In order to be able to take advantage of this function, you have to use pspell_new_personal() to open the dictionary. In order to permanently save the replacement pair, you have to use pspell_config_personal() and pspell_config_repl() to set the path where to save your custom wordlists, and then use pspell_save_wordlist() for the changes to be written to disk. Please, note that this function will not work unless you have pspell .11.2 and aspell .32.5 or later.

Exemplo 1. pspell_store_replacement()

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

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

pspell_suggest

(PHP 4 >= 4.0.2)

pspell_suggest -- Suggest spellings of a word

Description

array pspell_suggest ( int dictionary_link, string word)

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

Exemplo 1. pspell_suggest()

$pspell_link = pspell_new ("en");

if (!pspell_check ($pspell_link, "testt")) {
    $suggestions = pspell_suggest ($pspell_link, "testt");

    foreach ($suggestions as $suggestion) {
        echo "Possible spelling: $suggestion<br>"; 
    }
}

LXXXVI. GNU Readline

Introdução

The readline() functions implement an interface to the GNU Readline library. These are functions that provide editable command lines. An example being the way Bash allows you to use the arrow keys to insert characters or scroll through command history. Because of the 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.

Nota: This extension is not available on Windows platforms.


Requisitos

To use the readline functions, you need to install libreadline. You can find libreadline on the home page of the GNU Readline project, at http://cnswww.cns.cwru.edu/~chet/readline/rltop.html. It's maintained by Chet Ramey, who's also the author of Bash.

You can also use this functions with the libedit library, a non-GPL replacement for the readline library. The libedit library is BSD licensend and available for download from http://cnswww.cns.cwru.edu/~chet/readline/rltop.html.


Instalação

To use this functions you must compile the CGI or CLI version of PHP with readline support. You need to configure PHP --with-readline[=DIR]. In order you want to use the libedit readline replacement, configure PHP --with-libedit[=DIR].


Configuração durante execução

Esta extenção não define nenhum parâmetro de configuração no php.ini.


Tipos Resource

Esta extensão não possui nenhum tipo resource.


Constantes Predefinidas

Esta extensão não possui nenhuma constante.

Índice
readline_add_history -- Adds a line to the history
readline_clear_history -- Clears the history
readline_completion_function -- Registers a completion function
readline_info -- Gets/sets various internal readline variables
readline_list_history -- Lists the history
readline_read_history -- Reads the history
readline_write_history -- Writes the history
readline -- Reads a line

readline_add_history

(PHP 4 )

readline_add_history -- Adds a line to the history

Description

void readline_add_history ( string line)

This function adds a line to the command line history.

readline_clear_history

(PHP 4 )

readline_clear_history -- Clears the history

Description

bool readline_clear_history ( void)

This function clears the entire command line history.

readline_completion_function

(PHP 4 )

readline_completion_function -- Registers a completion function

Description

bool readline_completion_function ( string line)

This function registers a completion function. You must supply the name of an existing function which accepts a partial command line and returns an array of possible matches. This is the same kind of functionality you'd get if you hit your tab key while using Bash.

readline_info

(PHP 4 )

readline_info -- Gets/sets various internal readline variables

Description

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

If called with no parameters, this function returns an array of values for all the setting readline uses. The elements will be indexed by the following values: done, end, erase_empty_line, library_version, line_buffer, mark, pending_input, point, prompt, readline_name, and terminal_name.

If called with one parameter, the value of that setting is returned. If called with two parameters, the setting will be changed to the given value.

readline_list_history

(PHP 4 )

readline_list_history -- Lists the history

Description

array readline_list_history ( void)

This function returns an array of the entire command line history. The elements are indexed by integers starting at zero.

readline_read_history

(PHP 4 )

readline_read_history -- Reads the history

Description

bool readline_read_history ( string filename)

This function reads a command history from a file.

readline_write_history

(PHP 4 )

readline_write_history -- Writes the history

Description

bool readline_write_history ( string filename)

This function writes the command history to a file.

readline

(PHP 4 )

readline -- Reads a line

Description

string readline ( [string prompt])

This function returns a single string from the user. You may specify a string with which to prompt the user. The line returned has the ending newline removed. You must add this line to the history yourself using readline_add_history().

Exemplo 1. readline()

//get 3 commands from user
for ($i=0; $i < 3; $i++) {
        $line = readline ("Command: ");
        readline_add_history ($line);
}

//dump history
print_r (readline_list_history());

//dump variables
print_r (readline_info());

LXXXVII. GNU Recode functions

Introdução

This module contains an interface to the GNU Recode library, version 3.5. The GNU Recode library converts files between various coded character sets and surface encodings. When this cannot be achieved exactly, it may get rid of the offending characters or fall back on approximations. The library recognises or produces nearly 150 different character sets and is able to convert files between almost any pair. Most RFC 1345 character sets are supported.

Nota: This extension is not available on Windows platforms.


Requisitos

You must have GNU Recode 3.5 or higher installed on your system. You can download the package from here.


Instalação

To be able to use the functions defined in this module you must compile your PHP interpreter using the --with-recode[=DIR] option.

Atenção

Crashes and startup problems of PHP may be encountered when loading the recode as extension after loading any extension of mysql or imap. Loading the recode before those extension has proven to fix the problem. This is due a technical problem that both the c-client library used by imap and recode have their own hash_lookup() function and both mysql and recode have their own hash_insert function.

Atenção

The IMAP extension cannot be used in conjuction with the recode or YAZ extensions. This is due to the fact that they both share the same internal symbol.


Configuração durante execução

Esta extenção não define nenhum parâmetro de configuração no php.ini.


Tipos Resource

Esta extensão não possui nenhum tipo resource.


Constantes Predefinidas

Esta extensão não possui nenhuma constante.

Índice
recode_file --  Recode from file to file according to recode request
recode_string -- Recode a string according to a recode request
recode -- Recode a string according to a recode request

recode_file

(PHP 3>= 3.0.13, PHP 4 )

recode_file --  Recode from file to file according to recode request

Description

bool recode_file ( string request, resource input, resource output)

Recode the file referenced by file handle input into the file referenced by file handle output according to the recode request. Returns FALSE, if unable to comply, TRUE otherwise.

This function does not currently process filehandles referencing remote files (URLs). Both filehandles must refer to local files.

Exemplo 1. Basic recode_file() example

$input = fopen ('input.txt', 'r');
$output = fopen ('output.txt', 'w');
recode_file ("us..flat", $input, $output);

recode_string

(PHP 3>= 3.0.13, PHP 4 )

recode_string -- Recode a string according to a recode request

Description

string recode_string ( string request, string string)

Recode the string string according to the recode request request. Returns the recoded string or FALSE, if unable to perform the recode request.

A simple recode request may be "lat1..iso646-de". See also the GNU Recode documentation of your installation for detailed instructions about recode requests.

Exemplo 1. Basic recode_string() example:

print recode_string ("us..flat", "The following character has a diacritical mark: &aacute;");

recode

(PHP 4 )

recode -- Recode a string according to a recode request

Description

string recode ( string request, string string)

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

LXXXVIII. Regular Expression Functions (Perl-Compatible)

Introdução

The syntax for patterns used in these functions closely resembles Perl. The expression should be enclosed in the delimiters, a forward slash (/), for example. Any character can be used for delimiter as long as it's not alphanumeric or backslash (\). If the delimiter character has to be used in the expression itself, it needs to be escaped by backslash. Since PHP 4.0.4, you can also use Perl-style (), {}, [], and <> matching delimiters.

The ending delimiter may be followed by various modifiers that affect the matching. See Pattern Modifiers.

PHP also supports regular expressions using a POSIX-extended syntax using the POSIX-extended regex functions..


Requisitos

Regular expression support is provided by the PCRE library package, which is open source software, written by Philip Hazel, and copyright by the University of Cambridge, England. It is available at ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/.


Instalação

Beginning with PHP 4.2.0 these functions are enabled by default. You can disable the pcre functions with --without-pcre-regex. Use --with-pcre-regex=DIR to specify DIR where PCRE's include and library files are located, if not using bundled library. For older versions you have to configure and compile PHP with --with-pcre-regex[=DIR] in order to use these functions.

The windows version of PHP has built in support for this extension. You do not need to load any additional extension in order to use these functions.


Configuração durante execução

Esta extenção não define nenhum parâmetro de configuração no php.ini.


Tipos Resource

Esta extensão não possui nenhum tipo resource.


Constantes Predefinidas

As contantes abaixo são definidas por esta extensão e somente estarão disponíveis quando a extensão foi compilada com o PHP ou carregada dinamicamente durante a execução.

Tabela 1. PREG constants

constant description
PREG_PATTERN_ORDER Orders results so that $matches[0] is an array of full pattern matches, $matches[1] is an array of strings matched by the first parenthesized subpattern, and so on. This flag is only used with preg_match_all().
PREG_SET_ORDER Orders results so that $matches[0] is an array of first set of matches, $matches[1] is an array of second set of matches, and so on. This flag is only used with preg_match_all().
PREG_OFFSET_CAPTURE See the description of PREG_SPLIT_OFFSET_CAPTURE. This flag is available since PHP 4.3.0 .
PREG_SPLIT_NO_EMPTY This flag tells preg_split() to only return only non-empty pieces.
PREG_SPLIT_DELIM_CAPTURE This flag tells preg_split() to capture parenthesized expression in the delimiter pattern as well. This flag is available since PHP 4.0.5 .
PREG_SPLIT_OFFSET_CAPTURE If this flag is set, for every occuring match the appendant string offset will also be returned. Note that this changes the return value in an array where very element is an array consisting of the matched string at offset 0 and it's string offset into subject at offset 1. This flag is available since PHP 4.3.0 and is only used for preg_split().

Exemplos

Exemplo 1. Examples of valid patterns

  • /<\/\w+>/

  • |(\d{3})-\d+|Sm

  • /^(?i)php[34]/

  • {^\s+(\s+)?$}

Exemplo 2. Examples of invalid patterns

  • /href='(.*)' - missing ending delimiter

  • /\w+\s*\w+/J - unknown modifier 'J'

  • 1-\d3-\d3-\d4| - missing starting delimiter

Índice
Pattern Modifiers -- Describes possible modifiers in regex patterns
Pattern Syntax -- Describes PCRE regex syntax
preg_grep --  Return array entries that match the pattern
preg_match_all -- Perform a global regular expression match
preg_match -- Perform a regular expression match
preg_quote -- Quote regular expression characters
preg_replace_callback -- Perform a regular expression search and replace using a callback
preg_replace -- Perform a regular expression search and replace
preg_split -- Split string by a regular expression

Pattern Modifiers

Pattern Modifiers -- Describes possible modifiers in regex patterns

Description

The current possible PCRE modifiers are listed below. The names in parentheses refer to internal PCRE names for these modifiers.

i (PCRE_CASELESS)

If this modifier is set, letters in the pattern match both upper and lower case letters.

m (PCRE_MULTILINE)

By default, PCRE treats the subject string as consisting of a single "line" of characters (even if it actually contains several newlines). The "start of line" metacharacter (^) matches only at the start of the string, while the "end of line" metacharacter ($) matches only at the end of the string, or before a terminating newline (unless D modifier is set). This is the same as Perl.

When this modifier is set, the "start of line" and "end of line" constructs match immediately following or immediately before any newline in the subject string, respectively, as well as at the very start and end. This is equivalent to Perl's /m modifier. If there are no "\n" characters in a subject string, or no occurrences of ^ or $ in a pattern, setting this modifier has no effect.

s (PCRE_DOTALL)

If this modifier is set, a dot metacharacter in the pattern matches all characters, including newlines. Without it, newlines are excluded. This modifier is equivalent to Perl's /s modifier. A negative class such as [^a] always matches a newline character, independent of the setting of this modifier.

x (PCRE_EXTENDED)

If this modifier is set, whitespace data characters in the pattern are totally ignored except when escaped or inside a character class, and characters between an unescaped # outside a character class and the next newline character, inclusive, are also ignored. This is equivalent to Perl's /x modifier, and makes it possible to include comments inside complicated patterns. Note, however, that this applies only to data characters. Whitespace characters may never appear within special character sequences in a pattern, for example within the sequence (?( which introduces a conditional subpattern.

e

If this modifier is set, preg_replace() does normal substitution of backreferences in the replacement string, evaluates it as PHP code, and uses the result for replacing the search string.

Only preg_replace() uses this modifier; it is ignored by other PCRE functions.

Nota: This modifier was not available in PHP3.

A (PCRE_ANCHORED)

If this modifier is set, the pattern is forced to be "anchored", that is, it is constrained to match only at the start of the string which is being searched (the "subject string"). This effect can also be achieved by appropriate constructs in the pattern itself, which is the only way to do it in Perl.

D (PCRE_DOLLAR_ENDONLY)

If this modifier is set, a dollar metacharacter in the pattern matches only at the end of the subject string. Without this modifier, a dollar also matches immediately before the final character if it is a newline (but not before any other newlines). This modifier is ignored if m modifier is set. There is no equivalent to this modifier in Perl.

S

When a pattern is going to be used several times, it is worth spending more time analyzing it in order to speed up the time taken for matching. If this modifier is set, then this extra analysis is performed. At present, studying a pattern is useful only for non-anchored patterns that do not have a single fixed starting character.

U (PCRE_UNGREEDY)

This modifier inverts the "greediness" of the quantifiers so that they are not greedy by default, but become greedy if followed by "?". It is not compatible with Perl. It can also be set by a (?U) modifier setting within the pattern.

X (PCRE_EXTRA)

This modifier turns on additional functionality of PCRE that is incompatible with Perl. Any backslash in a pattern that is followed by a letter that has no special meaning causes an error, thus reserving these combinations for future expansion. By default, as in Perl, a backslash followed by a letter with no special meaning is treated as a literal. There are at present no other features controlled by this modifier.

u (PCRE_UTF8)

This modifier turns on additional functionality of PCRE that is incompatible with Perl. Pattern strings are treated as UTF-8. This modifier is available from PHP 4.1.0 or greater on Unix and from PHP 4.2.3 on win32.

Pattern Syntax

Pattern Syntax -- Describes PCRE regex syntax

Description

The PCRE library is a set of functions that implement regular expression pattern matching using the same syntax and semantics as Perl 5, with just a few differences (see below). The current implementation corresponds to Perl 5.005.

Differences From Perl

The differences described here are with respect to Perl 5.005.

  1. By default, a whitespace character is any character that the C library function isspace() recognizes, though it is possible to compile PCRE with alternative character type tables. Normally isspace() matches space, formfeed, newline, carriage return, horizontal tab, and vertical tab. Perl 5 no longer includes vertical tab in its set of whitespace characters. The \v escape that was in the Perl documentation for a long time was never in fact recognized. However, the character itself was treated as whitespace at least up to 5.002. In 5.004 and 5.005 it does not match \s.

  2. PCRE does not allow repeat quantifiers on lookahead assertions. Perl permits them, but they do not mean what you might think. For example, (?!a){3} does not assert that the next three characters are not "a". It just asserts that the next character is not "a" three times.

  3. Capturing subpatterns that occur inside negative looka- head assertions are counted, but their entries in the offsets vector are never set. Perl sets its numerical vari- ables from any such patterns that are matched before the assertion fails to match something (thereby succeeding), but only if the negative lookahead assertion contains just one branch.

  4. Though binary zero characters are supported in the subject string, they are not allowed in a pattern string because it is passed as a normal C string, terminated by zero. The escape sequence "\\x00" can be used in the pattern to represent a binary zero.

  5. The following Perl escape sequences are not supported: \l, \u, \L, \U, \E, \Q. In fact these are implemented by Perl's general string-handling and are not part of its pat- tern matching engine.

  6. The Perl \G assertion is not supported as it is not relevant to single pattern matches.

  7. Fairly obviously, PCRE does not support the (?{code}) construction.

  8. There are at the time of writing some oddities in Perl 5.005_02 concerned with the settings of captured strings when part of a pattern is repeated. For example, matching "aba" against the pattern /^(a(b)?)+$/ sets $2 to the value "b", but matching "aabbaa" against /^(aa(bb)?)+$/ leaves $2 unset. However, if the pattern is changed to /^(aa(b(b))?)+$/ then $2 (and $3) get set. In Perl 5.004 $2 is set in both cases, and that is also TRUE of PCRE. If in the future Perl changes to a consistent state that is different, PCRE may change to follow.

  9. Another as yet unresolved discrepancy is that in Perl 5.005_02 the pattern /^(a)?(?(1)a|b)+$/ matches the string "a", whereas in PCRE it does not. However, in both Perl and PCRE /^(a)?a/ matched against "a" leaves $1 unset.

  10. PCRE provides some extensions to the Perl regular expression facilities:

    1. Although lookbehind assertions must match fixed length strings, each alternative branch of a lookbehind assertion can match a different length of string. Perl 5.005 requires them all to have the same length.

    2. If PCRE_DOLLAR_ENDONLY is set and PCRE_MULTILINE is not set, the $ meta- character matches only at the very end of the string.

    3. If PCRE_EXTRA is set, a backslash followed by a letter with no special meaning is faulted.

    4. If PCRE_UNGREEDY is set, the greediness of the repeti- tion quantifiers is inverted, that is, by default they are not greedy, but if followed by a question mark they are.

Regular Expression Details

Introduction

The syntax and semantics of the regular expressions sup- ported by PCRE are described below. Regular expressions are also described in the Perl documentation and in a number of other books, some of which have copious examples. Jeffrey Friedl's "Mastering Regular Expressions", published by O'Reilly (ISBN 1-56592-257-3), covers them in great detail. The description here is intended as reference documentation. A regular expression is a pattern that is matched against a subject string from left to right. Most characters stand for themselves in a pattern, and match the corresponding charac- ters in the subject. As a trivial example, the pattern The quick brown fox matches a portion of a subject string that is identical to itself.

Meta-characters

The power of regular expressions comes from the ability to include alternatives and repetitions in the pat- tern. These are encoded in the pattern by the use of meta- characters, which do not stand for themselves but instead are interpreted in some special way.

There are two different sets of meta-characters: those that are recognized anywhere in the pattern except within square brackets, and those that are recognized in square brackets. Outside square brackets, the meta-characters are as follows:

\

general escape character with several uses

^

assert start of subject (or line, in multiline mode)

$

assert end of subject (or line, in multiline mode)

.

match any character except newline (by default)

[

start character class definition

]

end character class definition

|

start of alternative branch

(

start subpattern

)

end subpattern

?

extends the meaning of (, also 0 or 1 quantifier, also quantifier minimizer

*

0 or more quantifier

+

1 or more quantifier

{

start min/max quantifier

}

end min/max quantifier

Part of a pattern that is in square brackets is called a "character class". In a character class the only meta- characters are:

\

general escape character

^

negate the class, but only if the first character

-

indicates character range

]

terminates the character class

The following sections describe the use of each of the meta-characters.

backslash

The backslash character has several uses. Firstly, if it is followed by a non-alphanumeric character, it takes away any special meaning that character may have. This use of backslash as an escape character applies both inside and outside character classes.

For example, if you want to match a "*" character, you write "\*" in the pattern. This applies whether or not the follow- ing character would otherwise be interpreted as a meta- character, so it is always safe to precede a non-alphanumeric with "\" to specify that it stands for itself. In particu- lar, if you want to match a backslash, you write "\\".

If a pattern is compiled with the PCRE_EXTENDED option, whi- tespace in the pattern (other than in a character class) and characters between a "#" outside a character class and the next newline character are ignored. An escaping backslash can be used to include a whitespace or "#" character as part of the pattern.

A second use of backslash provides a way of encoding non- printing characters in patterns in a visible manner. There is no restriction on the appearance of non-printing characters, apart from the binary zero that terminates a pattern, but when a pattern is being prepared by text editing, it is usually easier to use one of the following escape sequences than the binary character it represents:

\a

alarm, that is, the BEL character (hex 07)

\cx

"control-x", where x is any character

\e

escape (hex 1B)

\f

formfeed (hex 0C)

\n

newline (hex 0A)

\r

carriage return (hex 0D)

\t

tab (hex 09)

\xhh

character with hex code hh

\ddd

character with octal code ddd, or backreference

The precise effect of "\cx" is as follows: if "x" is a lower case letter, it is converted to upper case. Then bit 6 of the character (hex 40) is inverted. Thus "\cz" becomes hex 1A, but "\c{" becomes hex 3B, while "\c;" becomes hex 7B.

After "\x", up to two hexadecimal digits are read (letters can be in upper or lower case).

After "\0" up to two further octal digits are read. In both cases, if there are fewer than two digits, just those that are present are used. Thus the sequence "\0\x\07" specifies two binary zeros followed by a BEL character. Make sure you supply two digits after the initial zero if the character that follows is itself an octal digit.

The handling of a backslash followed by a digit other than 0 is complicated. Outside a character class, PCRE reads it and any following digits as a decimal number. If the number is less than 10, or if there have been at least that many previous capturing left parentheses in the expression, the entire sequence is taken as a back reference. A description of how this works is given later, following the discussion of parenthesized subpatterns.

Inside a character class, or if the decimal number is greater than 9 and there have not been that many capturing subpatterns, PCRE re-reads up to three octal digits following the backslash, and generates a single byte from the least significant 8 bits of the value. Any subsequent digits stand for themselves. For example:

\040

is another way of writing a space

\40

is the same, provided there are fewer than 40 previous capturing subpatterns

\7

is always a back reference

\11

might be a back reference, or another way of writing a tab

\011

is always a tab

\0113

is a tab followed by the character "3"

\113

is the character with octal code 113 (since there can be no more than 99 back references)

\377

is a byte consisting entirely of 1 bits

\81

is either a back reference, or a binary zero followed by the two characters "8" and "1"

Note that octal values of 100 or greater must not be intro- duced by a leading zero, because no more than three octal digits are ever read.

All the sequences that define a single byte value can be used both inside and outside character classes. In addition, inside a character class, the sequence "\b" is interpreted as the backspace character (hex 08). Outside a character class it has a different meaning (see below).

The third use of backslash is for specifying generic charac- ter types:

\d

any decimal digit

\D

any character that is not a decimal digit

\s

any whitespace character

\S

any character that is not a whitespace character

\w

any "word" character

\W

any "non-word" character

Each pair of escape sequences partitions the complete set of characters into two disjoint sets. Any given character matches one, and only one, of each pair.

A "word" character is any letter or digit or the underscore character, that is, any character which can be part of a Perl "word". The definition of letters and digits is controlled by PCRE's character tables, and may vary if locale-specific matching is taking place (see "Locale support" above). For example, in the "fr" (French) locale, some char- acter codes greater than 128 are used for accented letters, and these are matched by \w.

These character type sequences can appear both inside and outside character classes. They each match one character of the appropriate type. If the current matching point is at the end of the subject string, all of them fail, since there is no character to match.

The fourth use of backslash is for certain simple asser- tions. An assertion specifies a condition that has to be met at a particular point in a match, without consuming any characters from the subject string. The use of subpatterns for more complicated assertions is described below. The backslashed assertions are

\b

word boundary

\B

not a word boundary

\A

start of subject (independent of multiline mode)

\Z

end of subject or newline at end (independent of multiline mode)

\z

end of subject(independent of multiline mode)

These assertions may not appear in character classes (but note that "\b" has a different meaning, namely the backspace character, inside a character class).

A word boundary is a position in the subject string where the current character and the previous character do not both match \w or \W (i.e. one matches \w and the other matches \W), or the start or end of the string if the first or last character matches \w, respectively.

The \A, \Z, and \z assertions differ from the traditional circumflex and dollar (described below) in that they only ever match at the very start and end of the subject string, whatever options are set. They are not affected by the PCRE_NOTBOL or PCRE_NOTEOL options. The difference between \Z and \z is that \Z matches before a newline that is the last character of the string as well as at the end of the string, whereas \z matches only at the end.

Circumflex and dollar


     Outside a character class, in the default matching mode, the
     circumflex  character  is an assertion which is true only if
     the current matching point is at the start  of  the  subject
     string. Inside a character class, circumflex has an entirely
     different meaning (see below).

     Circumflex need not be the first character of the pattern if
     a number of alternatives are involved, but it should be the
     first thing in each alternative in which it appears  if  the
     pattern is ever to match that branch. If all possible alter-
     natives start with a circumflex, that is, if the pattern  is
     constrained to match only at the start of the subject, it is
     said to be an "anchored" pattern. (There are also other con-
     structs that can cause a pattern to be anchored.)

     A dollar character is an assertion which is TRUE only if the
     current  matching point is at the end of the subject string,
     or immediately before a newline character that is  the  last
     character in the string (by default). Dollar need not be the
     last character of the pattern if a  number  of  alternatives
     are  involved,  but it should be the last item in any branch
     in which it appears.  Dollar has no  special  meaning  in  a
     character class.

     The meaning of dollar can be changed so that it matches only
     at   the   very   end   of   the   string,  by  setting  the
     PCRE_DOLLAR_ENDONLY
     option at compile or matching time. This
     does not affect the \Z assertion.

     The meanings of the circumflex  and  dollar  characters  are
     changed  if  the  PCRE_MULTILINE  option is set. When this is
     the case,  they  match  immediately  after  and  immediately
     before an internal "\n" character, respectively, in addition
     to matching at the start and end of the subject string.  For
     example,  the  pattern  /^abc$/  matches  the subject string
     "def\nabc" in multiline  mode,  but  not  otherwise.  Conse-
     quently,  patterns  that  are  anchored  in single line mode
     because all branches start with "^" are not anchored in mul-
     tiline  mode.  The  PCRE_DOLLAR_ENDONLY  option is ignored if
     PCRE_MULTILINE  is set.

     Note that the sequences \A, \Z, and \z can be used to  match
     the  start  and end of the subject in both modes, and if all
     branches of a pattern start with \A is it  always  anchored,
     whether PCRE_MULTILINE  is set or not.
     

FULL STOP


     Outside a character class, a dot in the pattern matches  any
     one  character  in  the  subject,  including  a non-printing
     character, but not (by default) newline.  If the PCRE_DOTALL 
     option  is  set,  then dots match newlines as well. The han-
     dling of dot is entirely independent of the handling of cir-
     cumflex  and  dollar,  the only relationship being that they
     both involve newline characters.  Dot has no special meaning
     in a character class.
     

Square brackets


     An opening square bracket introduces a character class, ter-
     minated  by  a  closing  square  bracket.  A  closing square
     bracket on its own is  not  special.  If  a  closing  square
     bracket  is  required as a member of the class, it should be
     the first data character in the class (after an initial cir-
     cumflex, if present) or escaped with a backslash.

     A character class matches a single character in the subject;
     the  character  must  be in the set of characters defined by
     the class, unless the first character in the class is a cir-
     cumflex,  in which case the subject character must not be in
     the set defined by the class. If a  circumflex  is  actually
     required  as  a  member  of  the class, ensure it is not the
     first character, or escape it with a backslash.

     For example, the character class [aeiou] matches  any  lower
     case vowel, while [^aeiou] matches any character that is not
     a lower case vowel. Note that a circumflex is  just  a  con-
     venient  notation for specifying the characters which are in
     the class by enumerating those that are not. It  is  not  an
     assertion:  it  still  consumes a character from the subject
     string, and fails if the current pointer is at  the  end  of
     the string.

     When caseless matching  is  set,  any  letters  in  a  class
     represent  both their upper case and lower case versions, so
     for example, a caseless [aeiou] matches "A" as well as  "a",
     and  a caseless [^aeiou] does not match "A", whereas a case-
     ful version would.

     The newline character is never treated in any special way in
     character  classes,  whatever the setting of the PCRE_DOTALL 
     or PCRE_MULTILINE  options is. A  class  such  as  [^a]  will
     always match a newline.

     The minus (hyphen) character can be used to specify a  range
     of  characters  in  a  character  class.  For example, [d-m]
     matches any letter between d and m, inclusive.  If  a  minus
     character  is required in a class, it must be escaped with a
     backslash or appear in a position where it cannot be  inter-
     preted as indicating a range, typically as the first or last
     character in the class.
     
     It is not possible to have the literal character "]" as  the
     end  character  of  a  range.  A  pattern such as [W-]46] is
     interpreted as a class of two characters ("W" and "-")  fol-
     lowed by a literal string "46]", so it would match "W46]" or
     "-46]". However, if the "]" is escaped with a  backslash  it
     is  interpreted  as  the end of range, so [W-\]46] is inter-
     preted as a single class containing a range followed by  two
     separate characters. The octal or hexadecimal representation
     of "]" can also be used to end a range.

     Ranges operate in ASCII collating sequence. They can also be
     used  for  characters  specified  numerically,  for  example
     [\000-\037]. If a range that includes letters is  used  when
     caseless  matching  is set, it matches the letters in either
     case. For example, [W-c] is equivalent  to  [][\^_`wxyzabc],
     matched  caselessly,  and  if  character tables for the "fr"
     locale are in use, [\xc8-\xcb] matches accented E characters
     in both cases.

     The character types \d, \D, \s, \S,  \w,  and  \W  may  also
     appear  in  a  character  class, and add the characters that
     they match to the class. For example, [\dABCDEF] matches any
     hexadecimal  digit.  A  circumflex  can conveniently be used
     with the upper case character types to specify a  more  res-
     tricted set of characters than the matching lower case type.
     For example, the class [^\W_] matches any letter  or  digit,
     but not underscore.

     All non-alphanumeric characters other than \,  -,  ^  (at  the
     start)  and  the  terminating ] are non-special in character
     classes, but it does no harm if they are escaped.
     

Vertical bar


     Vertical bar characters are  used  to  separate  alternative
     patterns. For example, the pattern

       gilbert|sullivan

     matches either "gilbert" or "sullivan". Any number of alternatives
     may  appear,  and an empty alternative is permitted
     (matching the empty string).   The  matching  process  tries
     each  alternative in turn, from left to right, and the first
     one that succeeds is used. If the alternatives are within  a
     subpattern  (defined  below),  "succeeds" means matching the
     rest of the main pattern as well as the alternative  in  the
     subpattern.
     

Internal option setting


     The settings of PCRE_CASELESS , 
     PCRE_MULTILINE ,  
     PCRE_DOTALL ,
     and  PCRE_EXTENDED  can be changed from within the pattern by
     a sequence of Perl option letters enclosed between "(?"  and
     ")". The option letters are

       i  for PCRE_CASELESS 
       m  for PCRE_MULTILINE 
       s  for PCRE_DOTALL 
       x  for PCRE_EXTENDED 

     For example, (?im) sets caseless, multiline matching. It  is
     also possible to unset these options by preceding the letter
     with a hyphen, and a combined setting and unsetting such  as
     (?im-sx),  which sets PCRE_CASELESS  and PCRE_MULTILINE  while
     unsetting PCRE_DOTALL  and PCRE_EXTENDED , is also  permitted.
     If  a  letter  appears both before and after the hyphen, the
     option is unset.

     The scope of these option changes depends on  where  in  the
     pattern  the  setting  occurs. For settings that are outside
     any subpattern (defined below), the effect is the same as if
     the  options were set or unset at the start of matching. The
     following patterns all behave in exactly the same way:

       (?i)abc
       a(?i)bc
       ab(?i)c
       abc(?i)

     which in turn is the same as compiling the pattern abc  with
     PCRE_CASELESS set.
     In  other words, such "top level" settings apply to the whole
     pattern  (unless  there  are  other changes  inside subpatterns).
     If there is more than one setting of the same option at top level,
     the rightmost  setting is used.

     If an option change occurs inside a subpattern,  the  effect
     is  different.  This is a change of behaviour in Perl 5.005.
     An option change inside a subpattern affects only that  part
     of the subpattern that follows it, so

       (a(?i)b)c

     matches  abc  and  aBc  and  no  other   strings   (assuming
     PCRE_CASELESS   is  not used).  By this means, options can be
     made to have different settings in different  parts  of  the
     pattern.  Any  changes  made  in one alternative do carry on
     into subsequent branches within  the  same  subpattern.  For
     example,

       (a(?i)b|c)

     matches "ab", "aB", "c", and "C", even though when  matching
     "C" the first branch is abandoned before the option setting.
     This is because the effects of  option  settings  happen  at
     compile  time. There would be some very weird behaviour otherwise.

     The PCRE-specific options PCRE_UNGREEDY  and  
     PCRE_EXTRA   can
     be changed in the same way as the Perl-compatible options by
     using the characters U and X  respectively.  The  (?X)  flag
     setting  is  special in that it must always occur earlier in
     the pattern than any of the additional features it turns on,
     even when it is at top level. It is best put at the start.
     

subpatterns


     Subpatterns are delimited by parentheses  (round  brackets),
     which can be nested.  Marking part of a pattern as a subpattern
     does two things:

     1. It localizes a set of alternatives. For example, the pat-
     tern

       cat(aract|erpillar|)

     matches one of the words "cat",  "cataract",  or  "caterpillar".
     Without  the  parentheses, it would match "cataract",
     "erpillar" or the empty string.

     2. It sets up the subpattern as a capturing  subpattern  (as
     defined  above).   When the whole pattern matches, that portion
     of the subject string that matched  the  subpattern  is
     passed  back  to  the  caller  via  the  ovector
     argument of
     pcre_exec(). Opening parentheses are counted
     from  left  to right (starting from 1) to obtain the numbers of the
     capturing subpatterns.

     For example, if the string "the red king" is matched against
     the pattern

       the ((red|white) (king|queen))

     the captured substrings are "red king", "red",  and  "king",
     and are numbered 1, 2, and 3.

     The fact that plain parentheses fulfil two functions is  not
     always  helpful.  There are often times when a grouping subpattern
     is required without a capturing requirement.  If  an
     opening parenthesis is followed by "?:", the subpattern does
     not do any capturing, and is not counted when computing  the
     number of any subsequent capturing subpatterns. For example,
     if the string "the  white  queen"  is  matched  against  the
     pattern

       the ((?:red|white) (king|queen))

     the captured substrings are "white queen" and  "queen",  and
     are  numbered  1  and 2. The maximum number of captured substrings
     is 99, and the maximum number  of  all  subpatterns,
     both capturing and non-capturing, is 200.

     As a  convenient  shorthand,  if  any  option  settings  are
     required  at  the  start  of a non-capturing subpattern, the
     option letters may appear between the "?" and the ":".  Thus
     the two patterns

       (?i:saturday|sunday)
       (?:(?i)saturday|sunday)

     match exactly the same set of strings.  Because  alternative
     branches  are  tried from left to right, and options are not
     reset until the end of the subpattern is reached, an  option
     setting  in  one  branch does affect subsequent branches, so
     the above patterns match "SUNDAY" as well as "Saturday".
     

Repetition


     Repetition is specified by quantifiers, which can follow any
     of the following items:

       a single character, possibly escaped
       the . metacharacter
       a character class
       a back reference (see next section)
       a parenthesized subpattern (unless it is  an  assertion  -
     see below)

     The general repetition quantifier specifies  a  minimum  and
     maximum  number  of  permitted  matches,  by  giving the two
     numbers in curly brackets (braces), separated  by  a  comma.
     The  numbers  must be less than 65536, and the first must be
     less than or equal to the second. For example:

       z{2,4}

     matches "zz", "zzz", or "zzzz". A closing brace on  its  own
     is not a special character. If the second number is omitted,
     but the comma is present, there is no upper  limit;  if  the
     second number and the comma are both omitted, the quantifier
     specifies an exact number of required matches. Thus

       [aeiou]{3,}

     matches at least 3 successive vowels,  but  may  match  many
     more, while

       \d{8}

     matches exactly 8 digits.  An  opening  curly  bracket  that
     appears  in a position where a quantifier is not allowed, or
     one that does not match the syntax of a quantifier, is taken
     as  a literal character. For example, {,6} is not a quantifier,
     but a literal string of four characters.

     The quantifier {0} is permitted, causing the  expression  to
     behave  as  if the previous item and the quantifier were not
     present.

     For convenience (and  historical  compatibility)  the  three
     most common quantifiers have single-character abbreviations:

       *    is equivalent to {0,}
       +    is equivalent to {1,}
       ?    is equivalent to {0,1}

     It is possible to construct infinite loops  by  following  a
     subpattern  that  can  match no characters with a quantifier
     that has no upper limit, for example:

       (a?)*

     Earlier versions of Perl and PCRE used to give an  error  at
     compile  time  for such patterns. However, because there are
     cases where this  can  be  useful,  such  patterns  are  now
     accepted,  but  if  any repetition of the subpattern does in
     fact match no characters, the loop is forcibly broken.

     By default, the quantifiers  are  "greedy",  that  is,  they
     match  as much as possible (up to the maximum number of permitted
     times), without causing the rest of  the  pattern  to
     fail. The classic example of where this gives problems is in
     trying to match comments in C programs. These appear between
     the  sequences /* and */ and within the sequence, individual
     * and / characters may appear. An attempt to  match  C  comments
     by applying the pattern

       /\*.*\*/

     to the string

       /* first command */  not comment  /* second comment */

     fails, because it matches  the  entire  string  due  to  the
     greediness of the .*  item.

     However, if a quantifier is followed  by  a  question  mark,
     then it ceases to be greedy, and instead matches the minimum
     number of times possible, so the pattern

       /\*.*?\*/

     does the right thing with the C comments. The meaning of the
     various  quantifiers is not otherwise changed, just the preferred
     number of matches.  Do not confuse this use of  ques-
     tion  mark  with  its  use as a quantifier in its own right.
     Because it has two uses, it can sometimes appear doubled, as
     in

       \d??\d

     which matches one digit by preference, but can match two  if
     that is the only way the rest of the pattern matches.

     If the PCRE_UNGREEDY  option is set (an option which  is  not
     available  in  Perl)  then the quantifiers are not greedy by
     default, but individual ones can be made greedy by following
     them  with  a  question mark. In other words, it inverts the
     default behaviour.

     When a parenthesized subpattern is quantified with a minimum
     repeat  count  that is greater than 1 or with a limited maximum,
     more store is required for the  compiled  pattern,  in
     proportion to the size of the minimum or maximum.

     If a pattern starts with .* or  .{0,}  and  the  PCRE_DOTALL 
     option (equivalent to Perl's /s) is set, thus allowing the .
     to match newlines, then the pattern is implicitly  anchored,
     because whatever follows will be tried against every character
     position in the subject string, so there is no point  in
     retrying  the overall match at any position after the first.
     PCRE treats such a pattern as though it were preceded by \A.
     In  cases where it is known that the subject string contains
     no newlines, it is worth setting PCRE_DOTALL  when  the  pattern begins with .* in order to
     obtain this optimization, or
     alternatively using ^ to indicate anchoring explicitly.

     When a capturing subpattern is repeated, the value  captured
     is the substring that matched the final iteration. For example, after

       (tweedle[dume]{3}\s*)+

     has matched "tweedledum tweedledee" the value  of  the  captured
     substring  is  "tweedledee".  However,  if  there are
     nested capturing  subpatterns,  the  corresponding  captured
     values  may  have been set in previous iterations. For example,
     after
     
       /(a|(b))+/

     matches "aba" the value of the second captured substring  is
     "b".
     

BACK REFERENCES


     Outside a character class, a backslash followed by  a  digit
     greater  than  0  (and  possibly  further  digits) is a back
     reference to a capturing subpattern  earlier  (i.e.  to  its
     left)  in  the  pattern,  provided there have been that many
     previous capturing left parentheses.

     However, if the decimal number following  the  backslash  is
     less  than  10,  it is always taken as a back reference, and
     causes an error only if there are not  that  many  capturing
     left  parentheses in the entire pattern. In other words, the
     parentheses that are referenced need not be to the  left  of
     the  reference  for  numbers  less  than 10. See the section
     entitled "Backslash" above for further details of  the  handling
     of digits following a backslash.

     A back reference matches whatever actually matched the  capturing
     subpattern in the current subject string, rather than
     anything matching the subpattern itself. So the pattern

       (sens|respons)e and \1ibility

     matches "sense and sensibility" and "response and  responsibility",
     but  not  "sense  and  responsibility". If caseful
     matching is in force at the time of the back reference, then
     the case of letters is relevant. For example,

       ((?i)rah)\s+\1

     matches "rah rah" and "RAH RAH", but  not  "RAH  rah",  even
     though  the  original  capturing subpattern is matched caselessly.

     There may be more than one back reference to the  same  subpattern.
     If  a  subpattern  has not actually been used in a
     particular match, then any  back  references  to  it  always
     fail. For example, the pattern

       (a|(bc))\2

     always fails if it starts to match  "a"  rather  than  "bc".
     Because  there  may  be up to 99 back references, all digits
     following the backslash are taken as  part  of  a  potential
     back reference number. If the pattern continues with a digit
     character, then some delimiter must be used to terminate the
     back reference. If the PCRE_EXTENDED  option is set, this can
     be whitespace.  Otherwise an empty comment can be used.

     A back reference that occurs inside the parentheses to which
     it  refers  fails when the subpattern is first used, so, for
     example, (a\1) never matches.  However, such references  can
     be useful inside repeated subpatterns. For example, the pattern

       (a|b\1)+

     matches any number of "a"s and also "aba", "ababaa" etc.  At
     each iteration of the subpattern, the back reference matches
     the character string corresponding to  the  previous  iteration.
     In order for this to work, the pattern must be such
     that the first iteration does not need  to  match  the  back
     reference.  This  can  be  done using alternation, as in the
     example above, or by a quantifier with a minimum of zero.
     

Assertions


     An assertion is  a  test  on  the  characters  following  or
     preceding  the current matching point that does not actually
     consume any characters. The simple assertions coded  as  \b,
     \B,  \A,  \Z,  \z, ^ and $ are described above. More complicated
     assertions are coded as  subpatterns.  There  are  two
     kinds:  those that look ahead of the current position in the
     subject string, and those that look behind it.

     An assertion subpattern is matched in the normal way, except
     that  it  does not cause the current matching position to be
     changed. Lookahead assertions start with  (?=  for  positive
     assertions and (?! for negative assertions. For example,

       \w+(?=;)

     matches a word followed by a semicolon, but does not include
     the semicolon in the match, and

       foo(?!bar)

     matches any occurrence of "foo"  that  is  not  followed  by
     "bar". Note that the apparently similar pattern

       (?!foo)bar

     does not find an occurrence of "bar"  that  is  preceded  by
     something other than "foo"; it finds any occurrence of "bar"
     whatsoever, because the assertion  (?!foo)  is  always  TRUE
     when  the  next  three  characters  are  "bar". A lookbehind
     assertion is needed to achieve this effect.
     
     Lookbehind assertions start with (?<=  for  positive  assertions
     and (?<! for negative assertions. For example,

       (?<!foo)bar

     does find an occurrence of "bar" that  is  not  preceded  by
     "foo". The contents of a lookbehind assertion are restricted
     such that all the strings  it  matches  must  have  a  fixed
     length.  However, if there are several alternatives, they do
     not all have to have the same fixed length. Thus

       (?<=bullock|donkey)

     is permitted, but

       (?<!dogs?|cats?)

     causes an error at compile time. Branches  that  match  different
     length strings are permitted only at the top level of
     a lookbehind assertion. This is an extension  compared  with
     Perl  5.005,  which  requires all branches to match the same
     length of string. An assertion such as

       (?<=ab(c|de))

     is not permitted, because its single  top-level  branch  can
     match two different lengths, but it is acceptable if rewritten
     to use two top-level branches:

       (?<=abc|abde)

     The implementation of lookbehind  assertions  is,  for  each
     alternative,  to  temporarily move the current position back
     by the fixed width and then  try  to  match.  If  there  are
     insufficient  characters  before  the  current position, the
     match is deemed to fail.  Lookbehinds  in  conjunction  with
     once-only  subpatterns can be particularly useful for matching
     at the ends of strings; an example is given at  the  end
     of the section on once-only subpatterns.

     Several assertions (of any sort) may  occur  in  succession.
     For example,

       (?<=\d{3})(?<!999)foo

     matches "foo" preceded by three digits that are  not  "999".
     Notice  that each of the assertions is applied independently
     at the same point in the subject string. First  there  is  a
     check  that  the  previous  three characters are all digits,
     then there is a check that the same three characters are not
     "999".   This  pattern  does not match "foo" preceded by six
     characters, the first of which are digits and the last three
     of  which  are  not  "999".  For  example,  it doesn't match
     "123abcfoo". A pattern to do that is

       (?<=\d{3}...)(?<!999)foo

     This time the first assertion looks  at  the  preceding  six
     characters,  checking  that  the first three are digits, and
     then the second assertion checks that  the  preceding  three
     characters are not "999".

     Assertions can be nested in any combination. For example,

       (?<=(?<!foo)bar)baz

     matches an occurrence of "baz" that  is  preceded  by  "bar"
     which in turn is not preceded by "foo", while

       (?<=\d{3}(?!999)...)foo

     is another pattern which matches  "foo"  preceded  by  three
     digits and any three characters that are not "999".

     Assertion subpatterns are not capturing subpatterns, and may
     not  be  repeated,  because  it makes no sense to assert the
     same thing several times. If any kind of assertion  contains
     capturing  subpatterns  within it, these are counted for the
     purposes of numbering the capturing subpatterns in the whole
     pattern.   However,  substring capturing is carried out only
     for positive assertions, because it does not make sense  for
     negative assertions.

     Assertions count towards the maximum  of  200  parenthesized
     subpatterns.
     

Once-only subpatterns


     With both maximizing and minimizing repetition,  failure  of
     what  follows  normally  causes  the repeated item to be re-
     evaluated to see if a different number of repeats allows the
     rest  of  the  pattern  to  match. Sometimes it is useful to
     prevent this, either to change the nature of the  match,  or
     to  cause  it fail earlier than it otherwise might, when the
     author of the pattern knows there is no  point  in  carrying
     on.

     Consider, for example, the pattern \d+foo  when  applied  to
     the subject line

       123456bar

     After matching all 6 digits and then failing to match "foo",
     the normal action of the matcher is to try again with only 5
     digits matching the \d+ item, and then with 4,  and  so  on,
     before ultimately failing. Once-only subpatterns provide the
     means for specifying that once a portion of the pattern  has
     matched,  it  is  not to be re-evaluated in this way, so the
     matcher would give up immediately on failing to match  "foo"
     the  first  time.  The  notation  is another kind of special
     parenthesis, starting with (?> as in this example:

       (?>\d+)bar

     This kind of parenthesis "locks up" the  part of the pattern
     it  contains once it has matched, and a failure further into
     the pattern is prevented from backtracking  into  it.  Back-
     tracking  past  it to previous items, however, works as normal.

     An alternative description is that a subpattern of this type
     matches  the  string  of  characters that an identical standalone
     pattern would match, if anchored at the current point
     in the subject string.

     Once-only subpatterns are not capturing subpatterns.  Simple
     cases  such as the above example can be thought of as a maximizing
     repeat that must  swallow  everything  it  can.  So,
     while both \d+ and \d+? are prepared to adjust the number of
     digits they match in order to make the rest of  the  pattern
     match, (?>\d+) can only match an entire sequence of digits.

     This construction can of course contain arbitrarily  complicated
     subpatterns, and it can be nested.

     Once-only subpatterns can be used in conjunction with  look-
     behind  assertions  to specify efficient matching at the end
     of the subject string. Consider a simple pattern such as

       abcd$

     when applied to a long string which does not match.  Because
     matching  proceeds  from  left  to right, PCRE will look for
     each "a" in the subject and then see if what follows matches
     the rest of the pattern. If the pattern is specified as

       ^.*abcd$

     then the initial .* matches the entire string at first,  but
     when  this  fails  (because  there  is no following "a"), it
     backtracks to match all but the last character, then all but
     the  last  two  characters, and so on. Once again the search
     for "a" covers the entire string, from right to left, so  we
     are no better off. However, if the pattern is written as

       ^(?>.*)(?<=abcd)

     then there can be no backtracking for the .*  item;  it  can
     match  only  the  entire  string.  The subsequent lookbehind
     assertion does a single test on the last four characters. If
     it  fails,  the  match  fails immediately. For long strings,
     this approach makes a significant difference to the processing time.

     When a pattern contains an unlimited repeat inside a subpattern
     that can itself be repeated an unlimited number of
     times, the use of a once-only subpattern is the only way  to
     avoid  some  failing matches taking a very long time indeed.
     The pattern

       (\D+|<\d+>)*[!?]

     matches an unlimited number of substrings that  either  consist
     of  non-digits,  or digits enclosed in <>, followed by
     either ! or ?. When it matches, it runs quickly. However, if
     it is applied to

       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

     it takes a long  time  before  reporting  failure.  This  is
     because the string can be divided between the two repeats in
     a large number of ways, and all have to be tried. (The example
     used  [!?]  rather  than a single character at the end,
     because both PCRE and Perl have an optimization that  allows
     for  fast  failure  when  a  single  character is used. They
     remember the last single character that is  required  for  a
     match,  and  fail early if it is not present in the string.)
     If the pattern is changed to

       ((?>\D+)|<\d+>)*[!?]

     sequences of non-digits cannot be broken, and  failure  happens quickly.
     

Conditional subpatterns


     It is possible to cause the matching process to obey a  subpattern 
     conditionally  or to choose between two alternative
     subpatterns, depending on the result  of  an  assertion,  or
     whether  a previous capturing subpattern matched or not. The
     two possible forms of conditional subpattern are

       (?(condition)yes-pattern)
       (?(condition)yes-pattern|no-pattern)

     If the condition is satisfied, the yes-pattern is used; otherwise
     the  no-pattern  (if  present) is used. If there are
     more than two alternatives in the subpattern, a compile-time
     error occurs.

     There are two kinds of condition. If the  text  between  the
     parentheses  consists  of  a  sequence  of  digits, then the
     condition is satisfied if the capturing subpattern  of  that
     number  has  previously matched. Consider the following pattern,
     which contains non-significant white space to make  it
     more  readable  (assume  the  PCRE_EXTENDED   option)  and to
     divide it into three parts for ease of discussion:

       ( \( )?    [^()]+    (?(1) \) )

     The first part matches an optional opening parenthesis,  and
     if  that character is present, sets it as the first captured
     substring. The second part matches one  or  more  characters
     that  are  not  parentheses. The third part is a conditional
     subpattern that tests whether the first set  of  parentheses
     matched  or  not.  If  they did, that is, if subject started
     with an opening parenthesis, the condition is TRUE,  and  so
     the  yes-pattern  is  executed  and a closing parenthesis is
     required. Otherwise, since no-pattern is  not  present,  the
     subpattern  matches  nothing.  In  other words, this pattern
     matches a sequence of non-parentheses,  optionally  enclosed
     in parentheses.

     If the condition is not a sequence of digits, it must be  an
     assertion.  This  may be a positive or negative lookahead or
     lookbehind assertion. Consider this pattern, again  containing
     non-significant  white space, and with the two alternatives on
     the second line:

       (?(?=[^a-z]*[a-z])
       \d{2}-[a-z]{3}-\d{2}  |  \d{2}-\d{2}-\d{2} )

     The condition is a positive lookahead assertion that matches
     an optional sequence of non-letters followed by a letter. In
     other words, it tests for  the  presence  of  at  least  one
     letter  in the subject. If a letter is found, the subject is
     matched against  the  first  alternative;  otherwise  it  is
     matched  against the second. This pattern matches strings in
     one of the two forms dd-aaa-dd or dd-dd-dd,  where  aaa  are
     letters and dd are digits.
     

Comments


     The  sequence  (?#  marks  the  start  of  a  comment  which
     continues   up  to  the  next  closing  parenthesis.  Nested
     parentheses are not permitted. The characters that make up a
     comment play no part in the pattern matching at all.

     If the PCRE_EXTENDED  option is set, an unescaped # character
     outside  a character class introduces a comment that contin-
     ues up to the next newline character in the pattern.
     

Recursive patterns


     Consider the problem of matching a  string  in  parentheses,
     allowing  for  unlimited nested parentheses. Without the use
     of recursion, the best that can be done is to use a  pattern
     that  matches  up  to some fixed depth of nesting. It is not
     possible to handle an arbitrary nesting depth. Perl 5.6  has
     provided   an  experimental  facility  that  allows  regular
     expressions to recurse (amongst other things).  The  special 
     item (?R) is  provided for  the specific  case of recursion. 
     This PCRE  pattern  solves the  parentheses  problem (assume 
     the PCRE_EXTENDED
     option is set so that white space is 
     ignored):

       \( ( (?>[^()]+) | (?R) )* \)

     First it matches an opening parenthesis. Then it matches any
     number  of substrings which can either be a sequence of non-
     parentheses, or a recursive  match  of  the  pattern  itself
     (i.e. a correctly parenthesized substring). Finally there is
     a closing parenthesis.

     This particular example pattern  contains  nested  unlimited
     repeats, and so the use of a once-only subpattern for matching
     strings of non-parentheses is  important  when  applying
     the  pattern to strings that do not match. For example, when
     it is applied to

       (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()

     it yields "no match" quickly. However, if a  once-only  subpattern
     is  not  used,  the match runs for a very long time
     indeed because there are so many different ways the + and  *
     repeats  can carve up the subject, and all have to be tested
     before failure can be reported.

     The values set for any capturing subpatterns are those  from
     the outermost level of the recursion at which the subpattern
     value is set. If the pattern above is matched against

       (ab(cd)ef)

     the value for the capturing parentheses is  "ef",  which  is
     the  last  value  taken  on  at the top level. If additional
     parentheses are added, giving

       \( ( ( (?>[^()]+) | (?R) )* ) \)
          ^                        ^
          ^                        ^ then the string they capture
     is "ab(cd)ef", the contents of the top level parentheses. If
     there are more than 15 capturing parentheses in  a  pattern,
     PCRE  has  to  obtain  extra  memory  to store data during a
     recursion, which it does by using  pcre_malloc,  freeing  it
     via  pcre_free  afterwards. If no memory can be obtained, it
     saves data for the first 15 capturing parentheses  only,  as
     there is no way to give an out-of-memory error from within a
     recursion.
     

Performances


     Certain items that may appear in patterns are more efficient
     than  others.  It is more efficient to use a character class
     like [aeiou] than a set of alternatives such as (a|e|i|o|u).
     In  general,  the  simplest  construction  that provides the
     required behaviour is usually the  most  efficient.  Jeffrey
     Friedl's  book contains a lot of discussion about optimizing
     regular expressions for efficient performance.

     When a pattern begins with .* and the PCRE_DOTALL  option  is
     set,  the  pattern  is implicitly anchored by PCRE, since it
     can match only at the start of a subject string. However, if
     PCRE_DOTALL   is not set, PCRE cannot make this optimization,
     because the . metacharacter does not then match  a  newline,
     and if the subject string contains newlines, the pattern may
     match from the character immediately following one  of  them
     instead of from the very start. For example, the pattern

       (.*) second

     matches the subject "first\nand second" (where \n stands for
     a newline character) with the first captured substring being
     "and". In order to do this, PCRE  has  to  retry  the  match
     starting after every newline in the subject.

     If you are using such a pattern with subject strings that do
     not  contain  newlines,  the best performance is obtained by
     setting PCRE_DOTALL , or starting the  pattern  with  ^.*  to
     indicate  explicit anchoring. That saves PCRE from having to
     scan along the subject looking for a newline to restart at.

     Beware of patterns that contain nested  indefinite  repeats.
     These  can  take a long time to run when applied to a string
     that does not match. Consider the pattern fragment

       (a+)*

     This can match "aaaa" in 33 different ways, and this  number
     increases  very  rapidly  as  the string gets longer. (The *
     repeat can match 0, 1, 2, 3, or 4 times,  and  for  each  of
     those  cases other than 0, the + repeats can match different
     numbers of times.) When the remainder of the pattern is such
     that  the entire match is going to fail, PCRE has in principle
     to try every possible variation, and this  can  take  an
     extremely long time.

     An optimization catches some of the more simple  cases  such
     as

       (a+)*b

     where a literal character follows. Before embarking  on  the
     standard matching procedure, PCRE checks that there is a "b"
     later in the subject string, and if there is not,  it  fails
     the  match  immediately. However, when there is no following
     literal this optimization cannot be used. You  can  see  the
     difference by comparing the behaviour of

       (a+)*\d

     with the pattern above. The former gives  a  failure  almost
     instantly  when  applied  to a whole line of "a" characters,
     whereas the latter takes an appreciable  time  with  strings
     longer than about 20 characters.
     

preg_grep

(PHP 4 )

preg_grep --  Return array entries that match the pattern

Description

array preg_grep ( string pattern, array input)

preg_grep() returns the array consisting of the elements of the input array that match the given pattern.

Since PHP 4.0.4, the results returned by preg_grep() are indexed using the keys from the input array. If this behavior is undesirable, use array_values() on the array returned by preg_grep() to reindex the values.

Exemplo 1. preg_grep() example

// return all array elements
// containing floating point numbers
$fl_array = preg_grep ("/^(\d+)?\.\d+$/", $array);

preg_match_all

(PHP 3>= 3.0.9, PHP 4 )

preg_match_all -- Perform a global regular expression match

Description

int preg_match_all ( string pattern, string subject, array matches [, int flags])

Searches subject for all matches to the regular expression given in pattern and puts them in matches in the order specified by flags.

After the first match is found, the subsequent searches are continued on from end of the last match.

flags can be a combination of the following flags (note that it doesn't make sense to use PREG_PATTERN_ORDER together with PREG_SET_ORDER):

PREG_PATTERN_ORDER

Orders results so that $matches[0] is an array of full pattern matches, $matches[1] is an array of strings matched by the first parenthesized subpattern, and so on.

<?php
preg_match_all ("|<[^>]+>(.*)</[^>]+>|U", 
    "<b>example: </b><div align=left>this is a test</div>", 
    $out, PREG_PATTERN_ORDER);
print $out[0][0].", ".$out[0][1]."\n";
print $out[1][0].", ".$out[1][1]."\n";
?>

This example will produce:
<b>example: </b>, <div align=left>this is a test</div>
example: , this is a test
So, $out[0] contains array of strings that matched full pattern, and $out[1] contains array of strings enclosed by tags.

PREG_SET_ORDER

Orders results so that $matches[0] is an array of first set of matches, $matches[1] is an array of second set of matches, and so on.

<?php
preg_match_all ("|<[^>]+>(.*)</[^>]+>|U", 
    "<b>example: </b><div align=left>this is a test</div>", 
    $out, PREG_SET_ORDER);
print $out[0][0].", ".$out[0][1]."\n";
print $out[1][0].", ".$out[1][1]."\n";
?>

This example will produce:

<b>example: </b>, example: 
<div align=left>this is a test</div>, this is a test

In this case, $matches[0] is the first set of matches, and $matches[0][0] has text matched by full pattern, $matches[0][1] has text matched by first subpattern and so on. Similarly, $matches[1] is the second set of matches, etc.

PREG_OFFSET_CAPTURE

If this flag is set, for every occuring match the appendant string offset will also be returned. Note that this changes the return value in an array where every element is an array consisting of the matched string at offset 0 and it's string offset into subject at offset 1. This flag is available since PHP 4.3.0 .

If no order flag is given, PREG_PATTERN_ORDER is assumed.

Returns the number of full pattern matches (which might be zero), or FALSE if an error occurred.

Exemplo 1. Getting all phone numbers out of some text.

<?php
preg_match_all ("/\(?  (\d{3})?  \)?  (?(1)  [\-\s] ) \d{3}-\d{4}/x",
                "Call 555-1212 or 1-800-555-1212", $phones);
?>

Exemplo 2. Find matching HTML tags (greedy)

<?php
// The \\2 is an example of backreferencing. This tells pcre that
// it must match the second set of parentheses in the regular expression
// itself, which would be the ([\w]+) in this case. The extra backslash is 
// required because the string is in double quotes.
$html = "<b>bold text</b><a href=howdy.html>click me</a>";

preg_match_all ("/(<([\w]+)[^>]*>)(.*)(<\/\\2>)/", $html, $matches);

for ($i=0; $i< count($matches[0]); $i++) {
  echo "matched: ".$matches[0][$i]."\n";
  echo "part 1: ".$matches[1][$i]."\n";
  echo "part 2: ".$matches[3][$i]."\n";
  echo "part 3: ".$matches[4][$i]."\n\n";
}
?>
This example will produce:
matched: <b>bold text</b>
part 1: <b>
part 2: bold text
part 3: </b>

matched: <a href=howdy.html>click me</a>
part 1: <a href=howdy.html>
part 2: click me
part 3: </a>

See also preg_match(), preg_replace(), and preg_split().

preg_match

(PHP 3>= 3.0.9, PHP 4 )

preg_match -- Perform a regular expression match

Description

int preg_match ( string pattern, string subject [, array matches [, int flags]])

Searches subject for a match to the regular expression given in pattern.

If matches is provided, then it is filled with the results of search. $matches[0] will contain the text that matched the full pattern, $matches[1] will have the text that matched the first captured parenthesized subpattern, and so on.

flags can be the following flag:

PREG_OFFSET_CAPTURE

If this flag is set, for every occuring match the appendant string offset will also be returned. Note that this changes the return value in an array where every element is an array consisting of the matched string at offset 0 and it's string offset into subject at offset 1. This flag is available since PHP 4.3.0 .

The flags parameter is available since PHP 4.3.0 .

preg_match() returns the number of times pattern matches. That will be either 0 times (no match) or 1 time because preg_match() will stop searching after the first match. preg_match_all() on the contrary will continue until it reaches the end of subject. preg_match() returns FALSE if an error occured.

Exemplo 1. Find the string of text "php"

// the "i" after the pattern delimiter indicates a case-insensitive search
if (preg_match ("/php/i", "PHP is the web scripting language of choice.")) {
    print "A match was found.";
} else {
    print "A match was not found.";
}

Exemplo 2. find the word "web"

// the \b in the pattern indicates a word boundary, so only the distinct
// word "web" is matched, and not a word partial like "webbing" or "cobweb"
if (preg_match ("/\bweb\b/i", "PHP is the web scripting language of choice.")) {
    print "A match was found.";
} else {
    print "A match was not found.";
}
if (preg_match ("/\bweb\b/i", "PHP is the website scripting language of choice.")) {
    print "A match was found.";
} else {
    print "A match was not found.";
}

Exemplo 3. Getting the domain name out of a URL

// get host name from URL
preg_match("/^(http:\/\/)?([^\/]+)/i",
"http://www.php.net/index.html", $matches);
$host = $matches[2];
// get last two segments of host name
preg_match("/[^\.\/]+\.[^\.\/]+$/",$host,$matches);
echo "domain name is: ".$matches[0]."\n";

This example will produce:
domain name is: php.net

See also preg_match_all(), preg_replace(), and preg_split().

preg_quote

(PHP 3>= 3.0.9, PHP 4 )

preg_quote -- Quote regular expression characters

Description

string preg_quote ( string str [, string delimiter])

preg_quote() takes str and puts a backslash in front of every character that is part of the regular expression syntax. This is useful if you have a run-time string that you need to match in some text and the string may contain special regex characters.

If the optional delimiter is specified, it will also be escaped. This is useful for escaping the delimiter that is required by the PCRE functions. The / is the most commonly used delimiter.

The special regular expression characters are:
. \\ + * ? [ ^ ] $ ( ) { } = ! < > | :

Exemplo 1.

$keywords = "$40 for a g3/400";
$keywords = preg_quote ($keywords, "/");
echo $keywords; // returns \$40 for a g3\/400

Exemplo 2. Italicizing a word within some text

// In this example, preg_quote($word) is used to keep the
// asterisks from having special meaning to the regular
// expression.

$textbody = "This book is *very* difficult to find.";
$word = "*very*";
$textbody = preg_replace ("/".preg_quote($word)."/",
                          "<i>".$word."</i>",
                          $textbody);

preg_replace_callback

(PHP 4 >= 4.0.5)

preg_replace_callback -- Perform a regular expression search and replace using a callback

Description

mixed preg_replace_callback ( mixed pattern, callback callback, mixed subject [, int limit])

The behavior of this function is almost identical to preg_replace(), except for the fact that instead of replacement parameter, one should specify a callback that will be called and passed an array of matched elements in the subject string. The callback should return the replacement string.

See also preg_replace().

preg_replace

(PHP 3>= 3.0.9, PHP 4 )

preg_replace -- Perform a regular expression search and replace

Description

mixed preg_replace ( mixed pattern, mixed replacement, mixed subject [, int limit])

Searches subject for matches to pattern and replaces them with replacement. If limit is specified, then only limit matches will be replaced; if limit is omitted or is -1, then all matches are replaced.

Replacement may contain references of the form \\n or (since PHP 4.0.4) $n, with the latter form being the preferred one. Every such reference will be replaced by the text captured by the n'th parenthesized pattern. n can be from 0 to 99, and \\0 or $0 refers to the text matched by the whole pattern. Opening parentheses are counted from left to right (starting from 1) to obtain the number of the capturing subpattern.

Nota: When working with a replacement pattern where a backreference is immediately followed by another number (i.e.: placing a literal number immediately after a matched pattern), you cannot use the familiar \\1 notation for your backreference. \\11, for example, would confuse preg_replace() since it does not know whether you want the \\1 backreference followed by a literal 1, or the \\11 backreference followed by nothing. In this case the solution is to use \${1}1. This creates an isolated $1 backreference, leaving the 1 as a literal.

Exemplo 1. Using backreferences followed by numeric literals.

<?php
$str = "April 15, 2003";
$pattern = "/(\w+) (\d+), (\d+)/i";
$replacement = "\${1}1,\$3";
print preg_replace($pattern, $replacement, $string);

/* Output
   ======

April1,2003

 */
?>

If matches are found, the new subject will be returned, otherwise subject will be returned unchanged.

Every parameter to preg_replace() (except limit) can be an array.

Nota: When using arrays with pattern and replacement, the keys are processed in the order they appear in the array. This is not necessarily the same as the numerical index order. If you use indexes to identify which pattern should be replaced by which replacement, you should perform a ksort() on each array prior to calling preg_replace().

Exemplo 2. Using indexed arrays with preg_replace()

<?php
$string = "The quick brown fox jumped over the lazy dog.";

$patterns[0] = "/quick/";
$patterns[1] = "/brown/";
$patterns[2] = "/fox/";

$replacements[2] = "bear";
$replacements[1] = "black";
$replacements[0] = "slow";

print preg_replace($patterns, $replacements, $string);

/* Output
   ======

The bear black slow jumped over the lazy dog.

*/

/* By ksorting patterns and replacements,
   we should get what we wanted. */

ksort($patterns);
ksort($replacements);

print preg_replace($patterns, $replacements, $string);

/* Output
   ======

The slow black bear jumped over the lazy dog.

*/

?>

If subject is an array, then the search and replace is performed on every entry of subject, and the return value is an array as well.

If pattern and replacement are arrays, then preg_replace() takes a value from each array and uses them to do search and replace on subject. If replacement has fewer values than pattern, then empty string is used for the rest of replacement values. If pattern is an array and replacement is a string, then this replacement string is used for every value of pattern. The converse would not make sense, though.

/e modifier makes preg_replace() treat the replacement parameter as PHP code after the appropriate references substitution is done. Tip: make sure that replacement constitutes a valid PHP code string, otherwise PHP will complain about a parse error at the line containing preg_replace().

Exemplo 3. Replacing several values

$patterns = array ("/(19|20)(\d{2})-(\d{1,2})-(\d{1,2})/",
                   "/^\s*{(\w+)}\s*=/");
$replace = array ("\\3/\\4/\\1\\2", "$\\1 =");
print preg_replace ($patterns, $replace, "{startDate} = 1999-5-27");
This example will produce:
$startDate = 5/27/1999

Exemplo 4. Using /e modifier

preg_replace ("/(<\/?)(\w+)([^>]*>)/e", 
              "'\\1'.strtoupper('\\2').'\\3'", 
              $html_body);

This would capitalize all HTML tags in the input text.

Exemplo 5. Convert HTML to text

// $document should contain an HTML document.
// This will remove HTML tags, javascript sections
// and white space. It will also convert some
// common HTML entities to their text equivalent.

$search = array ("'<script[^>]*?>.*?</script>'si",  // Strip out javascript
                 "'<[\/\!]*?[^<>]*?>'si",           // Strip out html tags
                 "'([\r\n])[\s]+'",                 // Strip out white space
                 "'&(quot|#34);'i",                 // Replace html entities
                 "'&(amp|#38);'i",
                 "'&(lt|#60);'i",
                 "'&(gt|#62);'i",
                 "'&(nbsp|#160);'i",
                 "'&(iexcl|#161);'i",
                 "'&(cent|#162);'i",
                 "'&(pound|#163);'i",
                 "'&(copy|#169);'i",
                 "'&#(\d+);'e");                    // evaluate as php

$replace = array ("",
                  "",
                  "\\1",
                  "\"",
                  "&",
                  "<",
                  ">",
                  " ",
                  chr(161),
                  chr(162),
                  chr(163),
                  chr(169),
                  "chr(\\1)");

$text = preg_replace ($search, $replace, $document);

Nota: Parameter limit was added after PHP 4.0.1pl2.

See also preg_match(), preg_match_all(), and preg_split().

preg_split

(PHP 3>= 3.0.9, PHP 4 )

preg_split -- Split string by a regular expression

Description

array preg_split ( string pattern, string subject [, int limit [, int flags]])

Nota: Parameter flags was added in PHP 4 Beta 3.

Returns an array containing substrings of subject split along boundaries matched by pattern.

If limit is specified, then only substrings up to limit are returned, and if limit is -1, it actually means "no limit", which is useful for specifying the flags.

flags can be any combination of the following flags (combined with bitwise | operator):

PREG_SPLIT_NO_EMPTY

If this flag is set, only non-empty pieces will be returned by preg_split().

PREG_SPLIT_DELIM_CAPTURE

If this flag is set, parenthesized expression in the delimiter pattern will be captured and returned as well. This flag was added for 4.0.5.

PREG_SPLIT_OFFSET_CAPTURE

If this flag is set, for every occuring match the appendant string offset will also be returned. Note that this changes the return value in an array where every element is an array consisting of the matched string at offset 0 and it's string offset into subject at offset 1. This flag is available since PHP 4.3.0 .

Exemplo 1. preg_split() example : Get the parts of a search string.

// split the phrase by any number of commas or space characters,
// which include " ", \r, \t, \n and \f
$keywords = preg_split ("/[\s,]+/", "hypertext language, programming");

Exemplo 2. Splitting a string into component characters.

$str = 'string';
$chars = preg_split('//', $str, -1, PREG_SPLIT_NO_EMPTY);
print_r($chars);

Exemplo 3. Splitting a string into matches and their offsets.

$str = 'hypertext language programming';
$chars = preg_split('/ /', $str, -1, PREG_SPLIT_OFFSET_CAPTURE);
print_r($chars);

will yield

Array
(
    [0] => Array
        (
            [0] => hypertext
            [1] => 0
        )

    [1] => Array
        (
            [0] => language
            [1] => 10
        )

    [2] => Array
        (
            [0] => programming
            [1] => 19
        )

)

See also spliti(), split(), implode(), preg_match(), preg_match_all(), and preg_replace().

LXXXIX. qtdom functions

Atenção

Este módulo é EXPERIMENTAL. Isso quer dizer que o comportamento neste módulo --- incluindo suas funções e seus nomes, e TUDO mais que está documentado sobre esse módulo --- poderá mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use este módulo por sua própria conta e risco.

Nota: This extension is not available on Windows platforms.


Requisitos

You need the Qt-library >=2.2.0


Instalação

Configure PHP --with-qtdom to use these functions.

Índice
qdom_error -- Returns the error string from the last QDOM operation or FALSE if no errors occured
qdom_tree -- creates a tree of an xml string

qdom_error

(PHP 4 >= 4.0.5)

qdom_error -- Returns the error string from the last QDOM operation or FALSE if no errors occured

Description

string qdom_error ( void)

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

qdom_tree

(PHP 4 >= 4.0.4)

qdom_tree -- creates a tree of an xml string

Description

object qdom_tree ( string )

Atenção

Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco.

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

XC. Regular Expression Functions (POSIX Extended)

Introdução

Nota: PHP also supports regular expressions using a Perl-compatible syntax using the PCRE functions. Those functions support non-greedy matching, assertions, conditional subpatterns, and a number of other features not supported by the POSIX-extended regular expression syntax.

Atenção

These regular expression functions are not binary-safe. The PCRE functions are.

Regular expressions are used for complex string manipulation in PHP. The functions that support regular expressions are:

These functions all take a regular expression string as their first argument. PHP uses the POSIX extended regular expressions as defined by POSIX 1003.2. For a full description of POSIX regular expressions see the regex man pages included in the regex directory in the PHP distribution. It's in manpage format, so you'll want to do something along the lines of man /usr/local/src/regex/regex.7 in order to read it.


Requisitos

Nenhuma biblioteca externa é necessária para compilar esta extensão.


Instalação

To enable regexp support configure PHP --with-regex[=TYPE]. TYPE can be one of system, apache, php. The default is to use php.

Nota: Do not change the TYPE unless you know what you are doing.

The windows version of PHP has built in support for this extension. You do not need to load any additional extension in order to use these functions.


Configuração durante execução

Esta extenção não define nenhum parâmetro de configuração no php.ini.


Tipos Resource

Esta extensão não possui nenhum tipo resource.


Constantes Predefinidas

Esta extensão não possui nenhuma constante.


Exemplos

Exemplo 1. Regular Expression Examples

ereg ("abc", $string);            
/* Returns true if"abc"
   is found anywhere in $string. */

ereg ("^abc", $string);
/* Returns true if "abc";
   is found at the beginning of $string. */

ereg ("abc$", $string);
/* Returns true if "abc"
   is found at the end of $string. */

eregi ("(ozilla.[23]|MSIE.3)", $HTTP_USER_AGENT);  
/* Returns true if client browser
   is Netscape 2, 3 or MSIE 3. */

ereg ("([[:alnum:]]+) ([[:alnum:]]+) ([[:alnum:]]+)", $string,$regs); 
/* Places three space separated words
   into $regs[1], $regs[2] and $regs[3]. */

$string = ereg_replace ("^", "<br />", $string); 
/* Put a <br /> tag at the beginning of $string. */
 
$string = ereg_replace ("$", "<br />", $string); 
/* Put a <br />; tag at the end of $string. */

$string = ereg_replace ("\n", "", $string);
/* Get rid of any newline
   characters in $string. */


Veja Também

For regular expressions in Perl-compatible syntax have a look at the PCRE functions. The simpler shell style wildcard pattern matching is provided by fnmatch().

Índice
ereg_replace -- Replace regular expression
ereg -- Regular expression match
eregi_replace -- replace regular expression case insensitive
eregi -- case insensitive regular expression match
split -- split string into array by regular expression
spliti --  Split string into array by regular expression case insensitive
sql_regcase --  Make regular expression for case insensitive match

ereg_replace

(PHP 3, PHP 4 )

ereg_replace -- Replace regular expression

Description

string ereg_replace ( string pattern, string replacement, string string)

Nota: preg_replace(), which uses a Perl-compatible regular expression syntax, is often a faster alternative to ereg_replace().

This function scans string for matches to pattern, then replaces the matched text with replacement.

The modified string is returned. (Which may mean that the original string is returned if there are no matches to be replaced.)

If pattern contains parenthesized substrings, replacement may contain substrings of the form \\digit, which will be replaced by the text matching the digit'th parenthesized substring; \\0 will produce the entire contents of string. Up to nine substrings may be used. Parentheses may be nested, in which case they are counted by the opening parenthesis.

If no matches are found in string, then string will be returned unchanged.

For example, the following code snippet prints "This was a test" three times:

Exemplo 1. ereg_replace() Example

$string = "This is a test";
echo ereg_replace (" is", " was", $string);
echo ereg_replace ("( )is", "\\1was", $string);
echo ereg_replace ("(( )is)", "\\2was", $string);

One thing to take note of is that if you use an integer value as the replacement parameter, you may not get the results you expect. This is because ereg_replace() will interpret the number as the ordinal value of a character, and apply that. For instance:

Exemplo 2. ereg_replace() Example

<?php
/* This will not work as expected. */
$num = 4;
$string = "This string has four words.";
$string = ereg_replace('four', $num, $string);
echo $string;   /* Output: 'This string has   words.' */

/* This will work. */
$num = '4';
$string = "This string has four words.";
$string = ereg_replace('four', $num, $string);
echo $string;   /* Output: 'This string has 4 words.' */
?>

Exemplo 3. Replace URLs with links

$text = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]",
                     "<a href=\"\\0\">\\0</a>", $text);

See also ereg(), eregi(), eregi_replace(), str_replace(), and preg_match().

ereg

(PHP 3, PHP 4 )

ereg -- Regular expression match

Description

int ereg ( string pattern, string string [, array regs])

Nota: preg_match(), which uses a Perl-compatible regular expression syntax, is often a faster alternative to ereg().

Searches a string for matches to the regular expression given in pattern.

If matches are found for parenthesized substrings of pattern and the function is called with the third argument regs, the matches will be stored in the elements of the array regs. $regs[1] will contain the substring which starts at the first left parenthesis; $regs[2] will contain the substring starting at the second, and so on. $regs[0] will contain a copy of the complete string matched.

Nota: Up to (and including) PHP 4.1.0 $regs will be filled with exactly ten elements, even though more or fewer than ten parenthesized substrings may actually have matched. This has no effect on ereg()'s ability to match more substrings. If no matches are found, $regs will not be altered by ereg().

Searching is case sensitive.

Returns TRUE if a match for pattern was found in string, or FALSE if no matches were found or an error occurred.

The following code snippet takes a date in ISO format (YYYY-MM-DD) and prints it in DD.MM.YYYY format:

Exemplo 1. ereg() Example

if (ereg ("([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})", $date, $regs)) {
    echo "$regs[3].$regs[2].$regs[1]";
} else {
    echo "Invalid date format: $date";
}

See also eregi(), ereg_replace(), eregi_replace(), and preg_match().

eregi_replace

(PHP 3, PHP 4 )

eregi_replace -- replace regular expression case insensitive

Description

string eregi_replace ( string pattern, string replacement, string string)

This function is identical to ereg_replace() except that this ignores case distinction when matching alphabetic characters.

See also ereg(), eregi(), and ereg_replace().

eregi

(PHP 3, PHP 4 )

eregi -- case insensitive regular expression match

Description

int eregi ( string pattern, string string [, array regs])

This function is identical to ereg() except that this ignores case distinction when matching alphabetic characters.

Exemplo 1. eregi() example

if (eregi("z", $string)) {
    echo "'$string' contains a 'z' or 'Z'!";
}

See also ereg(), ereg_replace(), and eregi_replace().

split

(PHP 3, PHP 4 )

split -- split string into array by regular expression

Description

array split ( string pattern, string string [, int limit])

Nota: preg_split(), which uses a Perl-compatible regular expression syntax, is often a faster alternative to split().

Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the regular expression pattern. If limit is set, the returned array will contain a maximum of limit elements with the last element containing the whole rest of string. If an error occurs, split() returns FALSE.

To split off the first four fields from a line from /etc/passwd:

Exemplo 1. split() Example

list($user,$pass,$uid,$gid,$extra)= split (":", $passwd_line, 5);

Nota: If there are n occurrences of pattern, the returned array will contain n+1 items. For example, if there is no occurrence of pattern, an array with only one element will be returned. Of course, this is also true if string is empty.

To parse a date which may be delimited with slashes, dots, or hyphens:

Exemplo 2. split() Example

$date = "04/30/1973";  // Delimiters may be slash, dot, or hyphen
list ($month, $day, $year) = split ('[/.-]', $date);
echo "Month: $month; Day: $day; Year: $year<br>\n";

Note that pattern is case-sensitive.

Note that if you don't require the power of regular expressions, it is faster to use explode(), which doesn't incur the overhead of the regular expression engine.

For users looking for a way to emulate Perl's @chars = split('', $str) behaviour, please see the examples for preg_split().

Please note that pattern is a regular expression. If you want to split on any of the characters which are considered special by regular expressions, you'll need to escape them first. If you think split() (or any other regex function, for that matter) is doing something weird, please read the file regex.7, included in the regex/ subdirectory of the PHP distribution. It's in manpage format, so you'll want to do something along the lines of man /usr/local/src/regex/regex.7 in order to read it.

See also: preg_split(), spliti(), explode(), implode(), chunk_split(), and wordwrap().

spliti

(PHP 4 >= 4.0.1)

spliti --  Split string into array by regular expression case insensitive

Description

array spliti ( string pattern, string string [, int limit])

This function is identical to split() except that this ignores case distinction when matching alphabetic characters.

See also preg_spliti(), split(), explode(), and implode().

sql_regcase

(PHP 3, PHP 4 )

sql_regcase --  Make regular expression for case insensitive match

Description

string sql_regcase ( string string)

Returns a valid regular expression which will match string, ignoring case. This expression is string with each character converted to a bracket expression; this bracket expression contains that character's uppercase and lowercase form if applicable, otherwise it contains the original character twice.

Exemplo 1. sql_regcase() Example

echo sql_regcase ("Foo bar");
prints
[Ff][Oo][Oo] [Bb][Aa][Rr]
.

This can be used to achieve case insensitive pattern matching in products which support only case sensitive regular expressions.

XCI. Semaphore, Shared Memory and IPC Functions

Introdução

This module provides wrappers for the System V IPC family of functions. It includes semaphores, shared memory and inter-process messaging (IPC).

Semaphores may be used to provide exclusive access to resources on the current machine, or to limit the number of processes that may simultaneously use a resource.

This module provides also shared memory functions using System V shared memory. Shared memory may be used to provide access to global variables. Different httpd-daemons and even other programs (such as Perl, C, ...) are able to access this data to provide a global data-exchange. Remember, that shared memory is NOT safe against simultaneous access. Use semaphores for synchronization.

Tabela 1. Limits of Shared Memory by the Unix OS

SHMMAX max size of shared memory, normally 131072 bytes
SHMMIN minimum size of shared memory, normally 1 byte
SHMMNI max amount of shared memory segments on a system, normally 100
SHMSEG max amount of shared memory segments per process, normally 6

The messaging functions may be used to send and receive messages to/from other processes. They provide a simple and effective means of exchanging data between processes, without the need for setting up an alternative using unix domain sockets.

Nota: This extension is not available on Windows platforms.


Requisitos

Nenhuma biblioteca externa é necessária para compilar esta extensão.


Instalação

Support for this functions are not enabled by default. To enable System V semaphore support compile PHP with the option --enable-sysvsem. To enable the System V shared memory support compile PHP with the option --enable-sysvshm. To enable the System V messages support compile PHP with the option --enable-sysvmsg.


Configuração durante execução

O comportamento dessas funções podem ser modificado pelas configurações do php.ini.

Tabela 2. Semaphore Configuration Options

Name Default Changeable
sysvmsg.value "42" PHP_INI_ALL
sysvmsg.string "foobar" PHP_INI_ALL
For further details and definition of the PHP_INI_* constants see ini_set().


Tipos Resource


Constantes Predefinidas

Esta extensão não possui nenhuma constante.

Índice
ftok --  Convert a pathname and a project identifier to a System V IPC key
msg_get_queue --  Create or attach to a message queue
msg_receive --  Receive a message from a message queue
msg_remove_queue --  Destroy a message queue
msg_send --  Send a message to a message queue
msg_set_queue --  Set information in the message queue data structure
msg_stat_queue --  Returns information from the message queue data structure
sem_acquire -- Acquire a semaphore
sem_get -- Get a semaphore id
sem_release -- Release a semaphore
sem_remove -- Remove a semaphore
shm_attach -- Creates or open a shared memory segment
shm_detach -- Disconnects from shared memory segment
shm_get_var -- Returns a variable from shared memory
shm_put_var -- Inserts or updates a variable in shared memory
shm_remove_var -- Removes a variable from shared memory
shm_remove -- Removes shared memory from Unix systems

ftok

(PHP 4 >= 4.2.0)

ftok --  Convert a pathname and a project identifier to a System V IPC key

Description

int ftok ( string pathname, string proj)

Atenção

Esta função não está documentada, somente a lista de argumentos está disponível.

msg_get_queue

(PHP 4 >= 4.3.0)

msg_get_queue --  Create or attach to a message queue

Description

int msg_get_queue ( int key [, int perms])

msg_get_queue() returns an id that can be used to access the System V message queue with the given key. The first call creates the message queue with the optional perms (default: 0666). A second call to msg_get_queue() for the same key will return a different message queue identifier, but both identifiers access the same underlying message queue. If the message queue already exists, the perms will be ignored.

See also: msg_remove_queue(), msg_receive(), msg_send(), msg_stat_queue() and msg_set_queue().

This function was introduced in PHP 4.3.0 (not yet released).

msg_receive

(PHP 4 >= 4.3.0)

msg_receive --  Receive a message from a message queue

Description

bool msg_receive ( int queue, int desiredmsgtype, int msgtype, int maxsize, mixed message [, bool unserialize [, int flags [, int errorcode]]])

msg_receive() will receive the first message from the specified queue of the type specified by desiredmsgtype. The type of the message that was received will be stored in msgtype. The maximum size of message to be accepted is specified by the maxsize; if the message in the queue is larger than this size the function will fail (unless you set flags as described below). The received message will be stored in message, unless there were errors receiving the message, in which case the optional errorcode will be set to the value of the system errno variable to help you identify the cause.

If desiredmsgtype is 0, the message from the front of the queue is returned. If desiredmsgtype is greater than 0, then the first message of that type is returned. If desiredmsgtype is less than 0, the first message on the queue with the lowest type less than or equal to the absolute value of desiredmsgtype will be read. If no messages match the criteria, your script will wait until a suitable message arrives on the queue. You can prevent the script from blocking by specifying MSG_IPC_NOWAIT in the flags parameter.

unserialize defaults to TRUE; if it is set to TRUE, the message is treated as though it was serialized using the same mechanism as the session module. The message will be unserialized and then returned to your script. This allows you to easily receive arrays or complex object structures from other PHP scripts, or if you are using the WDDX serializer, from any WDDX compatible source. If unserialize is FALSE, the message will be returned as a binary-safe string.

The optional flags allows you to pass flags to the low-level msgrcv system call. It defaults to 0, but you may specify one or more of the following values (by adding or ORing them together).

Tabela 1. Flag values for msg_receive

MSG_IPC_NOWAIT If there are no messages of the desiredmsgtype, return immediately and do not wait. The function will fail and return an integer value corresponding to ENOMSG.
MSG_EXCEPT Using this flag in combination with a desiredmsgtype greater than 0 will cause the function to receive the first message that is not equal to desiredmsgtype.
MSG_NOERROR If the message is longer than maxsize, setting this flag will truncate the message to maxsize and will not signal an error.

Upon successful completion the message queue data structure is updated as follows: msg_lrpid is set to the process-ID of the calling process, msg_qnum is decremented by 1 and msg_rtime is set to the current time.

msg_receive() returns TRUE on success or FALSE on failure. If the function fails, the optional errorcode will be set to the value of the system errno variable.

See also: msg_remove_queue(), msg_send(), msg_stat_queue() and msg_set_queue().

This function was introduced in PHP 4.3.0 (not yet released).

msg_remove_queue

(PHP 4 >= 4.3.0)

msg_remove_queue --  Destroy a message queue

Description

bool msg_remove_queue ( int queue)

msg_remove_queue() destroys the message queue specified by the queue. Only use this function when all processes have finished working with the message queue and you need to release the system resources held by it.

See also: msg_remove_queue(), msg_receive(), msg_stat_queue() and msg_set_queue().

This function was introduced in PHP 4.3.0 (not yet released).

msg_send

(PHP 4 >= 4.3.0)

msg_send --  Send a message to a message queue

Description

bool msg_send ( int queue, int msgtype, mixed message [, bool serialize [, bool blocking [, int errorcode]]])

msg_send() sends a message of type msgtype (which MUST be greater than 0) to a the message queue specified by queue.

If the message is too large to fit in the queue, your script will wait until another process reads messages from the queue and frees enough space for your message to be sent. This is called blocking; you can prevent blocking by setting the optional blocking parameter to FALSE, in which case msg_send() will immediately return FALSE if the message is too big for the queue, and set the optional errorcode to EAGAIN, indicating that you should try to send your message again a little later on.

The optional serialize controls how the message is sent. serialize defaults to TRUE which means that the message is serialized using the same mechanism as the session module before being sent to the queue. This allows complex arrays and objects to be sent to other PHP scripts, or if you are using the WDDX serializer, to any WDDX compatible client.

Upon successful completion the message queue data structure is updated as follows: msg_lspid is set to the process-ID of the calling process, msg_qnum is incremented by 1 and msg_stime is set to the current time.

See also: msg_remove_queue(), msg_receive(), msg_stat_queue() and msg_set_queue().

This function was introduced in PHP 4.3.0 (not yet released).

msg_set_queue

(PHP 4 >= 4.3.0)

msg_set_queue --  Set information in the message queue data structure

Description

bool msg_set_queue ( int queue, array data)

msg_set_queue() allows you to change the values of the msg_perm.uid, msg_perm.gid, msg_perm.mode and msg_qbytes fields of the underlying message queue data structure. You specify the values you require by setting the value of the keys that you require in the data array.

Changing the data structure will require that PHP be running as the same user that created the the queue, owns the queue (as determined by the existing msg_perm.xxx fields), or be running with root privileges. root privileges are required to raise the msg_qbytes values above the system defined limit.

See also: msg_remove_queue(), msg_receive(), msg_stat_queue() and msg_set_queue().

This function was introduced in PHP 4.3.0 (not yet released).

msg_stat_queue

(PHP 4 >= 4.3.0)

msg_stat_queue --  Returns information from the message queue data structure

Description

array msg_stat_queue ( int queue)

msg_stat_queue() returns the message queue meta data for the message queue specified by the queue. This is useful, for example, to determine which process sent the message that was just received.

The return value is an array whose keys and values have the following meanings:

Tabela 1. Array structure for msg_stat_queue

msg_perm.uid The uid of the owner of the queue.
msg_perm.gid The gid of the owner of the queue.
msg_perm.mode The file access mode of the queue.
msg_stime The time that the last message was sent to the queue.
msg_rtime The time that the last message was received from the queue.
msg_ctime The time that the queue was last changed.
msg_qnum The number of messages waiting to be read from the queue.
msg_qbytes The number of bytes of space currently available in the queue to hold sent messages until they are received.
msg_lspid The pid of the process that sent the last message to the queue.
msg_lrpid The pid of the process that received the last message from the queue.

See also: msg_remove_queue(), msg_receive(), msg_stat_queue() and msg_set_queue().

This function was introduced in PHP 4.3.0 (not yet released).

sem_acquire

(PHP 3>= 3.0.6, PHP 4 )

sem_acquire -- Acquire a semaphore

Description

bool sem_acquire ( int sem_identifier)

Returns: TRUE on success, FALSE on error.

sem_acquire() blocks (if necessary) until the semaphore can be acquired. A process attempting to acquire a semaphore which it has already acquired will block forever if acquiring the semaphore would cause its max_acquire value to be exceeded.

After processing a request, any semaphores acquired by the process but not explicitly released will be released automatically and a warning will be generated.

See also: sem_get() and sem_release().

sem_get

(PHP 3>= 3.0.6, PHP 4 )

sem_get -- Get a semaphore id

Description

int sem_get ( int key [, int max_acquire [, int perm]])

Returns: A positive semaphore identifier on success, or FALSE on error.

sem_get() returns an id that can be used to access the System V semaphore with the given key. The semaphore is created if necessary using the permission bits specified in perm (defaults to 0666). The number of processes that can acquire the semaphore simultaneously is set to max_acquire (defaults to 1). Actually this value is set only if the process finds it is the only process currently attached to the semaphore.

A second call to sem_get() for the same key will return a different semaphore identifier, but both identifiers access the same underlying semaphore.

See also: sem_acquire(), sem_release() and ftok().

Nota: This function does not work on Windows systems.

sem_release

(PHP 3>= 3.0.6, PHP 4 )

sem_release -- Release a semaphore

Description

bool sem_release ( int sem_identifier)

Returns: TRUE on success, FALSE on error.

sem_release() releases the semaphore if it is currently acquired by the calling process, otherwise a warning is generated.

After releasing the semaphore, sem_acquire() may be called to re-acquire it.

See also: sem_get() and sem_acquire().

Nota: This function does not work on Windows systems.

sem_remove

(PHP 4 >= 4.1.0)

sem_remove -- Remove a semaphore

Description

bool sem_remove ( int sem_identifier)

Returns: TRUE on success, FALSE on error.

sem_remove() removes the semaphore sem_identifier if it has been created by sem_get(), otherwise generates a warning.

After removing the semaphore, it is no more accessible.

See also: sem_get(), sem_release() and sem_acquire().

Nota: This function does not work on Windows systems. It was added on PHP 4.1.0.

shm_attach

(PHP 3>= 3.0.6, PHP 4 )

shm_attach -- Creates or open a shared memory segment

Description

int shm_attach ( int key [, int memsize [, int perm]])

shm_attach() returns an id that that can be used to access the System V shared memory with the given key, the first call creates the shared memory segment with mem_size (default: sysvshm.init_mem in the configuration file, otherwise 10000 bytes) and the optional perm-bits (default: 0666).

A second call to shm_attach() for the same key will return a different shared memory identifier, but both identifiers access the same underlying shared memory. Memsize and perm will be ignored.

See also: ftok().

Nota: This function does not work on Windows systems.

shm_detach

(PHP 3>= 3.0.6, PHP 4 )

shm_detach -- Disconnects from shared memory segment

Description

bool shm_detach ( int shm_identifier)

shm_detach() disconnects from the shared memory given by the shm_identifier created by shm_attach(). Remember, that shared memory still exist in the Unix system and the data is still present.

shm_detach() always returns TRUE.

shm_get_var

(PHP 3>= 3.0.6, PHP 4 )

shm_get_var -- Returns a variable from shared memory

Description

mixed shm_get_var ( int id, int variable_key)

shm_get_var() returns the variable with a given variable_key. The variable is still present in the shared memory.

Nota: This function does not work on Windows systems.

shm_put_var

(PHP 3>= 3.0.6, PHP 4 )

shm_put_var -- Inserts or updates a variable in shared memory

Description

int shm_put_var ( int shm_identifier, int variable_key, mixed variable)

Inserts or updates a variable with a given variable_key. All variable-types are supported.

Nota: This function does not work on Windows systems.

shm_remove_var

(PHP 3>= 3.0.6, PHP 4 )

shm_remove_var -- Removes a variable from shared memory

Description

int shm_remove_var ( int id, int variable_key)

Removes a variable with a given variable_key and frees the occupied memory.

Nota: This function does not work on Windows systems.

shm_remove

(PHP 3>= 3.0.6, PHP 4 )

shm_remove -- Removes shared memory from Unix systems

Description

int shm_remove ( int shm_identifier)

Removes shared memory from Unix systems. All data will be destroyed.

Nota: This function does not work on Windows systems.

XCII. SESAM database functions

Introdução

SESAM/SQL-Server is a mainframe database system, developed by Fujitsu Siemens Computers, Germany. It runs on high-end mainframe servers using the operating system BS2000/OSD.

In numerous productive BS2000 installations, SESAM/SQL-Server has proven

  • the ease of use of Java-, Web- and client/server connectivity,

  • the capability to work with an availability of more than 99.99%,

  • the ability to manage tens and even hundreds of thousands of users.

There is a PHP3 SESAM interface available which allows database operations via PHP-scripts.

Nota: Access to SESAM is only available with the latest CVS-Version of PHP3. PHP 4 does not support the SESAM database.


Configuração durante execução

O comportamento dessas funções podem ser modificado pelas configurações do php.ini.

sesam_oml string

Name of BS2000 PLAM library containing the loadable SESAM driver modules. Required for using SESAM functions. The BS2000 PLAM library must be set ACCESS=READ,SHARE=YES because it must be readable by the apache server's user id.

sesam_configfile string

Name of SESAM application configuration file. Required for using SESAM functions. The BS2000 file must be readable by the apache server's user id.

The application configuration file will usually contain a configuration like (see SESAM reference manual):

CNF=B
NAM=K
NOTYPE

sesam_messagecatalog string

Name of SESAM message catalog file. In most cases, this directive is not neccessary. Only if the SESAM message file is not installed in the system's BS2000 message file table, it can be set with this directive.

The message catalog must be set ACCESS=READ,SHARE=YES because it must be readable by the apache server's user id.


Configuration notes

There is no standalone support for the PHP SESAM interface, it works only as an integrated Apache module. In the Apache PHP module, this SESAM interface is configured using Apache directives.

Tabela 1. SESAM Configuration directives

Directive Meaning
php3_sesam_oml Name of BS2000 PLAM library containing the loadable SESAM driver modules. Required for using SESAM functions.

Example:

php3_sesam_oml $.SYSLNK.SESAM-SQL.030

php3_sesam_configfile Name of SESAM application configuration file. Required for using SESAM functions.

Example:

php3_sesam_configfile $SESAM.SESAM.CONF.AW

It will usually contain a configuration like (see SESAM reference manual):

CNF=B
NAM=K
NOTYPE

php3_sesam_messagecatalog Name of SESAM message catalog file. In most cases, this directive is not neccessary. Only if the SESAM message file is not installed in the system's BS2000 message file table, it can be set with this directive.

Example:

php3_sesam_messagecatalog $.SYSMES.SESAM-SQL.030

In addition to the configuration of the PHP/SESAM interface, you have to configure the SESAM-Database server itself on your mainframe as usual. That means:

  • starting the SESAM database handler (DBH), and

  • connecting the databases with the SESAM database handler

To get a connection between a PHP script and the database handler, the CNF and NAM parameters of the selected SESAM configuration file must match the id of the started database handler.

In case of distributed databases you have to start a SESAM/SQL-DCN agent with the distribution table including the host and database names.

The communication between PHP (running in the POSIX subsystem) and the database handler (running outside the POSIX subsystem) is realized by a special driver module called SQLSCI and SESAM connection modules using common memory. Because of the common memory access, and because PHP is a static part of the web server, database accesses are very fast, as they do not require remote accesses via ODBC, JDBC or UTM.

Only a small stub loader (SESMOD) is linked with PHP, and the SESAM connection modules are pulled in from SESAM's OML PLAM library. In the configuration, you must tell PHP the name of this PLAM library, and the file link to use for the SESAM configuration file (As of SESAM V3.0, SQLSCI is available in the SESAM Tool Library, which is part of the standard distribution).

Because the SQL command quoting for single quotes uses duplicated single quotes (as opposed to a single quote preceded by a backslash, used in some other databases), it is advisable to set the PHP configuration directives php3_magic_quotes_gpc and php3_magic_quotes_sybase to On for all PHP scripts using the SESAM interface.


Runtime considerations

Because of limitations of the BS2000 process model, the driver can be loaded only after the Apache server has forked off its server child processes. This will slightly slow down the initial SESAM request of each child, but subsequent accesses will respond at full speed.

When explicitly defining a Message Catalog for SESAM, that catalog will be loaded each time the driver is loaded (i.e., at the initial SESAM request). The BS2000 operating system prints a message after successful load of the message catalog, which will be sent to Apache's error_log file. BS2000 currently does not allow suppression of this message, it will slowly fill up the log.

Make sure that the SESAM OML PLAM library and SESAM configuration file are readable by the user id running the web server. Otherwise, the server will be unable to load the driver, and will not allow to call any SESAM functions. Also, access to the database must be granted to the user id under which the Apache server is running. Otherwise, connections to the SESAM database handler will fail.


Cursor Types

The result cursors which are allocated for SQL "select type" queries can be either "sequential" or "scrollable". Because of the larger memory overhead needed by "scrollable" cursors, the default is "sequential".

When using "scrollable" cursors, the cursor can be freely positioned on the result set. For each "scrollable" query, there are global default values for the scrolling type (initialized to: SESAM_SEEK_NEXT) and the scrolling offset which can either be set once by sesam_seek_row() or each time when fetching a row using sesam_fetch_row(). When fetching a row using a "scrollable" cursor, the following post-processing is done for the global default values for the scrolling type and scrolling offset:

Tabela 2. Scrolled Cursor Post-Processing

Scroll Type Action
SESAM_SEEK_NEXT none
SESAM_SEEK_PRIOR none
SESAM_SEEK_FIRST set scroll type to SESAM_SEEK_NEXT
SESAM_SEEK_LAST set scroll type to SESAM_SEEK_PRIOR
SESAM_SEEK_ABSOLUTE Auto-Increment internal offset value
SESAM_SEEK_RELATIVE none. (maintain global default offset value, which allows for, e.g., fetching each 10th row backwards)


Porting note

Because in the PHP world it is natural to start indexes at zero (rather than 1), some adaptions have been made to the SESAM interface: whenever an indexed array is starting with index 1 in the native SESAM interface, the PHP interface uses index 0 as a starting point. E.g., when retrieving columns with sesam_fetch_row(), the first column has the index 0, and the subsequent columns have indexes up to (but not including) the column count ($array["count"]). When porting SESAM applications from other high level languages to PHP, be aware of this changed interface. Where appropriate, the description of the respective php sesam functions include a note that the index is zero based.


Security concerns

When allowing access to the SESAM databases, the web server user should only have as little privileges as possible. For most databases, only read access privilege should be granted. Depending on your usage scenario, add more access rights as you see fit. Never allow full control to any database for any user from the 'net! Restrict access to php scripts which must administer the database by using password control and/or SSL security.


Migration from other SQL databases

No two SQL dialects are ever 100% compatible. When porting SQL applications from other database interfaces to SESAM, some adaption may be required. The following typical differences should be noted:

  • Vendor specific data types

    Some vendor specific data types may have to be replaced by standard SQL data types (e.g., TEXT could be replaced by VARCHAR(max. size)).

  • Keywords as SQL identifiers

    In SESAM (as in standard SQL), such identifiers must be enclosed in double quotes (or renamed).

  • Display length in data types

    SESAM data types have a precision, not a display length. Instead of int(4) (intended use: integers up to '9999'), SESAM requires simply int for an implied size of 31 bits. Also, the only datetime data types available in SESAM are: DATE, TIME(3) and TIMESTAMP(3).

  • SQL types with vendor-specific unsigned, zerofill, or auto_increment attributes

    Unsigned and zerofill are not supported. Auto_increment is automatic (use "INSERT ... VALUES(*, ...)" instead of "... VALUES(0, ...)" to take advantage of SESAM-implied auto-increment.

  • int ... DEFAULT '0000'

    Numeric variables must not be initialized with string constants. Use DEFAULT 0 instead. To initialize variables of the datetime SQL data types, the initialization string must be prefixed with the respective type keyword, as in: CREATE TABLE exmpl ( xtime timestamp(3) DEFAULT TIMESTAMP '1970-01-01 00:00:00.000' NOT NULL );

  • $count = xxxx_num_rows();

    Some databases promise to guess/estimate the number of the rows in a query result, even though the returned value is grossly incorrect. SESAM does not know the number of rows in a query result before actually fetching them. If you REALLY need the count, try SELECT COUNT(...) WHERE ..., it will tell you the number of hits. A second query will (hopefully) return the results.

  • DROP TABLE thename;

    In SESAM, in the DROP TABLE command, the table name must be either followed by the keyword RESTRICT or CASCADE. When specifying RESTRICT, an error is returned if there are dependent objects (e.g., VIEWs), while with CASCADE, dependent objects will be deleted along with the specified table.


Notes on the use of various SQL types

SESAM does not currently support the BLOB type. A future version of SESAM will have support for BLOB.

At the PHP interface, the following type conversions are automatically applied when retrieving SQL fields:

Tabela 3. SQL to PHP Type Conversions

SQL Type PHP Type
SMALLINT, INTEGER integer
NUMERIC, DECIMAL, FLOAT, REAL, DOUBLE float
DATE, TIME, TIMESTAMP string
VARCHAR, CHARACTER string
When retrieving a complete row, the result is returned as an array. Empty fields are not filled in, so you will have to check for the existence of the individual fields yourself (use isset() or empty() to test for empty fields). That allows more user control over the appearance of empty fields (than in the case of an empty string as the representation of an empty field).


Support of SESAM's "multiple fields" feature

The special "multiple fields" feature of SESAM allows a column to consist of an array of fields. Such a "multiple field" column can be created like this:

Exemplo 1. Creating a "multiple field" column

CREATE TABLE multi_field_test (
    pkey CHAR(20) PRIMARY KEY,
    multi(3) CHAR(12)
)
and can be filled in using:

Exemplo 2. Filling a "multiple field" column

INSERT INTO multi_field_test (pkey, multi(2..3) )
    VALUES ('Second', <'first_val', 'second_val'>)
Note that (like in this case) leading empty sub-fields are ignored, and the filled-in values are collapsed, so that in the above example the result will appear as multi(1..2) instead of multi(2..3).

When retrieving a result row, "multiple columns" are accessed like "inlined" additional columns. In the example above, "pkey" will have the index 0, and the three "multi(1..3)" columns will be accessible as indices 1 through 3.


Veja Também

For specific SESAM details, please refer to the SESAM/SQL-Server documentation (english) or the SESAM/SQL-Server documentation (german), both available online, or use the respective manuals.

Índice
sesam_affected_rows --  Get number of rows affected by an immediate query
sesam_commit --  Commit pending updates to the SESAM database
sesam_connect -- Open SESAM database connection
sesam_diagnostic --  Return status information for last SESAM call
sesam_disconnect -- Detach from SESAM connection
sesam_errormsg -- Returns error message of last SESAM call
sesam_execimm -- Execute an "immediate" SQL-statement
sesam_fetch_array -- Fetch one row as an associative array
sesam_fetch_result -- Return all or part of a query result
sesam_fetch_row -- Fetch one row as an array
sesam_field_array --  Return meta information about individual columns in a result
sesam_field_name --  Return one column name of the result set
sesam_free_result -- Releases resources for the query
sesam_num_fields --  Return the number of fields/columns in a result set
sesam_query -- Perform a SESAM SQL query and prepare the result
sesam_rollback --  Discard any pending updates to the SESAM database
sesam_seek_row --  Set scrollable cursor mode for subsequent fetches
sesam_settransaction -- Set SESAM transaction parameters

sesam_affected_rows

(PHP 3 CVS only)

sesam_affected_rows --  Get number of rows affected by an immediate query

Description

int sesam_affected_rows ( string result_id)

result_id is a valid result id returned by sesam_query().

Returns the number of rows affected by a query associated with result_id.

The sesam_affected_rows() function can only return useful values when used in combination with "immediate" SQL statements (updating operations like INSERT, UPDATE and DELETE) because SESAM does not deliver any "affected rows" information for "select type" queries. The number returned is the number of affected rows.

See also: sesam_query() and sesam_execimm()

$result = sesam_execimm ("DELETE FROM PHONE WHERE LASTNAME = '".strtoupper ($name)."'");
if (!$result) {
    ... error ...
}
print sesam_affected_rows ($result).
    " entries with last name ".$name." deleted.\n"

sesam_commit

(PHP 3 CVS only)

sesam_commit --  Commit pending updates to the SESAM database

Description

bool sesam_commit ( void)

Returns: TRUE on success, FALSE on errors

sesam_commit() commits any pending updates to the database.

Note that there is no "auto-commit" feature as in other databases, as it could lead to accidental data loss. Uncommitted data at the end of the current script (or when calling sesam_disconnect()) will be discarded by an implied sesam_rollback() call.

See also: sesam_rollback().

Exemplo 1. Committing an update to the SESAM database

<?php
if (sesam_connect ("mycatalog", "myschema", "otto")) {
    if (!sesam_execimm ("INSERT INTO mytable VALUES (*, 'Small Test', <0, 8, 15>)"))
        die("insert failed");
    if (!sesam_commit())
        die("commit failed");
}
?>

sesam_connect

(PHP 3 CVS only)

sesam_connect -- Open SESAM database connection

Description

bool sesam_connect ( string catalog, string schema, string user)

Returns TRUE if a connection to the SESAM database was made, or FALSE on error.

sesam_connect() establishes a connection to an SESAM database handler task. The connection is always "persistent" in the sense that only the very first invocation will actually load the driver from the configured SESAM OML PLAM library. Subsequent calls will reuse the driver and will immediately use the given catalog, schema, and user.

When creating a database, the "catalog" name is specified in the SESAM configuration directive //ADD-SQL-DATABASE-CATALOG-LIST ENTRY-1 = *CATALOG(CATALOG-NAME = catalogname,...)

The "schema" references the desired database schema (see SESAM handbook).

The "user" argument references one of the users which are allowed to access this "catalog" / "schema" combination. Note that "user" is completely independent from both the system's user id's and from HTTP user/password protection. It appears in the SESAM configuration only.

See also sesam_disconnect().

Exemplo 1. Connect to a SESAM database

<?php
if (!sesam_connect ("mycatalog", "myschema", "otto")
    die("Unable to connect to SESAM");
?>

sesam_diagnostic

(PHP 3 CVS only)

sesam_diagnostic --  Return status information for last SESAM call

Description

array sesam_diagnostic ( void)

Returns an associative array of status and return codes for the last SQL query/statement/command. Elements of the array are:

Tabela 1. Status information returned by sesam_diagnostic()

Element Contents
$array["sqlstate"] 5 digit SQL return code (see the SESAM manual for the description of the possible values of SQLSTATE)
$array["rowcount"] number of affected rows in last update/insert/delete (set after "immediate" statements only)
$array["errmsg"] "human readable" error message string (set after errors only)
$array["errcol"] error column number of previous error (0-based; or -1 if undefined. Set after errors only)
$array["errlin"] error line number of previous error (0-based; or -1 if undefined. Set after errors only)

In the following example, a syntax error (E SEW42AE ILLEGAL CHARACTER) is displayed by including the offending SQL statement and pointing to the error location:

Exemplo 1. Displaying SESAM error messages with error position

<?php
// Function which prints a formatted error message,
// displaying a pointer to the syntax error in the
// SQL statement
function PrintReturncode ($exec_str) {
    $err = Sesam_Diagnostic();
    $colspan=4; // 4 cols for: sqlstate, errlin, errcol, rowcount
    if ($err["errlin"] == -1)
        --$colspan;
    if ($err["errcol"] == -1)
        --$colspan;
    if ($err["rowcount"] == 0)
        --$colspan;
    echo "<TABLE BORDER>\n";
    echo "<TR><TH COLSPAN=".$colspan."><FONT COLOR=red>ERROR:</FONT> ".
	  	htmlspecialchars($err["errmsg"])."</TH></TR>\n";
    if ($err["errcol"] >= 0) {
        echo "<TR><TD COLSPAN=".$colspan."><PRE>\n";
        $errstmt = $exec_str."\n";
        for ($lin=0; $errstmt != ""; ++$lin) {
            if ($lin != $err["errlin"]) { // $lin is less or greater than errlin
                if (!($i = strchr ($errstmt, "\n")))
                    $i = "";
                $line = substr ($errstmt, 0, strlen($errstmt)-strlen($i)+1);
                $errstmt = substr($i, 1);
                if ($line != "\n")
                    print htmlspecialchars ($line);
            } else {
                if (! ($i = strchr ($errstmt, "\n")))
                    $i = "";
                $line = substr ($errstmt, 0, strlen ($errstmt)-strlen($i)+1);
                $errstmt = substr($i, 1);
                for ($col=0; $col < $err["errcol"]; ++$col)
                    echo (substr($line, $col, 1) == "\t") ? "\t" : ".";
                echo "<FONT COLOR=RED><BLINK>\\</BLINK></FONT>\n";
                print "<FONT COLOR=\"#880000\">".htmlspecialchars($line)."</FONT>";
                for ($col=0; $col < $err["errcol"]; ++$col)
                    echo (substr ($line, $col, 1) == "\t") ? "\t" : ".";
                echo "<FONT COLOR=RED><BLINK>/</BLINK></FONT>\n";
            }
        }
        echo "</PRE></TD></TR>\n";
    }
    echo "<TR>\n";
    echo " <TD>sqlstate=" . $err["sqlstate"] . "</TD>\n";
    if ($err["errlin"] != -1)
        echo " <TD>errlin=" . $err["errlin"] . "</TD>\n";
    if ($err["errcol"] != -1)
        echo " <TD>errcol=" . $err["errcol"] . "</TD>\n";
    if ($err["rowcount"] != 0)
         echo " <TD>rowcount=" . $err["rowcount"] . "</TD>\n";
    echo "</TR>\n";
    echo "</TABLE>\n";
}

if (!sesam_connect ("mycatalog", "phoneno", "otto"))
  die ("cannot connect");

$stmt = "SELECT * FROM phone\n".
        " WHERE@ LASTNAME='KRAEMER'\n".
        " ORDER BY FIRSTNAME";
if (!($result = sesam_query ($stmt)))
    PrintReturncode ($stmt);
?>

See also: sesam_errormsg() for simple access to the error string only

sesam_disconnect

(PHP 3 CVS only)

sesam_disconnect -- Detach from SESAM connection

Description

bool sesam_disconnect ( void)

Returns: always TRUE.

sesam_disconnect() closes the logical link to a SESAM database (without actually disconnecting and unloading the driver).

Note that this isn't usually necessary, as the open connection is automatically closed at the end of the script's execution. Uncommitted data will be discarded, because an implicit sesam_rollback() is executed.

sesam_disconnect() will not close the persistent link, it will only invalidate the currently defined "catalog", "schema" and "user" triple, so that any sesam function called after sesam_disconnect() will fail.

See also: sesam_connect().

Exemplo 1. Closing a SESAM connection

if (sesam_connect ("mycatalog", "myschema", "otto")) {
    ... some queries and stuff ...
    sesam_disconnect(); 
}

sesam_errormsg

(PHP 3 CVS only)

sesam_errormsg -- Returns error message of last SESAM call

Description

string sesam_errormsg ( void)

Returns the SESAM error message associated with the most recent SESAM error.

if (!sesam_execimm ($stmt))
  printf ("%s<br>\n", sesam_errormsg());

See also: sesam_diagnostic() for the full set of SESAM SQL status information

sesam_execimm

(PHP 3 CVS only)

sesam_execimm -- Execute an "immediate" SQL-statement

Description

string sesam_execimm ( string query)

Returns: A SESAM "result identifier" on success, or FALSE on error.

sesam_execimm() executes an "immediate" statement (i.e., a statement like UPDATE, INSERT or DELETE which returns no result, and has no INPUT or OUTPUT variables). "select type" queries can not be used with sesam_execimm(). Sets the affected_rows value for retrieval by the sesam_affected_rows() function.

Note that sesam_query() can handle both "immediate" and "select-type" queries. Use sesam_execimm() only if you know beforehand what type of statement will be executed. An attempt to use SELECT type queries with sesam_execimm() will return $err["sqlstate"] == "42SBW".

The returned "result identifier" can not be used for retrieving anything but the sesam_affected_rows(); it is only returned for symmetry with the sesam_query() function.

$stmt = "INSERT INTO mytable VALUES ('one', 'two')";
$result = sesam_execimm ($stmt);
$err = sesam_diagnostic();
print ("sqlstate = ".$err["sqlstate"]."\n".
       "Affected rows = ".$err["rowcount"]." == ".
       sesam_affected_rows($result)."\n");

See also: sesam_query() and sesam_affected_rows().

sesam_fetch_array

(PHP 3 CVS only)

sesam_fetch_array -- Fetch one row as an associative array

Description

array sesam_fetch_array ( string result_id [, int whence [, int offset]])

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

sesam_fetch_array() is an alternative version of sesam_fetch_row(). Instead of storing the data in the numeric indices of the result array, it stores the data in associative indices, using the field names as keys.

result_id is a valid result id returned by sesam_query() (select type queries only!).

For the valid values of the optional whenceand offset parameters, see the sesam_fetch_row() function for details.

sesam_fetch_array() fetches one row of data from the result associated with the specified result identifier. The row is returned as an associative array. Each result column is stored with an associative index equal to its column (aka. field) name. The column names are converted to lower case.

Columns without a field name (e.g., results of arithmetic operations) and empty fields are not stored in the array. Also, if two or more columns of the result have the same column names, the later column will take precedence. In this situation, either call sesam_fetch_row() or make an alias for the column.

SELECT TBL1.COL AS FOO, TBL2.COL AS BAR FROM TBL1, TBL2

A special handling allows fetching "multiple field" columns (which would otherwise all have the same column names). For each column of a "multiple field", the index name is constructed by appending the string "(n)" where n is the sub-index of the multiple field column, ranging from 1 to its declared repetition factor. The indices are NOT zero based, in order to match the nomenclature used in the respective query syntax. For a column declared as:

CREATE TABLE ... ( ... MULTI(3) INT )

the associative indices used for the individual "multiple field" columns would be "multi(1)", "multi(2)", and "multi(3)" respectively.

Subsequent calls to sesam_fetch_array() would return the next (or prior, or n'th next/prior, depending on the scroll attributes) row in the result set, or FALSE if there are no more rows.

Exemplo 1. SESAM fetch array

<?php
$result = sesam_query ("SELECT * FROM phone\n".
                       "  WHERE LASTNAME='".strtoupper($name)."'\n".
                       "  ORDER BY FIRSTNAME", 1);
if (!$result) {
    ... error ...
}
// print the table:
print "<TABLE BORDER>\n";
while (($row = sesam_fetch_array ($result)) && count ($row) > 0) {
    print " <TR>\n";
    print " <TD>".htmlspecialchars ($row["firstname"])."</TD>\n";
    print " <TD>".htmlspecialchars ($row["lastname"])."</TD>\n";
    print " <TD>".htmlspecialchars ($row["phoneno"])."</TD>\n";
    print " </TR>\n";
}
print "</TABLE>\n";
sesam_free_result ($result);
?>

See also: sesam_fetch_row() which returns an indexed array.

sesam_fetch_result

(PHP 3 CVS only)

sesam_fetch_result -- Return all or part of a query result

Description

mixed sesam_fetch_result ( string result_id [, int max_rows])

Returns a mixed array with the query result entries, optionally limited to a maximum of max_rows rows. Note that both row and column indexes are zero-based.

Tabela 1. Mixed result set returned by sesam_fetch_result()

Array Element Contents
int $arr["count"] number of columns in result set (or zero if this was an "immediate" query)
int $arr["rows"] number of rows in result set (between zero and max_rows)
bool $arr["truncated"] TRUE if the number of rows was at least max_rows, FALSE otherwise. Note that even when this is TRUE, the next sesam_fetch_result() call may return zero rows because there are no more result entries.
mixed $arr[col][row] result data for all the fields at row(row) and column(col), (where the integer index row is between 0 and $arr["rows"]-1, and col is between 0 and $arr["count"]-1). Fields may be empty, so you must check for the existence of a field by using the php isset() function. The type of the returned fields depend on the respective SQL type declared for its column (see SESAM overview for the conversions applied). SESAM "multiple fields" are "inlined" and treated like a sequence of columns.
Note that the amount of memory used up by a large query may be gigantic. Use the max_rows parameter to limit the maximum number of rows returned, unless you are absolutely sure that your result will not use up all available memory.

See also: sesam_fetch_row(), and sesam_field_array() to check for "multiple fields". See the description of the sesam_query() function for a complete example using sesam_fetch_result().

sesam_fetch_row

(PHP 3 CVS only)

sesam_fetch_row -- Fetch one row as an array

Description

array sesam_fetch_row ( string result_id [, int whence [, int offset]])

Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

The number of columns in the result set is returned in an associative array element $array["count"]. Because some of the result columns may be empty, the count() function can not be used on the result row returned by sesam_fetch_row().

result_id is a valid result id returned by sesam_query() (select type queries only!).

whence is an optional parameter for a fetch operation on "scrollable" cursors, which can be set to the following predefined constants:

Tabela 1. Valid values for "whence" parameter

Value Constant Meaning
0 SESAM_SEEK_NEXT read sequentially (after fetch, the internal default is set to SESAM_SEEK_NEXT)
1 SESAM_SEEK_PRIOR read sequentially backwards (after fetch, the internal default is set to SESAM_SEEK_PRIOR)
2 SESAM_SEEK_FIRST rewind to first row (after fetch, the default is set to SESAM_SEEK_NEXT)
3 SESAM_SEEK_LAST seek to last row (after fetch, the default is set to SESAM_SEEK_PRIOR)
4 SESAM_SEEK_ABSOLUTE seek to absolute row number given as offset (Zero-based. After fetch, the internal default is set to SESAM_SEEK_ABSOLUTE, and the internal offset value is auto-incremented)
5 SESAM_SEEK_RELATIVE seek relative to current scroll position, where offset can be a positive or negative offset value.
This parameter is only valid for "scrollable" cursors.

When using "scrollable" cursors, the cursor can be freely positioned on the result set. If the whence parameter is omitted, the global default values for the scrolling type (initialized to: SESAM_SEEK_NEXT, and settable by sesam_seek_row()) are used. If whence is supplied, its value replaces the global default.

offset is an optional parameter which is only evaluated (and required) if whence is either SESAM_SEEK_RELATIVE or SESAM_SEEK_ABSOLUTE. This parameter is only valid for "scrollable" cursors.

sesam_fetch_row() fetches one row of data from the result associated with the specified result identifier. The row is returned as an array (indexed by values between 0 and $array["count"]-1). Fields may be empty, so you must check for the existence of a field by using the php isset() function. The type of the returned fields depend on the respective SQL type declared for its column (see SESAM overview for the conversions applied). SESAM "multiple fields" are "inlined" and treated like a sequence of columns.

Subsequent calls to sesam_fetch_row() would return the next (or prior, or n'th next/prior, depending on the scroll attributes) row in the result set, or FALSE if there are no more rows.

Exemplo 1. SESAM fetch rows

<?php
$result = sesam_query ("SELECT * FROM phone\n".
                       "  WHERE LASTNAME='".strtoupper($name)."'\n".
                       "  ORDER BY FIRSTNAME", 1);
if (!$result) {
    ... error ...
}
// print the table in backward order
print "<TABLE BORDER>\n";
$row = sesam_fetch_row ($result, SESAM_SEEK_LAST);
while (is_array ($row)) {
    print " <TR>\n";
    for ($col = 0; $col < $row["count"]; ++$col) {
        print "  <TD>".htmlspecialchars ($row[$col])."</TD>\n";
    }
    print " </TR>\n";
    // use implied SESAM_SEEK_PRIOR
    $row = sesam_fetch_row ($result);
}
print "</TABLE>\n";
sesam_free_result ($result);
?>

See also: sesam_fetch_array() which returns an associative array, and sesam_fetch_result() which returns many rows per invocation.

sesam_field_array

(PHP 3 CVS only)

sesam_field_array --  Return meta information about individual columns in a result

Description

array sesam_field_array ( string result_id)

result_id is a valid result id returned by sesam_query().

Returns a mixed associative/indexed array with meta information (column name, type, precision, ...) about individual columns of the result after the query associated with result_id.

Tabela 1. Mixed result set returned by sesam_field_array()

Array Element Contents
int $arr["count"] Total number of columns in result set (or zero if this was an "immediate" query). SESAM "multiple fields" are "inlined" and treated like the respective number of columns.
string $arr[col]["name"] column name for column(col), where col is between 0 and $arr["count"]-1. The returned value can be the empty string (for dynamically computed columns). SESAM "multiple fields" are "inlined" and treated like the respective number of columns, each with the same column name.
string $arr[col]["count"] The "count" attribute describes the repetition factor when the column has been declared as a "multiple field". Usually, the "count" attribute is 1. The first column of a "multiple field" column however contains the number of repetitions (the second and following column of the "multiple field" contain a "count" attribute of 1). This can be used to detect "multiple fields" in the result set. See the example shown in the sesam_query() description for a sample use of the "count" attribute.
string $arr[col]["type"] php variable type of the data for column(col), where col is between 0 and $arr["count"]-1. The returned value can be one of

depending on the SQL type of the result. SESAM "multiple fields" are "inlined" and treated like the respective number of columns, each with the same php type.
string $arr[col]["sqltype"] SQL variable type of the column data for column(col), where col is between 0 and $arr["count"]-1. The returned value can be one of

  • "CHARACTER"

  • "VARCHAR"

  • "NUMERIC"

  • "DECIMAL"

  • "INTEGER"

  • "SMALLINT"

  • "FLOAT"

  • "REAL"

  • "DOUBLE"

  • "DATE"

  • "TIME"

  • "TIMESTAMP"

describing the SQL type of the result. SESAM "multiple fields" are "inlined" and treated like the respective number of columns, each with the same SQL type.
string $arr[col]["length"] The SQL "length" attribute of the SQL variable in column(col), where col is between 0 and $arr["count"]-1. The "length" attribute is used with "CHARACTER" and "VARCHAR" SQL types to specify the (maximum) length of the string variable. SESAM "multiple fields" are "inlined" and treated like the respective number of columns, each with the same length attribute.
string $arr[col]["precision"] The "precision" attribute of the SQL variable in column(col), where col is between 0 and $arr["count"]-1. The "precision" attribute is used with numeric and time data types. SESAM "multiple fields" are "inlined" and treated like the respective number of columns, each with the same precision attribute.
string $arr[col]["scale"] The "scale" attribute of the SQL variable in column(col), where col is between 0 and $arr["count"]-1. The "scale" attribute is used with numeric data types. SESAM "multiple fields" are "inlined" and treated like the respective number of columns, each with the same scale attribute.

See the sesam_query() function for an example of the sesam_field_array() use.

sesam_field_name

(PHP 3 CVS only)

sesam_field_name --  Return one column name of the result set

Description

int sesam_field_name ( string result_id, int index)

Returns the name of a field (i.e., the column name) in the result set, or FALSE on error.

For "immediate" queries, or for dynamic columns, an empty string is returned.

Nota: The column index is zero-based, not one-based as in SESAM.

See also: sesam_field_array(). It provides an easier interface to access the column names and types, and allows for detection of "multiple fields".

sesam_free_result

(PHP 3 CVS only)

sesam_free_result -- Releases resources for the query

Description

int sesam_free_result ( string result_id)

Releases resources for the query associated with result_id. Returns FALSE on error.

sesam_num_fields

(PHP 3 CVS only)

sesam_num_fields --  Return the number of fields/columns in a result set

Description

int sesam_num_fields ( string result_id)

After calling sesam_query() with a "select type" query, this function gives you the number of columns in the result. Returns an integer describing the total number of columns (aka. fields) in the current result_id result set or FALSE on error.

For "immediate" statements, the value zero is returned. The SESAM "multiple field" columns count as their respective dimension, i.e., a three-column "multiple field" counts as three columns.

See also: sesam_query() and sesam_field_array() for a way to distinguish between "multiple field" columns and regular columns.

sesam_query

(PHP 3 CVS only)

sesam_query -- Perform a SESAM SQL query and prepare the result

Description

string sesam_query ( string query [, bool scrollable])

Returns: A SESAM "result identifier" on success, or FALSE on error.

A "result_id" resource is used by other functions to retrieve the query results.

sesam_query() sends a query to the currently active database on the server. It can execute both "immediate" SQL statements and "select type" queries. If an "immediate" statement is executed, then no cursor is allocated, and any subsequent sesam_fetch_row() or sesam_fetch_result() call will return an empty result (zero columns, indicating end-of-result). For "select type" statements, a result descriptor and a (scrollable or sequential, depending on the optional boolean scrollable parameter) cursor will be allocated. If scrollable is omitted, the cursor will be sequential.

When using "scrollable" cursors, the cursor can be freely positioned on the result set. For each "scrollable" query, there are global default values for the scrolling type (initialized to: SESAM_SEEK_NEXT) and the scrolling offset which can either be set once by sesam_seek_row() or each time when fetching a row using sesam_fetch_row().

For "immediate" statements, the number of affected rows is saved for retrieval by the sesam_affected_rows() function.

See also: sesam_fetch_row() and sesam_fetch_result().

Exemplo 1. Show all rows of the "phone" table as a html table

<?php
if (!sesam_connect ("phonedb", "demo", "otto"))
    die ("cannot connect");
$result = sesam_query ("select * from phone");
if (!$result) {
    $err = sesam_diagnostic();
    die ($err["errmsg"]);
}
echo "<TABLE BORDER>\n";
// Add title header with column names above the result:
if ($cols = sesam_field_array ($result)) {
    echo " <TR><TH COLSPAN=".$cols["count"].">Result:</TH></TR>\n";
    echo " <TR>\n";
    for ($col = 0; $col < $cols["count"]; ++$col) {
        $colattr = $cols[$col];
        /* Span the table head over SESAM's "Multiple Fields": */
        if ($colattr["count"] > 1) {
            echo "  <TH COLSPAN=".$colattr["count"].">".$colattr["name"].
                "(1..".$colattr["count"].")</TH>\n";
            $col += $colattr["count"] - 1;
        } else
            echo "  <TH>" . $colattr["name"] . "</TH>\n";
    }
    echo " </TR>\n";
}

do {
    // Fetch the result in chunks of 100 rows max.
    $ok = sesam_fetch_result ($result, 100);
    for ($row=0; $row < $ok["rows"]; ++$row) {
        echo " <TR>\n";
        for ($col = 0; $col < $ok["cols"]; ++$col) {
            if (isset($ok[$col][$row]))
                echo "  <TD>" . $ok[$col][$row] . "</TD>\n";
            } else {
                echo "  <TD>-empty-</TD>\n";
            }
        }
        echo " </TR>\n";
    }
} 
while ($ok["truncated"]) { // while there may be more data
    echo "</TABLE>\n";
}
// free result id
sesam_free_result($result);
?>

sesam_rollback

(PHP 3 CVS only)

sesam_rollback --  Discard any pending updates to the SESAM database

Description

bool sesam_rollback ( void)

Returns: TRUE on success, FALSE on errors

sesam_rollback() discards any pending updates to the database. Also affected are result cursors and result descriptors.

At the end of each script, and as part of the sesam_disconnect() function, an implied sesam_rollback() is executed, discarding any pending changes to the database.

See also: sesam_commit().

Exemplo 1. Discarding an update to the SESAM database

<?php
if (sesam_connect ("mycatalog", "myschema", "otto")) {
    if (sesam_execimm ("INSERT INTO mytable VALUES (*, 'Small Test', <0, 8, 15>)")
        && sesam_execimm ("INSERT INTO othertable VALUES (*, 'Another Test', 1)"))
        sesam_commit();
    else
        sesam_rollback();
}
?>

sesam_seek_row

(PHP 3 CVS only)

sesam_seek_row --  Set scrollable cursor mode for subsequent fetches

Description

bool sesam_seek_row ( string result_id, int whence [, int offset])

result_id is a valid result id (select type queries only, and only if a "scrollable" cursor was requested when calling sesam_query()).

whence sets the global default value for the scrolling type, it specifies the scroll type to use in subsequent fetch operations on "scrollable" cursors, which can be set to the following predefined constants:

Tabela 1. Valid values for "whence" parameter

Value Constant Meaning
0 SESAM_SEEK_NEXT read sequentially
1 SESAM_SEEK_PRIOR read sequentially backwards
2 SESAM_SEEK_FIRST fetch first row (after fetch, the default is set to SESAM_SEEK_NEXT)
3 SESAM_SEEK_LAST fetch last row (after fetch, the default is set to SESAM_SEEK_PRIOR)
4 SESAM_SEEK_ABSOLUTE fetch absolute row number given as offset (Zero-based. After fetch, the default is set to SESAM_SEEK_ABSOLUTE, and the offset value is auto-incremented)
5 SESAM_SEEK_RELATIVE fetch relative to current scroll position, where offset can be a positive or negative offset value (this also sets the default "offset" value for subsequent fetches).

offset is an optional parameter which is only evaluated (and required) if whence is either SESAM_SEEK_RELATIVE or SESAM_SEEK_ABSOLUTE.

sesam_settransaction

(PHP 3 CVS only)

sesam_settransaction -- Set SESAM transaction parameters

Description

bool sesam_settransaction ( int isolation_level, int read_only)

Returns: TRUE if the values are valid, and the settransaction() operation was successful, FALSE otherwise.

sesam_settransaction() overrides the default values for the "isolation level" and "read-only" transaction parameters (which are set in the SESAM configuration file), in order to optimize subsequent queries and guarantee database consistency. The overridden values are used for the next transaction only.

sesam_settransaction() can only be called before starting a transaction, not after the transaction has been started already.

To simplify the use in php scripts, the following constants have been predefined in php (see SESAM handbook for detailed explanation of the semantics):

Tabela 1. Valid values for "Isolation_Level" parameter

Value Constant Meaning
1 SESAM_TXISOL_READ_UNCOMMITTED Read Uncommitted
2 SESAM_TXISOL_READ_COMMITTED Read Committed
3 SESAM_TXISOL_REPEATABLE_READ Repeatable Read
4 SESAM_TXISOL_SERIALIZABLE Serializable

Tabela 2. Valid values for "Read_Only" parameter

Value Constant Meaning
0 SESAM_TXREAD_READWRITE Read/Write
1 SESAM_TXREAD_READONLY Read-Only

The values set by sesam_settransaction() will override the default setting specified in the SESAM configuration file.

Exemplo 1. Setting SESAM transaction parameters

<?php
sesam_settransaction (SESAM_TXISOL_REPEATABLE_READ,
                     SESAM_TXREAD_READONLY);
?>

XCIII. Manejo de sessões

Introdução

Suporte a sessões no PHP consiste em uma forma de preservar certos dados através de acessos subseqüentes. Isto te permite construir aplicações mais personalizadas e aumenta a atração ao seu web site.

Se você está familiarizado com o gerenciamento de sessões do PHPLIB, você irá notar que alguns conceitos são similares ao suporte de sessões do PHP.

Um visitante acessando seu web site está determinado por uma única id, a então chamada id de sessão. Esta ou é guardada em um cookie do lado do usuário ou está na URL.

Sessões te permite registrar arbitrariamente números de variáveis para estarem lado a lado com os requerimentos. Quando um visitante acessa seu site, o PHP checará automaticamente (se session.auto_start está definida para 1) ou no seu pedido (explicitamente através da session_start() ou implicitamente através da session_register()) se uma id de sessão especifica foi enviada com o pedido. Se este é o caso, o ambiente anterior guardado é restaurado.

Todas as variáveis registradas são publicadas em série após o pedido terminar. Variáveis registradas que estão indefinidas estão marcadas como estando não definida. Num acesso subseqüente, estas não estarão definidas pelo módulo da sessão a menos que o usuário defina elas mais tarde.

Nota: Manejo de sessões foi adicionado no PHP 4.0.


Requisitos

Nenhuma biblioteca externa é necessária para compilar esta extensão.


Instalação

Suporte a sessões esta habilitado no PHP 4.0 por definição. Se você não gostaria de seu PHP com suporte a sessão, você especifica a opção de configuração --disable-session.


Configuração durante execução

O sistema de suporte de sessão oferece no arquivo php.ini numerosas opções de configuração. nós daremos um breve resumo.

  • session.save_handlerdefine o nome do operador(funções-handler) que é usado para guardar e resgatar dados associados com a sessão. Por definição files.

  • session.save_path define o argumento que que é passado para o save handler. Se você escolher o default files handler, este é o caminho onde os arquivos serão criados. Por definição para /tmp. Se a profundidade do caminho de session.save_path é maior do que 2, coleção de lixo não será executada(garbage collection - gc).

    Atenção

    Se você deixar isto definido para um diretório muito visível, tal como /tmp (o padrão), outros usuários do servidor poderão ser capazes de assumir o controle da sessão obtendo a lista de arquivos naquele diretório.

  • session.name especifica o nome da sessão que é usada como nome de cookie. Ela poderia apenas conter caracteres alfanuméricos. Por definição PHPSESSID.

  • session.auto_start especifica se o módulo da sessão inicia a sessão automaticamente num pedido na inicialização. Por definição 0 (desabilitado).

  • session.cookie_lifetime especifica o tempo de vida de um cookie em segundos que é enviado para o navegador. O valor 0 significa "até que o navegador seja fechado." Por definição 0.

  • session.serialize_handler define o nome do operador(handler) que é usado para serializar/deserializar dados. Correntemente, um formato interno do PHP (nome php) e WDDX é suportado (nome wddx). WDDX está apenas disponível, se o PHP está compilado com o suporteWDDX support. Por definição php.

  • session.gc_probability especifica a probabilidade que a rotina gc (coleção de lixo-garbage collection) é iniciada em cada pedido em porcentagem. Por definição 1.

  • session.gc_maxlifetime especifica o número de segundos depois que o dado será visto como 'lixo' e limpado.

  • session.referer_check contém a substring que você quer checar cada HTTP Referer para. Se o Referer foi enviado pelo cliente e a substring não foi encontrada, a id de sessão embutida será percebida como inválida. Por definição uma string vazia.

  • session.entropy_file dá um caminho para um recurso externo(file) que será usado como um entropy source na criação da id de sessão. São exemplos /dev/random ou /dev/urandom que estão disponéveis em muitos Sistemas Unix.

  • session.entropy_length especifíca o número de bytes que serão lidos do arquivo especificado acima. Por definição 0 (desabilitada).

  • session.use_cookies especifica se o módulo usará cookies para gravar a id de sessão no lado do cliente. Por definição 1 (habilitada).

  • session.use_only_cookies especifica se o módulo usaráapenas cookies para gravar a id de sessão no lado do cliente. Por definição 0 (desabilitada). Habilitar esta definição previni ataques envolvendo id de sessão passadas em URLs. Esta definição foi adicionada no PHP 4.3.0.

  • session.cookie_path especifica o caminho para definir em session_cookie. Por definição /.

  • session.cookie_domain especifica o domínio para para definir em session_cookie. Nenhuma definição.

  • session.cache_limiter especifica o método de controle do cache para usar para páginas de sessão (none/nocache/private/private_no_expire/public). Por definição nocache.

  • session.cache_expire especifica o tempo de vida para páginas de sessão no cache em minutos, isto não tem efeito para para limitador sem cache. Por definição 180.

  • session.use_trans_sid se o suporte de sid transparente está habilitado ou não, se habilitado por compilação com --enable-trans-sid. Por definição 1 (habilitado).

  • url_rewriter.tags especifica quais tags html estão reescritas para incluir id de sessão se o suporte transparente de sid está habilitado. Por definição a=href,area=href,frame=src,input=src,form=fakeentry

A configuração de track_vars e register_globals influencia em como as variáveis da sessão conseguem armazenar e devolver.

Nota: No PHP 4.0.3, track_vars está sempre ligada.


Tipos Resource

Esta extensão não possui nenhum tipo resource.


Constantes Predefinidas

As contantes abaixo são definidas por esta extensão e somente estarão disponíveis quando a extensão foi compilada com o PHP ou carregada dinamicamente durante a execução.

SID (string)

Constant containing the session name and session ID in the form of "name=ID".


Exemplos

Nota: No PHP 4.1.0, $_SESSION está disponível como variável global apenas como $_POST, $_GET, $_REQUEST e assim por diante. Não como $HTTP_SESSION_VARS, $_SESSION está sempre global. Então, global poderia não ser usada para $_SESSION.

Se track_vars is habilitada e register_globals está desabilitada, apenas aquelas membros da matriz associativa $HTTP_SESSION_VARS podem ser registradas em uma sessão de variáveis. A sessão de variáveis restauradas somente estarão disponíveis na matriz $HTTP_SESSION_VARS.

Exemplo 1. Registrando uma variável com track_vars habilitada

<?php
session_start();
if (isset($HTTP_SESSION_VARS['count'])) {
   $HTTP_SESSION_VARS['count']++;
}
else {
   $HTTP_SESSION_VARS['count'] = 0;
}
?>

Uso de $_SESSION (ou $HTTP_SESSION_VARS com PHP 4.0.6 ou inferior) é recomendado por segurança e code readablity. Com $_SESSION ou $HTTP_SESSION_VARS, não á necessidade de usar as funções session_register()/session_unregister()/session_is_registered(). Usuários podem acessar variável de sessão como uma variável normal.

Exemplo 2. Registrando uma variável com $_SESSION.

<?php
session_start();
// Use $HTTP_SESSION_VARS with PHP 4.0.6 or less
if (!isset($_SESSION['count'])) {
    $_SESSION['count'] = 0;
} else {
    $_SESSION['count']++;
}
?>

Exemplo 3. Desregistrando uma variável com $_SESSION.

<?php
session_start();
// Use $HTTP_SESSION_VARS with PHP 4.0.6 or less
unset($_SESSION['count']);
?>

Se a register_globals está habilitada, então todas as variáveis globais podem ser registradas como variáveis de sessão e as variáveis de sessão serão restauradas para a variável global correspondente. Visto que o PHP deve saber quais variáveis globais estão registradas como variáveis de sessão, usuaários devem registrar variáveis com a função session_register() enquanto $HTTP_SESSION_VARS/$_SESSION não necessita utilizar session_register().

Cuidado

Se você está usando $HTTP_SESSION_VARS/$_SESSION e desabilitada register_globals, não faça uso de session_register(), session_is_registered() e session_unregister().

Se você habilita register_globals, session_unregister() poderiam ser usadas desde que as variáveis de sessão estejam registradas como variáveis globais quando os dados da sessão não estão em série. Desabilitar register_globals é recomendado para ambas razões, segurança e performance.

Exemplo 4. Registrando uma variável com register_globals habilitada

<?php
if (!session_is_registered('count')) {
    session_register("count");
    $count = 0;
}
else {
    $count++;
}
?>

Se ambas track_vars e register_globals estão habilitadas, então as variáveis globais e as entradas $HTTP_SESSION_VARS/$_SESSION farão referência ao mesmo valor para as variáveis já registradas.

Se o usuário utiliza session_register() para registrar variável de sessão, $HTTP_SESSION_VARS/$_SESSION não terão esta variável numa matriz até que ela seja lida de um armazém de sessão. (i.e. até o próximo pedido)


Passando a ID de sessão

Há dois métodos para propagar uma id de sessão:

  • Cookies

  • Parâmetro URL

Módulo de sessão suporta ambos os métodos. Cookies são mais eficientes, mas se eles não estiverem autorizados (clientes não são obrigados a aceita-los), nós não podemos conter deles. O segundo método inclui a id de sessão diretamente na URL.

PHP é capaz de fazer isto transparentemente quando compilado com --enable-trans-sid. Se você habilitar esta opção, URIs ligadas serão automaticamente mudadas para conter a id de sessão. Alternativamente, você pode usar a constante SID que é definida, se o cliente não enviar o cookie apropriado. SID é do formulário session_name=session_id ou é uma string vazia.

Nota: A diretriz arg_separator.output php.ini permite personalizar o argumento separador.

O seguinte exemplo demonstra como registrar uma variável, e e como ligar corretamente a outra página usando SID.

Exemplo 5. Contar o número de visitas de um simples usuário

<?php
if (!session_is_registered('count')) {
    session_register('count');
    $count = 1;
}
else {
    $count++;
}
?>

Hello visitor, you have seen this page <?php echo $count; ?> times.<p>;

<?php
# the <?php echo SID?> (<?=SID?> can be used if short tag is enabled) 
# is necessary to preserve the session id
# in the case that the user has disabled cookies
?>

To continue, <A HREF="nextpage.php?<?php echo SID?>">click here</A>

A <?=SID?> não é necessário, se --enable-trans-sid foi usada para compilar o PHP.

Nota: URLs não ligadas estão assumidas para apontar para sites externos e portanto não anexam a SID, pois ela poderia escapar para outro servidor.


Session handlers customizáveis

Para implementar o armazenamento num banco de dados, ou qualque outra forma de aramzenamento, você vai precisar usar session_set_save_handler()* para define as funções de armazenamento que são usadas (* to create a set of user-level storage functions).

Índice
session_cache_expire -- Retorna o prazo do cache atual
session_cache_limiter -- Obtém e/ou define o limitador do cache atual
session_decode -- Decifra dado de sessão de uma string
session_destroy -- Destrói todos os dados registrados para uma sessão
session_encode --  Codifica os dados da sessão atual como uma string
session_get_cookie_params --  Obtém os parâmetros do cookie da sessão
session_id -- Obtém e/ou define a id da sessão atual
session_is_registered --  Descobre se uma variável está registrada numa sessão
session_module_name -- Obtém e/ou define o módulo da sessão atual
session_name -- Obtém e/ou define o nome da sessão atual
session_readonly -- Início da sessão - reinicia variáveis congeladas, mas sem escrever de volta no fim da requisição
session_register --  Registrar uma ou mais variáveis na sessão atual
session_save_path -- Obtém e/ou define o save path da sessão atual
session_set_cookie_params --  Define os parâmetros do cookie de sessão
session_set_save_handler --  Define a sequência de funções de armazenamento
session_start -- Inicia dados de sessão
session_unregister --  Desregistra variável da sessão atual
session_unset --  Liberta todas as variáveis de sessão
session_write_close -- Escreve dados de sessão e termina a sessão

session_cache_expire

(PHP 4 >= 4.2.0)

session_cache_expire -- Retorna o prazo do cache atual

Descrição

int session_cache_expire ( [int new_cache_expire])

session_cache_expire() retorna o prazo do cache atual. Se new_cache_expire for dado, o prazo do cache atual é substituído com new_cache_expire.

session_cache_limiter

(PHP 4 >= 4.0.3)

session_cache_limiter -- Obtém e/ou define o limitador do cache atual

Descrição

string session_cache_limiter ( [string cache_limiter])

session_cache_limiter() retorna o nome do atual limitador do cache. Se o cache_limiter está especificado, o nome do limitador do cache atual é mudado para o novo valor.

O limitador do cache controla HTTP headers enviados para o cliente. Estes headers determinam pelas quais o conteúdo da página pode ser guardado no cache. Definindo o limitador do cache para nocache, por exemplo, rejeitaria qualquer armazenamento no cache do cliente. Um valor como public, entretanto, permitiria o armazenamento no cache. Ele também poderia ser definido como private, que é um pouco mais restritivo do que public.

No modo private , Header expirado enviado para o cliente, pode provocar confusão para alguns para alguns navegadores incluindo o Mozilla. Você pode evitar este problema com o modo private_no_expire. Header expirado nunca é enviado para o cliente nesse modo.

Nota: private_no_expire foi adicionado no PHP 4.2.0dev.

O limitador do cache é zerado para o valor padrão guardado em session.cache_limiter no pedido do startup time. Assim, você precisa chamar session_cache_limiter() para cada pedido (e antes session_start() é chamada).

Exemplo 1. session_cache_limiter() exemplos

<?php

# Defini o limitador do cache para 'private'

session_cache_limiter('private');
$cache_limiter = session_cache_limiter();

echo "o limitador do cache est&aacute; definido agora para $cache_limiter<p>";
?>

session_decode

(PHP 4 )

session_decode -- Decifra dado de sessão de uma string

Descrição

bool session_decode ( string data)

session_decode() decifra dado de sessão em data, definindo variáveis guardadas na sessão.

session_destroy

(PHP 4 )

session_destroy -- Destrói todos os dados registrados para uma sessão

Descrição

bool session_destroy ( void)

session_destroy() destrói tudo dos dados associados com a sessão corrente. Ela não elimina nenhuma das variáveis globais associadas com a sessão, e nem o cookie de sessão.

Esta função retorna TRUE caso funcione e FALSE caso falhe para destruição dos dados da sessão.

Exemplo 1. Destruindo uma sessão

<?php

// Inicializa uma sess&atilde;o.
// Se voc&ecirc; est&aacute; usando session_name("something"), n&atilde;o esque&ccedil;a!
session_start();
// Eliminar todas as vari&aacute;veis de sess&atilde;o.
session_unset();
// Finalmente, destrui&ccedil;&atilde;o da sess&atilde;o.
session_destroy();

?>

Exemplo 2. Destruindo uma sessão com $_SESSION

<?php

// Inicializa uma sess&atilde;o.
// Se voc&ecirc; est&aacute; usando session_name("something"), n&atilde;o esque&ccedil;a!
session_start();
// Eliminar todas as vari&aacute;veis de sess&atilde;o.
$_SESSION = array();
// Finalmente, destrui&ccedil;&atilde;o da sess&atilde;o.
session_destroy();

?>

session_encode

(PHP 4 )

session_encode --  Codifica os dados da sessão atual como uma string

Descrição

string session_encode ( void)

session_encode() retorna uma string com o conteúdo da sessão corrente codificado em seu interior.

session_get_cookie_params

(PHP 4 )

session_get_cookie_params --  Obtém os parâmetros do cookie da sessão

Descrição

array session_get_cookie_params ( void)

A função session_get_cookie_params() retorna uma matriz com informação do cookie da sessão atual, a matriz contém os seguintes items:

  • "lifetime" - A duração do cookie.

  • "path" - O caminho onde a informação está guardada.

  • "domain" - O domínio do cookie.

  • "secure" - O cookie seria enviado apenas sobre conexões seguras. (Este item foi incluído no PHP 4.0.4.)

session_id

(PHP 4 )

session_id -- Obtém e/ou define a id da sessão atual

Descrição

string session_id ( [string id])

session_id() retorna a id de sessão para a sessão atual.

Se id está especificado, irá trocar a id da sessão atual. session_id() necessita ser chamada antes de session_start() para esse propósito. Dependendo do session handler, nem todos os caracteres serão permitidos dentro da id de sessão. Por exemplo, o arquivo session handler permite apenas caracteres do intervalo a-z, A-Z e 0-9!

A constante SID também pode ser usada para devolver o nome e a id de sessão atual como uma string combinada para adicionar nas URLs. Note que SID está apenas definido se o cliente não enviou o cookie correto. Veja também Session handling.

Veja também session_start().

session_is_registered

(PHP 4 )

session_is_registered --  Descobre se uma variável está registrada numa sessão

Descrição

bool session_is_registered ( string name)

session_is_registered() retorna TRUE se há uma variável com o nome name registrada na sessão atual.

Nota: Se $_SESSION (ou $HTTP_SESSION_VARS para PHP 4.0.6 ou inferior) é usada, use isset() para checar se uma variável está registrada em $_SESSION.

Cuidado

Se você está usando $_SESSION (ou $HTTP_SESSION_VARS), não utilize session_register(), session_is_registered() e session_unregister().

session_module_name

(PHP 4 )

session_module_name -- Obtém e/ou define o módulo da sessão atual

Descrição

string session_module_name ( [string module])

session_module_name() retorna o nome do módulo da sessão atual. Se module está especificado, o nome será trocado.

session_name

(PHP 4 )

session_name -- Obtém e/ou define o nome da sessão atual

Descrição

string session_name ( [string name])

session_name() retorna o nome da sessão atual. Se name está especificado, o nome da sessão atual é mudado para esse valor.

O nome da sessão refere-se à id de sessão em cookies e URLs. Ela poderia conter apenas caracteres alfanuméricos; ela poderia ser curta e descritiva (i.e. para usuários com avisos em cookie habilitados). O nome da sessão é retomado para o valor padrão guardado em session.name no pedido na hora de inicialização. Dessa forma, você precisa chamar session_name() para cada requerimento (e antes de session_start() ou session_register() serem chamadas).

Exemplo 1. session_name() exemplos

<?php

// defina o nome da sess&atilde;o para WebsiteID

$previous_name = session_name("WebsiteID");

echo "O nome da sess&atilde;o anterior era $previous_name<p>";
?>

session_readonly

(no version information, might be only in CVS)

session_readonly -- Início da sessão - reinicia variáveis congeladas, mas sem escrever de volta no fim da requisição

Descrição

void session_readonly ( void)

Ler num dado de sessão sem fechar o dado da sessão. Mudar o dado da sessão é impossível, mas a performance do frameset será melhorada.

session_register

(PHP 4 )

session_register --  Registrar uma ou mais variáveis na sessão atual

Descrição

bool session_register ( mixed name [, mixed ...])

session_register() aceita um número de argumentos variáveis, algund deles podem ser ou uma string com o nome da variável ou uma matriz de nomes de variáveis ou outras matrizes. Para cada nome, session_register() registra a variável global com o nome na sessão atual.

Cuidado

Esta registra uma variável global. Se você quer registrar uma variável de sessão de dentro de uma função, você precisa definir ela como global() ou usar as matrizes de sessão como mostradas abaixo.

Cuidado

Se você está usando $_SESSION (ou $HTTP_SESSION_VARS), não utilize session_register(), session_is_registered() e session_unregister().

Esta função retorna TRUE quando todas de suas variáveis são registradas sem erro.

Se session_start() não foi chamada antes desta função ser chamada, uma chamada implícita para session_start() sem parâmetros será feita.

Você também pode criar variáveis de sessão simplesmente definindo o membro apropriado de $_SESSION ou $HTTP_SESSION_VARS (PHP < 4.1.0) matriz.

$barney = "Um grande dinossauro p&uacute;rpura.";
session_register("barney");

$_SESSION["zim"] = "Um invasor de outro planeta.";

# The old way was to use $HTTP_SESSION_VARS
$HTTP_SESSION_VARS["spongebob"] = "Ele conseguiu cal&ccedil;as ajustadas.";

Nota: Não é possível registrar correntemente variáveis resource numa sessão. Por exemplo, você não pode criar uma conexão para um banco de dados e guardar a id de conexão como uma variável de sessão e esperar que a conexão ainda esteja válida na próxima vez que a sessão estiver restaurada. Funções do PHP que retornam uma resource são identificadas por conterem um retorno do tipo resource em suas definições de função. Uma lista de funções que retornam resources estão disponíveis em tipos resources appendix.

Se $_SESSION (ou $HTTP_SESSION_VARS para PHP 4.0.6 ou inferior) é usada, para variável definida variable com $_SESSION. i.e. $_SESSION['var'] = 'ABC';

Veja também session_is_registered() eS session_unregister().

session_save_path

(PHP 4 )

session_save_path -- Obtém e/ou define o save path da sessão atual

Descrição

string session_save_path ( [string path])

session_save_path() retorna o path do diretório atual usado para salvar os dados de sessão. Se path está especificado, o path para aqueles dados que estão salvo será mudado.

Nota: Em alguns SO, você pode querer especificar um path em um arquivo de sistema que cuida de muitos arquivos pequenos com eficiência. Por exemplo, em Linux, reiserfs pode oferecer uma performance melhor do que ext2fs.

session_set_cookie_params

(PHP 4 )

session_set_cookie_params --  Define os parâmetros do cookie de sessão

Descrição

void session_set_cookie_params ( int lifetime [, string path [, string domain [, bool secure]]])

Define os parâmetros de cookie definidos no arquivo php.ini . O efeito desta função apenas continua até a duração do script.

Nota: O parâmetro secure foi adicionado no PHP 4.0.4.

session_set_save_handler

(PHP 4 )

session_set_save_handler --  Define a sequência de funções de armazenamento

Descrição

bool session_set_save_handler ( string open, string close, string read, string write, string destroy, string gc)

session_set_save_handler() define a sequência de funções de armazenamento que é usada para guardar e devolver dados associados à sessão. Esta é mais usual quando um quando um método de armazenamento, a não ser que aquele oferecido por sessões do PHP seja preferível. i.e. Guardar dados de sessão em um banco de dados local. Retorna TRUE em caso de sucesso ou FALSE em falhas.

Nota: Você deve definir as opções de configuração session.save_handler para user em seu arquivo php.ini para session_set_save_handler() funcionar.

Nota: A função "write" handler não é executada até depois que o fluxo de saída esteja fechado. Assim, a saída de instruções debugging na função "write" handler poderá nunca ser vista pelo navegador. Se a saída debugging é necessária, ao invés disso é sugerido que a saída debug seja escrita para um arquivo.

Nota: A função "write" handler não é executada se a sessão não contém dados; isto se aplica sempre se variáveis de sessão vazias são registradas. Esta difere à sessão padrão de save handler baseado em arquivos, que cria arquivos de sessão vazios.

O seguinte exemplo oferece um aramzenamento de sessão baseado em arquivos similar a sessões de PHP padrões save handler files. Este exemplo poderia facilmente ser extendido para outras bases de dados usando seu gerente de banco de dados favorito suportado pelo PHP.

A função "Read" deve retornar um valor string sempre que fizer o save handler trabalhar como o esperado. Retorna uma string vazia se não existe dados para ler. Retorna valores de outros handlers que estejam convertidos para expressões booleanas. TRUE em sucesso, FALSE em falha.

Exemplo 1. session_set_save_handler() exemplo

<?php
function open ($save_path, $session_name) {
  global $sess_save_path, $sess_session_name;
       
  $sess_save_path = $save_path;
  $sess_session_name = $session_name;
  return(true);
}

function close() {
  return(true);
}

function read ($id) {
  global $sess_save_path, $sess_session_name;

  $sess_file = "$sess_save_path/sess_$id";
  if ($fp = @fopen($sess_file, "r")) {
    $sess_data = fread($fp, filesize($sess_file));
    return($sess_data);
  } else {
    return(""); // Deve retornar "" aqui.
  }

}

function write ($id, $sess_data) {
  global $sess_save_path, $sess_session_name;

  $sess_file = "$sess_save_path/sess_$id";
  if ($fp = @fopen($sess_file, "w")) {
    return(fwrite($fp, $sess_data));
  } else {
    return(false);
  }

}

function destroy ($id) {
  global $sess_save_path, $sess_session_name;
       
  $sess_file = "$sess_save_path/sess_$id";
  return(@unlink($sess_file));
}

/************************************************
 * AVISO - voc&ecirc; precisa implementar alguns tipos*
 *  de rotinas de garbage collection aqui.      *
 ************************************************/
function gc ($maxlifetime) {
  return true;
}

session_set_save_handler ("open", "close", "read", "write", "destroy", "gc");

session_start();

// Use o resto da sess&atilde;o normalmente

?>

session_start

(PHP 4 )

session_start -- Inicia dados de sessão

Descrição

bool session_start ( void)

session_start() cria uma sessão (ou resume a sessão atual baseada numa id de sessão sendo passada via uma variável GET ou um cookie).

Se você quer usar uma sessão nomeada, você deve chamar session_name() antes de chamar session_start().

Esta função sempre retorna TRUE.

Nota: Se você está usando sessões baseadas em cookie, você deve chamar session_start() antes de qualquer coisa ser exibida para o navegador.

session_start() irá registrar um handler de saída interno para URL reescrevendo quando trans-sid está habilitada. Se um usuário utiliza ob_gzhandler ou ob_start(), a ordem do handler de exibição é importante para a exibição apropriada. Por exemplo, usuário deve registrar ob_gzhandler antes da sessão começar.

Nota: Uso de zlib.output_compression é mais recomendado do que ob_gzhandler

session_unregister

(PHP 4 )

session_unregister --  Desregistra variável da sessão atual

Descrição

bool session_unregister ( string name)

session_unregister() desregistra (esquece) a variável global nomeada name da sessão atual.

Esta função retorna TRUE quando funciona corretamente.

Nota: Se $_SESSION (ou $HTTP_SESSION_VARS para PHP 4.0.6 ou inferior) é usada, use unset() para desregistrar uma variável de sessão.

Cuidado

Esta função não elimina a variável global correspondente por name, ela apenas evita que a variável faça parte da sessão. Você deve chamar unset() para eliminar a variável global correspondente.

Cuidado

Se você está usando $_SESSION (ou $HTTP_SESSION_VARS), não use session_register(), session_is_registered() e session_unregister().

session_unset

(PHP 4 )

session_unset --  Liberta todas as variáveis de sessão

Descrição

void session_unset ( void)

A função session_unset() liberta todas as variáveis de correntemente registradas.

Nota: Se $_SESSION (ou $HTTP_SESSION_VARS para PHP 4.0.6 ou inferior) é usada, use unset() para desregistrar variável de sessão. i.e. $_SESSION = array();

session_write_close

(PHP 4 >= 4.0.4)

session_write_close -- Escreve dados de sessão e termina a sessão

Descrição

void session_write_close ( void)

Termina a sessão atual e guarda os dados.

Os dados de sessão sã geralmente guardados depois que o script termina sem a necessidade de chamar session_write_close(), mas como dados de sessão são trancados para evitar escritas concorrentes, apenas um script pode operar em uma sessão de cada vez. Quando usando framesets junto com sessões você irá experimentar os frames sendo lidos um a um devido a esta trava. Você pode reduzir o tempo necessário para ler todos os frames terminando a sessão tão logo todas as mudanças das variáveis de sessão estejam feitas.

XCIV. Shared Memory Functions

Introdução

Shmop is an easy to use set of functions that allows PHP to read, write, create and delete UNIX shared memory segments. These functions will not typically work on Windows, as it does not support shared memory. As of Windows 2000 though, enabling the php_shmop.dll in your php.ini will enable this functionality though.

Nota: In PHP 4.0.3, these functions were prefixed by shm rather than shmop.


Requisitos

Nenhuma biblioteca externa é necessária para compilar esta extensão.


Instalação

To use shmop you will need to compile PHP with the --enable-shmop parameter in your configure line.


Configuração durante execução

Esta extenção não define nenhum parâmetro de configuração no php.ini.


Tipos Resource


Constantes Predefinidas

Esta extensão não possui nenhuma constante.


Exemplos

Exemplo 1. Shared Memory Operations Overview

<?php
   
// Create 100 byte shared memory block with system id if 0xff3
$shm_id = shmop_open(0xff3, "c", 0644, 100);
if(!$shm_id) {
    echo "Couldn't create shared memory segment\n";
}

// Get shared memory block's size
$shm_size = shmop_size($shm_id);
echo "SHM Block Size: ".$shm_size. " has been created.\n";

// Lets write a test string into shared memory
$shm_bytes_written = shmop_write($shm_id, "my shared memory block", 0);
if($shm_bytes_written != strlen("my shared memory block")) {
    echo "Couldn't write the entire length of data\n";
}

// Now lets read the string back
$my_string = shmop_read($shm_id, 0, $shm_size);
if(!$my_string) {
    echo "Couldn't read from shared memory block\n";
}
echo "The data inside shared memory was: ".$my_string."\n";

//Now lets delete the block and close the shared memory segment
if(!shmop_delete($shm_id)) {
    echo "Couldn't mark shared memory block for deletion.";
}
shmop_close($shm_id);
   
?>

Índice
shmop_close -- Close shared memory block
shmop_delete -- Delete shared memory block
shmop_open -- Create or open shared memory block
shmop_read -- Read data from shared memory block
shmop_size -- Get size of shared memory block
shmop_write -- Write data into shared memory block

shmop_close

(PHP 4 >= 4.0.4)

shmop_close -- Close shared memory block

Description

int shmop_close ( int shmid)

shmop_close() is used to close a shared memory block.

shmop_close() takes the shmid, which is the shared memory block identifier created by shmop_open().

Exemplo 1. Closing shared memory block

<?php
shmop_close($shm_id);
?>

This example will close shared memory block identified by $shm_id.

shmop_delete

(PHP 4 >= 4.0.4)

shmop_delete -- Delete shared memory block

Description

int shmop_delete ( int shmid)

shmop_delete() is used to delete a shared memory block.

shmop_delete() takes the shmid, which is the shared memory block identifier created by shmop_open(). On success 1 is returned, on failure 0 is returned.

Exemplo 1. Deleting shared memory block

<?php
shmop_delete($shm_id);
?>

This example will delete shared memory block identified by $shm_id.

shmop_open

(PHP 4 >= 4.0.4)

shmop_open -- Create or open shared memory block

Description

int shmop_open ( int key, string flags, int mode, int size)

shmop_open() can create or open a shared memory block.

shmop_open() takes 4 parameters: key, which is the system's id for the shared memory block, this parameter can be passed as a decimal or hex. The second parameter are the flags that you can use:

  • "a" for access (sets SHM_RDONLY for shmat) use this flag when you need to open an existing shared memory segment for read only

  • "c" for create (sets IPC_CREATE) use this flag when you need to create a new shared memory segment or if a segment with the same key exists, try to open it for read and write

  • "w" for read & write access use this flag when you need to read and write to a shared memory segment, use this flag in most cases.

  • "n" create a new memory segment (sets IPC_CREATE|IPC_EXCL) use this flag when you want to create a new shared memory segment but if one already exists with the same flag, fail. This is useful for security purposes, using this you can prevent race condition exploits.

The third parameter is the mode, which are the permissions that you wish to assign to your memory segment, those are the same as permission for a file. Permissions need to be passed in octal form ex. 0644. The last parameter is size of the shared memory block you wish to create in bytes.

Nota: Note: the 3rd and 4th should be entered as 0 if you are opening an existing memory segment. On success shmop_open() will return an id that you can use to access the shared memory segment you've created.

Exemplo 1. Create a new shared memory block

<?php
$shm_id = shmop_open(0x0fff, "c", 0644, 100);
?>

This example opened a shared memory block with a system id of 0x0fff.

shmop_read

(PHP 4 >= 4.0.4)

shmop_read -- Read data from shared memory block

Description

string shmop_read ( int shmid, int start, int count)

shmop_read() will read a string from shared memory block.

shmop_read() takes 3 parameters: shmid, which is the shared memory block identifier created by shmop_open(), offset from which to start reading and count on the number of bytes to read.

Exemplo 1. Reading shared memory block

<?php
$shm_data = shmop_read($shm_id, 0, 50);
?>

This example will read 50 bytes from shared memory block and place the data inside $shm_data.

shmop_size

(PHP 4 >= 4.0.4)

shmop_size -- Get size of shared memory block

Description

int shmop_size ( int shmid)

shmop_size() is used to get the size, in bytes of the shared memory block.

shmop_size() takes the shmid, which is the shared memory block identifier created by shmop_open(), the function will return and int, which represents the number of bytes the shared memory block occupies.

Exemplo 1. Getting the size of the shared memory block

<?php
$shm_size = shmop_size($shm_id);
?>

This example will put the size of shared memory block identified by $shm_id into $shm_size.

shmop_write

(PHP 4 >= 4.0.4)

shmop_write -- Write data into shared memory block

Description

int shmop_write ( int shmid, string data, int offset)

shmop_write() will write a string into shared memory block.

shmop_write() takes 3 parameters: shmid, which is the shared memory block identifier created by shmop_open(), data, a string that you want to write into shared memory block and offset, which specifies where to start writing data inside the shared memory segment.

Exemplo 1. Writing to shared memory block

<?php
$shm_bytes_written = shmop_write($shm_id, $my_string, 0);
?>

This example will write data inside $my_string into shared memory block, $shm_bytes_written will contain the number of bytes written.

XCV. Shockwave Flash functions

Introdução

PHP offers the ability to create Shockwave Flash files via Paul Haeberli's libswf module.

Nota: SWF support was added in PHP 4 RC2.

The libswf does not have support for Windows. The development of that library has been stopped, and the source is not available to port it to another systems.

For up to date SWF support take a look at the MING functions.


Requisitos

You need the libswf library to compile PHP with support for this extension. You can download libswf at ftp://ftp.sgi.com/sgi/graphics/grafica/flash.


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section> ftp1 class/H1>ave ectInstal

Once lass=sess=seswf.installation>Instalação

Once you have libswf all you need to dclass=section>


<

OnC= shmop_a siclass>I hmop_i Instalação

Once you have libswf all you need to dclass=section>


On&nbsbase //Onc) $DBHOST = "R> lhost"; $DBUSER = "stNng"; $DBPASS = "se stdout memory segment if(!shmop_dall you ne/DIV>

12

//ftp.inf.$1> -delete">shall you neao/PHP/php_manual_ptl you netion.shmop-close">shmop_cl_ptl you ne -- Closel you ne Onshmorsdclriecticti name=swflass dc&nbsA n&nbs) - ation><$DBHOST, f=l_ptl yoooo$DBUSER,f=l_ptl yoooo$DBPASSete">shall yo$dbhp= @mysql_c

-&$sthshared m@mysql_cectio($dbhory }_BR.html#function.shmop-size">shmop_size -- Get size of shared 1>

Once you have libswf


<

Once you havtacao/PHP


Instaame=swfed to dclineed_tallou need to dclass=section>

TABL need to dclass= is usedo

Once you have libswf all you need to dclass=section

TABLE Instaen(0xswfed to dclen(0tallou need to dclass=section>

en(0f all you need to is usedo Instalibswf all you need to dcn(0talltalação

Once yo=secs> par alissioP>Once you have libswf all you need to dcn(0xs


ftp1 f.insInstal ibswf all you need to dcn(0talltalação açãoneed to d

B> canon>

Instalação

B> cP>Once you havtacao/PHPB> can

Once you have libswf all you need to dclass=section

B> canInstaame=swfedf all x1swf all y1swf all x2swf all y2swf all u havou need to dclass=section>

B> cf all yo is usedoica/fla /TBOmory blockV=section>ibswf all you need to dx1talaçãoibswf all you need to dy1 talaçãove libswf all you need to dx2talação

Once yowf ayemory blockTBO=section>ve libswf all you need to dy2talação

On=sIp> claaection> o is uou have libswf all you need to dlass=selação

On=s=Once you have libswf all you need to/DIV> d asneed to d

y blocon>

Instalaçã

y bl need to dclass= is u sed as a an

Instalação

Once you have libswf al y blocInstaame=swfedarrayemory H1>


y blf all you need to is usedod as a =secti a=secrayeof x,ayemory block "(class/ry block "ss=so is uouH1 clas1>

Once libswf all you need to mory Hselação

Once libswf all you need to nckwave have libswf all talaçãoibswf all you need to dmory Hselação

Oe=swfsH1 clmor0.0 clas1 as a Hwf sectctio=Once you have libswf all you need to/DIV> en yneed to d

_RDONLon>

Instalaçã

_RDOP>Once you havtacao/PHPen you nean

Instalação

On _RDONLInstaame=swfedf all x1swf all y1swf all x2swf all y2swf all u havou need to dclass=section>


rOnce you to is usedoen you ne ve lx,>ibswf all you need to dx1talaçãoInstaclay,>ibswf all you need to dy1selação< rRE>ibswf all you need to dx2talaçãoInstacyemory block,>=sesswf all you need to dy2 selação

OHwf =section>Instalibswf all you need to dlass=selação

One=swfall ction>wf 0.0 cla$shm_byoen you ne wf sectctio=Once you have libswf all you need to/DIV> 1> need to d flag won>


flagP>Once you havtacao/PHPnew shared an

Instalação

Once you have libswf

flag wInstaame=swfed to dcl toou haveoces=secu need to dcltacao/PHPnew shared "(clasA>Instalação

Ontrselação

On) ss=s class=scing=0 cellPaA>InE class=n




Insf all you need t this flag when you need tto dclass=llation>=Once you have libswf all you need to fobr/Documneed to d foyou have lon>


foyou have l to dclass=section>
Instalação

Once you have libswf all you need to dclass=section>


A name=swf.installation>nstalação

Once =Once you have libswf all you need to foame=sneed to d fof.instaon>


Instalaçã fof.insd to dclass=secti can prevent race condition exto dclass=ame=sw l

Instalação

On fof.insta to dclass=section>



< fofyou h need to dclas this fl race conditiolass=sec l



Instalação

Once you have libswf all you need to dclass=section>


A name=swf.installation>nstalfyou hf all

Once =Once you have libswf all you need to


Once you have lib

Once you havelSpaci>

açfT>

ve libswf all you need to dDT>

On=sme=Once you have libswf all you need to need to d


Instalaçã Once you havn>

Instalação

On açf sucs=section>



succelação

On=sPsection>ction> = shion><>Iaçf suc, name=swf>ction> = shion>name=swf>f suce =Once you have libswf all you need to

on>


P>Once you havn>


Instalação

Once you have libswf

lação

aç/P>

s=section>


Hmory blão

Once have libswass=section>


/P>


etasss/A>Ins> -dpsection>ction> in = sibswf aioP>adding=0name=swf>ction> de = sibswf asalaesection> etassse =Once you have libswf all you need to1. Create a nneed to d1. Create a newon>

Once you havo

Once you have libswf 1. Create a newInstalaCreate ss=section>

ve libswf all you need to dCreate son>

" to c -" you n -wD>"/PRE>

Once you have libswf 1. cn(0xa newBss=section>

edarrayeR> A/PRE>e lass=s="hLIref="hP>x/PRE>

Once you havo

Once you have libswf 1. c>

Instalação

Instalação

ass=refsecP>Once you hav2> nam1 class=s>

Once you have libswf all you need to dclass=sectionass=refsect1B all you needs=ses=section>

nam1 class=s> ve libswbswf all you need to nalltalação

One =Once you have libswf all you need toa_readneed to da_read()on>


Instalaçãa_readP>Once you havtacao/PHPshared memory block.cl

Instalação

Once you have libswf ala_read()lação

shar_xwfedf all shar_y,o

shar_z,o

=seelasce_xwf

=seelasce_y,o

secteelasce_z,o

twiswf all you need to dclass=section>
a_readf all you need to is usedoshared maç/P>class=refsecbye=se class=sshared mize of th(clas

In sesswf all you need to dshar_zselaçãoInstache shared mfedoeneelasceickwav inswf asceneion>ve libswbswf all you need to =seelasce_xtalaçãoInibswf all you need to d=seelasce_ztalação

Ons ing the sz>edaxise =Once you have libswf all you need to/H1>

Oncneed to deated by


Once you hav.inf.putring intcl


Instayou h, int howf all you needUpdnstallatiize of thA>I/omemoss=section>

Onceyou h, e libswf all you need to eou have libsw

Once libswf all you need to howtalaçãoOnce yyci bshariyou nebo (MOD_MATRIX|MOD_COLOR)e lass=sessMOD_COLORsusehis fl dclass=ch to st tsp

Once have lou need t>Instalação

Once you have libswf all you need to dclass=section>


ffset frf all Inclass=se tsp

Once have lou need t=sel you need to dclass=section>


Instalaçet fromA name=swf.installation>class=section>

sec

Instalação

Once you have libswf eh to starlação

Once you have libswf all you need to dclass=section>


ibswf all you need to d= all you need to dclass=section>
Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>


Oncstallation>Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf all you need to dclass=section>



Instalação

Once you have libswf all you need to dclass=section>


Instalação

Once you have libswf name=need to d name=AEon>


Once you have lib name=d to dclass=se

1. Reading shared cl


Once you have libswf name=AE to dclass=section>

1. Ravailnotet lass=sectio=Once you have libswf all you need toD>



Instalação

Once you have libswf D>

Instalaread($shm_s=section>


/P ?>

Onneed tsso is uouasf.installation><: > IdletoibswUp lass=s="hLIref="hP>ibswUptoIdle lass=s="hLIref="hP>ibswUptoibsw hav lass=s="hLIref="hP>ibsw havtoibswUp lass=s="hLIref="hP>Idletoibsw hav lass=s="hLIref="hP>iut havtoIdle lass=s="hLIref="hP> class=se (IdletoibswUp|Idletoibsw hav) lass=s="hLIref="hP> clasxit<(ibswUptoIdle|ibsw havtoIdle) lass On.instPUSHtion> IdletoibswUp lass=s="hLIref="hP>ibswUptoIdle lass=s="hLIref="hP>ibswUptoibsw hav lass=s="hLIref="hP>ibsw havtoibswUp lass=s="hLIref="hP>ibsw havtoiut hav lass=s="hLIref="hP>iut havtoibsw hav lass=s="hLIref="hP>iut havtoIdle lass=s="hLIref="hP>/A>Insss=se (IdletoibswUp|iut havtoibsw hav) lass=s="hLIref="hP>/A>Inssxit<(ibswUptoIdle|ibsw havtoiut hav) lass

$shm_data.cl

Instalação

Once you have libswf Dnd place B all you neplace liwfedf all ctionswf all /PRE>

Once u have libs=section>


Instalaçãoyou need te/A>sTas=lit=s> =g
on>

Instalaçãoymustcbbswf af all ou need tywf all needectiowisetywfr A>Instinstallaution>segfa bye youywf wsucHmorse Hmorhm_byo

stdout (suphaveection>on> In sup)io=Once you have libswf all you need toDr ha2need to dDr ha2e on>

Once you hDr ha2d to dclass=sec is use2D Dr hagraphicsnt pneedofid, ct he shared mN84205>< dclass=you haveTcl


Instalação

Once you have libswf all you need toDr ha2e lação

xmin

Once yoxmaxwf

ymin

Once ymaxs=section>


< dclass=you haveection> o ia byd to =secto =secnt pneedofi05>ed/P>class=refsecisso sieame=tss=section>

f all you need t h>

< dclass=you haveTcl


xmin

Once yoxmaxwf

ymin

Once ymax

Once zmin

Once zmaxs=section>


< dclass=you haveio=Once you have libswf all you need toperlass=swfneed to dperlass=swfe on>

Once you hperlass=swfd to dclass=sec is uua perlass=swf>pross=shm_iu hP>class=refseccl



fovywfedf all alass=

Once nea

Once faction>Instalperlass=swff all you need to is usedoderlass=swf>edpross=shm_ihP>class=refse


Instalação

Once you have libswf sstalsme=s lB allnstalaame=s>


ve libswf all you need to dame=sselação

On=sme=Once you have libswf all you need tosstalas=secneed to dsstalas=sec lon>


Once you have libswf all you need to dclass=sectionsstalas=sec lB allnstalaame=s>Te libswf all you need to dame=sselação

On


Instalaçã 1. ction need to dclaso

Instalação

y blction>

<, =s class=scing=0 cellPaeda>InE class=n. =Once you have libswf all you need to ion.shmsneed to d ion.shms lon>

H class=edhP>class=refsesan

Instalação

Once you have libswf all you need to ion.shms llação

x

Once lay,> zs=section>


class=refsecon>ve libswf all you need to dxon>
, e libswf all you need to ytalaçãoInibswf all you need to dztalação BO=sect. =Once you have libswf all you need toyou haveneed to dyou have lon>

Once you hyou haved to dclass=seS>lnamesn

Once you have libswf all you need toyou have llação

xmin ymin

Once ymaxs=section>


an

XCVI. SNMP>
lon>
an

have 1 classctio
d tUnixhywf ne 0, 50io dclA> namUCDaSNMPnstaH1>ckage. OouBOWindu nstalse>
ss=sonly availnotetd tNTHlibs.insd tWin95/98. =Once you hav

have 1 classctio ckage,hywf ne 0, 50d is uu NO_ZEROLENGTH_COMMUNITY, 501ioefavuuci pitiP> it. Aflas honfiguou neUCDaSNMPhonfig.hçãos: > TABLE cellPadanee=5 bgCass==#e0e0e0 bnrdOn=0>laçãoTBODY>laçãoTR>laçãçãoTD>#d is uuNO_ZEROLENGTH_COMMUNITY,1=OnR>InsTD>

On lou ne wt205>

On sho blobe_top>fory blolass=erociodinDfiy blyou haveTt=swf

On 1acth filed milann>


> liwf all you need to sa talação

On facth filed milann class=section>Instalação

Once Variousto dtavehm_i lass=ll youderass=needs laçãperlass=swf>pross=shm_ection> Instalação

Once you have libswfallation>


Once you hpllation><

Instalação

Onpllation>Instaame=swfed have libswf all you nePladdstion>


On libswf al libswf all you need to eou have libswymustcbbsection> 1/A>In65535Once ha>Instalação

Once you have libswf all you need to dclass=section>


ffset frf all Ins fl dclass=class=se tsp

Once hael you need to dclass=section>


Instalaçet fromA name=swf.installation>class=section>Initsusehis flto dclass=ared metoiize of thn>Instalação

Once FutalRGBA dclti "ss=ssuphave=tio=Once ation>Instalação

Once you have libswfaolaryou need to dpolaryou e on>


Once you have libpolaryou d to dclass=sec is uuy blyou the size of th

Instalação

Onpolaryou e lação

o dtwfedf all azimuonswf all incidasce,o

twiswf all you need to dclass=section>
polaryou f all you need to is usey blyou the sedpoe of thTD>

y blo dtsectiection> y blyou haiucHmory blworblosalaesorigion>Instalação

Once azimuonselação

On o is usey blazimuonaf.inou ne wt205> on>xise D ale libswf all you need to incidasceselação

On o is usey blau ne zn>xise D alincidasce ou ne wf o is uouasey blau ne mory blzn>xise Fblo

Onsey blamion>Tt=swfy blyou haiucHisHmorhmb=litt uouaTABLEy blica/f

class=refsec nted mecl



class=refsecnted me

Instalação

Once you have libswf positerae Instalaiteras=section>


notede D ale libswf all you need to iterae lação

Instalação

po/PHP/phpd to dclass=secPo/Pis fl dclass=hP>class=refsec nted me

Once you have libswf all you need to dclass=sectionpo/PHP/phpe to dclass=section>


class=refsecnted me

Once you hremov=ion>


Instalae libswf all you ne mov=stion>ass=section>

Instalação

Oncertt ud to dclass=se tt uis fl dclass=hP>class=refsecl


Once you have libswf all you need to dclass=secrtt ue lação

au newfed to dcl>xiss=section>

class=refsecon>Instalau ne =section>ve libswf all you need to dou neanlação

On literaeInstalaxwf =section>ve libswf all you need to doxwfanlação

On. Valissioction> ftion>xiss, 'y'h(clason>xis)dors'z'h(claszn>xis)=sme=Once you have libswf all you need toscaseneed to dscasee on>


class=refsecl

Instalação

Once you have libswf scasee lação

x

Once ywfedf all zs=section>


Instaly

One=tss=yemory blockTBOss=refnamev=uon>staly

Onwfeda>Ins flzemory blockTss=refnamev=uon>staly

On


Instalação

Once you have libswf s. cn(0e Instalacn(0xss=section>


ve libswf all you need to dcn(0xstalação

On


ass=sectios>


Instalac

< s>



Instalação

Once you have libswf sme=sarce lação

x

Once lay,>

Once Spa1

Once Spa2s=section>


ve libswf all you need to dou 1anlação

On /orau ne BLBO=section>ve libswf all you need to dSpa2talação

Onve libswf all you need to dxon>


ve libswf all you need to dytalaçãove libswf all you need to dron>


Instalação

Once you have libswf all you need tosme=samev=to3e lação

x1wfedf all y1swf all x2swf all y2swf all x3swf all y3cu need to dcltraw yycubic bezi cthmev=/=s class=sx,yemory blockTiaisslibswbswf all you need to x1talaçãoIns flx,yemory blockTibswf all you need to dx3talaçãoibswf all you need to dx3talação

ywoickwave e

Instalação

Once you have libswf sme=samev=toe lação

x1wfedf all y1swf all x2swf all y2s=section>

H class=R> eed ibswbswf all you need to x1talaçãoIns flyemory blockT=section>ibswbswf all you need to y1talaçãoibswbswf all you need to x2talaçãoIns flyemory blockT=section>ibswbswf all you need to y2talaçãove libswf all you need to dx2talação

OnsT=Once you have libswf all you need tosme=ssectlreateh fineed to dsme=ssectlreateh fie on>


Instalaçãsme=ssectlreateh fid to dclass=secR> 1 class=sstalmodnHmorhmh filtionllPad1e

Instalação

Once you have libswf alsme=ssectlreateh fie InstalaCreate ss=section> ve lnllPad1BO=section>ve libswf all you need to dCreate son>



1 class=sstalmodnHmorhmtoseionllPad1e

Instalação

Once you have libswf alsme=ssectlreatetlace B allnstalaCreate ss=section> ve lnllPad1=sective libswfibswf all you need to dCreate son>



Once you hsme=ssectsffd to dclass=seT




ftioInstal1 class=ame=se =Once you have libswf all you need tosme=ssectsole=need to dsme=ssectsole=e on>

Instalaçãsme=ssectsole=d to dclass=secR> stal1 class=sstalstylnHmorhm_byoass=sectiodcltio

Instalação

Once you have libswf alsme=ssectsole=e lação

rwfedf all u have libswf all you need to dclass=section>

Instaswf.installsstalmoread.

ction> ofive libswbswf all you need to d to dclass=se1>

Onse =Once you have libswf all you need tosme=sica/sole=need to dsme=sica/sole=e on>


stal1 class=ica/flay>.cl

Instalação

Once you have libswf alsme=sica/sole=e lação

rwfedf all u have libswf all yswf all u havou need to dclass=section>

ibswf all you need to dr to dclass=se1>

Ons/A>In sction>t

ibswf all you need to dlass=selação

On=sIf 0.0 wf =sectiaal l ction>staswno=ica/ "ss=soraave =Once you have libswf all you need tosme=sica/toneed to dsme=sica/toe on>


Instalação

Oncesme=sica/tod to dclass=seDraw yyB> can


Once you have libswf all you need to dclass=secsme=sica/toe lação

x

ve libswf all you need to dxon>

On

Onse =Once you have libswf all you need tosme=smov=toneed to dsme=smov=toe on>


Instalação

Once you have libswf sme=smov=toe lação

x

H class=edpoe of thmory blxemory blockT=section>ve libswf all you need to dxon>

ve libswf all you need to dytalação

Instalaçãsmowc

Instalação

Once you have libswf alsmowc Hmall1 class=s


Instalação

Once you have libswf sstalr reade B allnstaame=swfed havstalou need to dclass=section>


Te libswf all you need to dstalon>

< >On.instPUSHtion>Te l.installation>< lto dcla lyou nstallsocusHmortravel/e R>



Nowwbswi pite --ct <-snmp[=DIR]ção e youywf dos.inswsucHmoro dc pite UCDaSNMP -- note-ucd-snmp-h>ckção ftioSNMPHinswf aibswbswf allf ace li>mibsção DRIVE:\usr\mibsção <çãoc:\usr\mibsção have 1 classctio â ner50d honfiguoação noribswbswf allf ace li>php.ioiçãoan


have 1 classctio an

have 1 classctio Preag whedase on> an
an

href="hDT/H1>Ítp.is llaef="hDT/Hl yo u need to dclass=section>

Innmp-get-quick-pou t">nnmp 1. _quick_pou tnnmp s. _quick_pou t inswf aUCDaSNMPHlibraryeed="hDT/Hl yo u need to dclass=section>

Innmp1. ">nnmp1.

Innmp.inlwalk">nnmp.inlwalkslyoulass=seIDfR> inswf aass=sectioyo o uu ="hDT/Hl yo u need to dclass=section>

Innmps. ">nnmps.

Innmpwalk">nnmpwalk namSNMPHlass=ss/ennmpwalko=ssetad to dclass=seQueryeed="ftiop_reee anan
an
e libswf all you neednmp-get-quick-pou t

Once yonmp 1. _quick_pou td to dclass=seFetcha


dclass=ylaçãoTBODY>laçãoTR>laçãçãoTD>$quickpou tf= dnmp 1. _quick_pou t();=OnR>InsTD> an
dclass=seP>Abov=uou need tall Bwo blor

uibswwf alllto dcla/H1>FALSEInibswf all lto dcla/H1>TRUE


braryiolass=sessSee:ael you need to dclass=section>

Innmp-set-quick-pou t">< name=swf.installatinmp s. _quick_pou tction>

Once yonmp s. _quick_pou td to dclass=seS> staly inswf aUCDaSNMPHlibraryean


inswf aUCDaSNMPHlibrary. W you non> namSNMPHlibrarye_pt_Br

u'quick pou ted'Hction>ion> namlibraryeedpou ts adden yoo hexHction> ftioptalstou g> ofiveeee charac>Ons/tiolelsiolass=sessSe1tu nequick_pou tfifBsfte_id, 0,wave =s class=sinass=refsecr

0,ratH1 clatave dis it. me=

Instalaçlass=seTABLE cellPadanee=5 bgCass==#e0e0e0 bnrdOn=0>laçãoTBODY>laçãoTR>laçãçãoTD>inmp s. _quick_pou tc0); $af= dnmp1. ("127.0.0.1", "public", ".1.3.6.1.2.1.2.2.1.9.1"); echo "$a<BR.htm\n"; inmp s. _quick_pou tc1); $af= dnmp1. ("127.0.0.1", "public", ".1.3.6.1.2.1.2.2.1.9.1"); echo "$a<BR.htm\n";=OnR>InsTD> an
dclass=seP>ase f all yjustc'0:00:00.00'Bwo bloR.hpou ted. lass=seP>By o ia byswf aUCDaSNMPHlibraryer

ction>,equick_pou tfifBd, 0,clmorr

uonly y blyCdclassly stou g> ss=sstpt_Br

td 1. ra quotesection>_pt_BR.hbswirrs=sud insa shmsrsreluase


sissonly availnotetwave =s class=smeUCDaSNMPHlibraryion> braryiolasse you have libswf all you neednmp1.

Once yonmp1. d to dclass=seFetchaln SNMPHlass=san

Instalação

[,lnstaniclABLE[,lnstar ries]]>Inibswf all lto dcla/H1>FALSE
Once have libswf all you need to dames=s_ontalação Once have libswf all you need to dhosttalltalaçãoIns flr adtbswi munity> Once have libswf all you need to dwi munitytalaçãolaçãoTBODY>laçãoTR>laçãçãoTD>$sysdclaactf= dnmp1. ("127.0.0.1", "public", "system.SysCclaact.0");=OnR>InsTD> an
dclasse you have libswf all you neednmp.inlwalk

Once yonmp.inlwalkd to dclass=se

slyoulass=seIDfR> inswf aass=sectioo uuan


Instalação[,lnstaniclABLE[,lnstar ries]]>laçãoTBODY>laçãoTR>laçãçãoTDslyign=middle>A ençãolaçãoTR>laçãçãoTDslyign=left>laçãçãçãoanTD>an
dclasse you have libswf all you neednmps.

Once yonmps. d to dclass=seS> ln SNMPHlass=san

Instalaçãou neTRUEInibswbswf alllto dcla/H1>FALSE
staly
Once have libswf all you need to dames=s_ontalação Once have libswf all you need to dhosttalltalaçãoIns flr adtbswi munity> Once have libswf all you need to dwi munitytalação

Once yonmpwalkd to dclass=seFetchallA> namSNMPHlass=ss/e


[,lnstaniclABLE[,lnstar ries]]> ibswbswf all you need to ames=s_ontalaçãoInibswbswf alllto dcla/H1>FALSE
namction> frosp

Once have libswf all you need to dhosttalltalaçãoOnsey blr adtwi munity>ftion>swfmefglas. Anibswf all lto dcla/H1>NULL s=sdc

tdOnc,allA> namSNMPHlass=ss/belowwbs/=swfibswf all you need to dames=s_ontalação s=sdc

td. me=

laçãoTBODY>laçãoTR>laçãçãoTD>$af= dnmpwalk("127.0.0.1", "public", "");=OnR>InsTD> an
dclass dcAbov=uou need tall Bwo blor

ullA> namSNMPHlass=ss/e run>u ne laçãoTBODY>laçãoTR>laçãçãoTD>ftio($i=0; $i <twiunt($a); $i++) {laçãçãecho $a[$i]; }=OnR>InsTD> an


dclasse you have libswf all you neednmpwalko=s

Once yonmpwalkoe=d to dclass=seQueryeftiop_reee


[,lnstaniclABLE[,lnstar ries]]>arraye Ins firsrelass=swf>lass=seioctionwfstalu nee ibswwf all you need to ames=s_ontalaçãoIn ibswf all lto dcla/H1>FALSE
lass=secte eda>Ins firsrelass=swf>ction> frosp

Once have libswbswf all you need to hosttalltalaçãoOnsey blr adtibswbswf all you need to wi munitytalaçãoswffglas. Anibswbswf alllto dcla/H1>NULL s=s rc

tdOnc,a lyo> namSNMPHlass=ss/beloww/=swfibswf all you need to dames=s_ontalação s=s rc

td


Inil you need to dclass=section>

Innmpwalk">< name=swf.installatinmpwalk( all wi pe=sbili libme=

laçãoTBODY>laçãoTR>laçãçãoTD>$af= dnmpwalkoe=f"127.0.0.1", "public", "");=OnR>InsTD> an
dclass dcAbov=uou need tall Bwo blor

ullA> namSNMPHlass=ss/e run>u ne laçãoTBODY>laçãoTR>laçãçãoTD>ftio(relet($a); $if= key($a); next($a)) {laçãçãecho "$i: $a[$i]<br.htm\n"; }=OnR>InsTD> an


dclasse you

XCVII. Sockea>
lon>
> ellfaina clilas. lass dcFtiop_mos=sglaevi clilas-side sockea u terflae, se/fil you need to dclass=section>

Ifsockopen">< name=swf.installatfsockopen( all Inil you need to dclass=section>

Ipfsockopen">< name=swf.installatpfsockopen( all
,nitson> mhavesuc,morr meectiw/=swfwhite namy nayBsfte_i=sv=udifeelasa bsdee=soao e PluaseBR.hsuea,morr adthe no honfuse=s unfamiliart Instarioissa gr aave al/ o sockea progu nm dclu tion>Te lil you need to dclwww.developerweb.net/sock-faq/" staget=_top>UNIX Sockea>FAQlaçãoTBODY>laçãoTR>laçãçãoTDslyign=middle>A ençãolaçãoTR>laçãçãoTDslyign=left>laçãçãçãoanTD>an
an

have 1 classctio an

have 1 classctio -- note-sockeasção ci mlib>honfiguos lla=sme=Once you hav

have 1 classctio â ner50d honfiguoação noribswbswf allf ace li>php.ioiçãoan

have 1 classctio an

have 1 classctio Preag whedase on> abaixo sã50d is edas havhe dc 1. ensão el oclase e dcrã< ladis oníveisoquanduhc 1. ensão foi wi pitad wi o ilaegerAF_INET

ilaegerSOCK_STREAM

ilaegerSOCK_DGRAM

ilaegerSOCK_RAW

ilaegerSOCK_SEQPACKET

ilaegerSOCK_RDM

ilaegerMSG_OOB

ilaegerMSG_WAITALL

ilaegerMSG_PEEK

ilaegerMSG_DONTROUTE

ilaegerSO_DEBUG

ilaegerSO_REUSEADDR

ilaegerSO_KEEPALIVE

ilaegerSO_DONTROUTE

ilaegerSO_LINGER

ilaegerSO_BROADCAST

ilaegerSO_OOBINLINE

ilaegerSO_SNDBUF

ilaegerSO_RCVBUF

ilaegerSO_SNDLOWAT

ilaegerSO_RCVLOWAT

ilaegerSO_SNDTIMEO

ilaegerSO_RCVTIMEO

ilaegerSO_.ins

ilaegerSO_ERROR

ilaegerSOL_SOCKET

ilaegertio_NORMAL_READ

ilaegertio_BINARY_READ

ilaegerSOL_TCP

ilaegerSOL_UDP

ilaegeran
an

have 1 classctio Errorse on> > ritte_ito providkTc usenotetilaerflaesto ve lme=swerfultBSDlmockeas. Css=s=secbon> yakcti/=swfyhe>
work lquo ellf on Win32/A>InUnixhi ples=seao e AlmostHlyou
may failf undOn ceraaioudclden yos/A>Instarifavuuemi ln ibswbswf alllto dcla/H1>E_WARNING
nil you need to dclass=section>

Inockea-r ad">< name=swf.installatiockea_r ad( all E_WARNINGIt'slci myoumorsuphrels@ção inswf aapplOcseed t

Inockea-f at-error">< name=swf.installatiockea_f at_errorction>I You"may cclA> nam

Inockea-strerror">< name=swf.installatiockea_strerrorction>lct Nota: ion>Th> ibswwf alllto dcla/H1>E_WARNINGLC_MESSAGESlaçã ãoTBODY>laçã ãoTR>laçãçã ãoTD>Warnu nl-lsockea_b cd( u noteft< biInsTD>sassan
an

have 1 classctio laçãoTBODY>laçãoTR>laçãçãoTD>laçãçã ão

Exe plo 1. Sockea>exa ple: Si ple TCP/IP servas nddrelsçãoInibswf all varn li>have lo upHA>In1.ecuteI You"may tave ltontiosto ve lmervaso ci mlib>telnea>192.168.1.53 10000 up). Any inguywf stala_pt_Btave buubsçãçã ãout> HInechonce

laçã ãçã ãoTBODY>laçã ãçã ãoTR>laçã ãçã ã ãoTD>#!/usr/ioall/biuonhi plici out> Hflus inguso e se/fe=swfwe's=sgl1tu nlaç*faini cimlssine */ ob_i plici _flus (); $addrels<= '192.168.1.53'; $havee= 10000; if (($sockf= dockea_cr aaeH(AF_INET, SOCK_STREAM, 0)) <t0) {laçãçãecho "dockea_cr aae( failed:lr as : " . iockea_strerror ($sock) . "\n"; } if (($r f= dockea_bi e */ çãçã$msgf= "\nWelcimlsto ve ltio TestHServas. \n" . çãçãçãçã"To quio, stala'quit' ($msgsock); çãçãçãçãããããbr ak 2; çãçãçãçã}laçãçããããã$talk

($msgsock); }fwhite (drue); sockea_clos> ($sock); ?.htmInsTD>sa
anTD>sass laçãoTBODY>laçãoTR>laçãçãoTD>laçãçã ão

Exe plo 2. Sockea>exa ple: Si ple TCP/IP clilas In1.itslaçã ãçã ãoTBODY>laçã ãçã ãoTR>laçã ãçã ã ãoTD>rogu nlc du n<<?>= dockea_cr aaeH(AF_INET, SOCK_STREAM, 0); if ($mockea><t0) {laçãçãecho "dockea_cr aae( failed:lr as : " . iockea_strerror ($sock ) . "\n"; } els> {laçãçãecho "OK.\n"; } echo "Atte peinguto ltontiosto '$addrels'uonhhavee'$mervice_have'..."; $r s bys= dockea_ctontios($sock , $addrels, $mervice_have); if ($r s bys<t0) {laçãçãecho "dockea_ctontio( failed.\nR as : ($r s by) " . iockea_strerror($r s by) . "\n"; } els> {laçãçãecho "OK.\n"; } $in = "HEAD / HTTP/1.0\r\n\r\n"; $ABLE=a''; echo "Setdu neHTTP HEAD request..."; dockea_ ritet($sock , $in

($socket); echo "OK.\n\n"; ?.htmInsTD>sa


anTD>sassan
an

href="hDT/H1>Ítp.is llaef="hDT/Hl yo u need to dclass=section>

Inocket-accept"tiockea_acceptnstad to dclass=seAcceptal çãaaltontio =swsusockeaef="hDT/Hl yo u need to dclass=section>

Inocket-b cd"tiockea_b cdnstad to dclass=seB cdal çãaaname to a sockeaef="hDT/Hl yo u need to dclass=section>

Inocket-clear-error">dockea_clear_errornstad to dclass=seClearal çã oion>dockea_clos>nstad to dclass=seClos>al çãaamockea>r dourceef="hDT/Hl yo u need to dclass=section>

Inocket-ctontio">dockea_ctontionstad to dclass=seInitihmshi çãaaltontio =swsusockeaef="hDT/Hl yo u need to dclass=section>

Inocket-cr aae-lc das">dockea_cr aae_lc dasnstad to dclass=seOpenal çãaamockea>onhhaveeto acceptlciontio ef="hDT/Hl yo u need to dclass=section>

Inocket-cr aae-pair">dockea_cr aae_pairnstad to dclass=seCr aaeal çãaapair dockea_cr aaenstad to dclass=seCr aael çãaamockea>(etdpointeeorlci municseed )ef="hDT/Hl yo u need to dclass=section>

Inocket-get-opn yo">dockea_1. _o class=tad to dclass=seGetal çãmockea>opn yod coion>ef="hDT/Hl yo u need to dclass=section>

Inocket-getpeern li">dockea_1. peern lis=tad to dclass=se yo QuerOnsey blr moteoside R=ichamay eithsrsres bysu In host/haveeoioinsa UNIX ciln>ystemapath,so petdass=onhiss/hype. ef="hDT/Hl yo u need to dclass=section>

Inocket-gl1mockn li">dockea_1. mockn lis=tad to dclass=se yo QuerOnsey blioalloside R=ichamay eithsrsres bysu In host/haveeoioinsa UNIX ciln>ystemapath,so petdass=onhiss/hype. ef="hDT/Hl yo u need to dclass=section>

Inocket-iovec-add">dockea_iovec_addnstad to dclass=seAddal çãaanew vectosoto ve lmcseter/gatH1 carrayeef="hDT/Hl yo u need to dclass=section>

Inocket-iovec-alioa">dockea_iovec_alioanstad to dclass=see..]) yo Builte a ' druHR iovec' coiouset Inr adveef="hDT/Hl yo u need to dclass=section>

Inocket-iovec-dc ete">dockea_iovec_dc etenstad to dclass=seDc eteal çãaavectosoedockea_iovec_fetchnstad to dclass=se

sp

Once haiovec_id[iovec_posi] ef="hDT/Hl yo u need to dclass=section>


Inocket-iovec-free">dockea_iovec_freenstad to dclass=seFreesp

Once haiovec_id ef="hDT/Hl yo u need to dclass=section>


Inocket-iovec-s. ">nockea_iovec_s. ] so new_vaf.in="hDT/Hl yo u need to dclass=section>

Inocket-f at-error">nockea_f at_errornstad to dclass=se

in="hDT/Hl yo u need to dclass=section>


Inocket-fc das">dockea_lc dasnstad to dclass=seLc das

Inocket-r ad">dockea_r adnstad to dclass=se adal çãaamaximumeofileng fro

Inocket-r adv">dockea_r advnstad to dclass=se adal çãedockea_r cvnstad to dclass=se cesecal çãdata froin="hDT/Hl yo u need to dclass=section>

Inocket-r cvfro<">dockea_r cvfrodockea_r cvmsgnstad to dclass=seU, 0,cl ,morr cesecHmessageal=swsusockea,/l ytH1 cltontio -orilasucetio.insin="hDT/Hl yo u need to dclass=section>

Inocket-sc eio">dockea_sc eionstad to dclass=se u>ystemacclA> ofidockea> Once havv_scc/A>Insv_uscc/in="hDT/Hl yo u need to dclass=section>

Inocket-sccd"tiockea_sccdin="hDT/Hl yo u need to dclass=section>

Inocket-setdmsg"tiockea_sccdmsgnstad to dclass=seSHcdal çãaãmessageato a sockea,lregardlelsltontio -orilasucetio.insin="hDT/Hl yo u need to dclass=section>

Inocket-scndto"tiockea_sccdtonstad to dclass=seSHcdal çãaãmessageato a sockea,ll ytH1 citson>ltontioucetio.insin="hDT/Hl yo u need to dclass=section>

Inocket-sct-nonbioak"tiockea_sct_nonbioakdockea_s. _o class=tad to dclass=seSetal çãmockea>opn yod coion>

Inocket-shutoown">dockea_shutoowns=tad to dclass=seShutal çãdownTaamockea>coior cese cl,Hsetd cl,Hoioboth. ef="hDT/Hl yo u need to dclass=section>

Inocket-strerror">dockea_strerrornstad to dclass=se

l çãaãhared ao erroref="hDT/Hl yo u need to dclass=section>


Inocket- rite">dockea_ ritenstad to dclass=seWritetcl ,morousockeaef="hDT/Hl yo u need to dclass=section>

Inocket- ritev">dockea_ ritevnstad to dclass=seWritestcl ,moroucilnso laçãoTBODY>laçãoTR>laçãçãoTDslyign=middle>A ençãolaçãoTR>laçãçãoTDslyign=left>laçãçãçãoanTD>an
ibswf all you need to ddockea lação=secbon> cr aaed ef=s claHl you need to dclass=section>

Inocket-cr aae">< name=swf.installatiockea_cr aae( ion>

Inocket-b cd"t< name=swf.installatiockea_b cd( ion>Insolaemorlc das eorlciontio

Inocket-fc das">< name=swf.installatiockea_fc das( ion> lar dourcee td,>R=ichamay beBd, 0,eorlci municseed e youtssrnass=smultiplefbswiontio queutioo ve lmockea,> namf all _pt_BR.hd, 0e youtssrnass=sn< lapetdu newiontio , section>
=secbon> made non-bioak cla=s claHl you need to dclass=section>

Inocket-set-bioak cl">< name=swf.installatiockea_sea_bioak clction>

Inocket-set-nonbioak"t< name=swf.installatiockea_sea_nonbioak( ion>FALSEtdr dourceerc

td


Inmay beBred, 0e lass=sess

r dourceeon succels,Hoioibswbswf alllto dcla/H1>FALSE


Inocket-l at-error">< name=swf.installatiockea_f at_errorction>

Inocket-strerror">< name=swf.installatiockea_strerrorction>

Inocket-b cd"t< name=swf.installatiockea_b cd( ion>

Inocket-ctontio">< name=swf.installatiockea_ctontio( ion>

Inocket-fc das">< name=swf.installatiockea_fc das( ion>

Inocket-cr aae">< name=swf.installatiockea_cr aae( ion>Inil you need to dclass=section>

Inocket-strerror">< name=swf.installatiockea_strerrorction>

Instalaçlass=4 .htm= 4.1.0nce yoockea_b cdd to dclass=seB cdalaaname to a dockea

Instalaçãoed to dclnddrels<[,lnstahave]>laçãoTBODY>laçãoTR>laçãçãoTDslyign=middle>A ençãolaçãoTR>laçãçãoTDslyign=left>laçãçãçãoanTD>an

bito ve lmockea o r dourceebswr aaed

Inocket-cr aae">< name=swf.installatiockea_cr aae( ion> you neede 127.0.0.1çãoiniscoA y blibswwf alllto dcla/H1>AF_INEToion>>inUnix-domai emockea,>if wf amockea>familye AF_UNIX you neede ciontio nguto ln ibswwf alllto dcla/H1>AF_INETA>Ino ignaaeal n>TRUEFALSE

Inocket-l at-error">< name=swf.installatiockea_f at_errorction>

Inocket-strerror">< name=swf.installatiockea_strerrorction>

Inocket-ctontio">< name=swf.installatiockea_ctontio( ion>

Inocket-fc das">< name=swf.installatiockea_fc das( ion>

Inocket-cr aae">< name=swf.installatiockea_cr aae( ion>

Inocket-l at-error">< name=swf.installatiockea_f at_errorction>

Inil you need to dclass=section>

Inocket-strerror">< name=swf.installatiockea_strerrorction>

Instalaçlass=4 .htm= 4.2.0nce yoockea_clear_errord to dclass=seClearalthH1errorloion>

Instalaçãoe libswf all you needockea_clear_errornslação[r dourcee dockea]>laçãoTBODY>laçãoTR>laçãçãoTDslyign=middle>A ençãolaçãoTR>laçãçãoTDslyign=left>laçãçãçãoanTD>an
oion> >inmockea>oiooA y bl1. ense=swglobalrl atferrorlcideion>
Inil you need to dclass=section>

Inocket-strerror">< name=swf.installatiockea_strerrorction>nson>

Instalaçlass=4 .htm= 4.1.0nce yoockea_clos>d to dclass=seClos>alaamockea>inr dource

Instalaçãoe libswf all you needockea_clos>nslaçãor dourcee dockea>laçãoTBODY>laçãoTR>laçãçãoTDslyign=middle>A ençãolaçãoTR>laçãçãoTDslyign=left>laçãçãçãoanTD>an

( ion> clos>aln>r dourcee=sectAby sbswbswf all you need to dockea laçãoNota: ion>section>
( ion> can'tsbeBd, 0,o tioucilns=s="r dources wr aaed

Ipopen">< nam ction>
popen( all

Ifsockopen">< nam ction>
fsockopen( all

Ipfsockopen">< nam ction>
pfsockopen( all meanteeorl

Idocket-cr aae">< nam ction>

Idocket-accept"t< nam ction>
an
=sessSee also Hl you need to dclass=section>

Inocket-b cd"t< name=swf.installatiockea_b cd( ion>

Inocket-fc das">< name=swf.installatiockea_fc das( ion>

Inocket-cr aae">< name=swf.installatiockea_cr aae( ion>

Inil you need to dclass=section>

Inocket-strerror">< name=swf.installatiockea_strerrorction>

Instalon>InstalaçãolaçãoTBODY>laçãoTR>laçãçãoTDslyign=middle>A ençãolaçãoTR>laçãçãoTDslyign=left>laçãçãçãoanTD>an
r dourceesbswbswf all you need to dockea laçãor dourceebswr aaed

Inocket-cr aae">< name=swf.installatiockea_cr aae( ion> you neede 127.0.0.1çãoiniscoA y blibswwf alllto dcla/H1>AF_INEToion>>inUnix-domai emockea,>if wf amockea>familye AF_UNIX you neede ciontio nguto ln ibswwf alllto dcla/H1>AF_INETA>Ino ignaaeal n>TRUEFALSE

Inocket-l at-error">< name=swf.installatiockea_f at_errorction>

Inocket-strerror">< name=swf.installatiockea_strerrorction>

Inocket-b cd"t< name=swf.installatiockea_b cd( ion>

Inocket-fc das">< name=swf.installatiockea_fc das( ion>

Inocket-cr aae">< name=swf.installatiockea_cr aae( ion>

Inocket-l at-error">< name=swf.installatiockea_f at_errorction>

Inil you need to dclass=section>

Inocket-strerror">< name=swf.installatiockea_strerrorction>

Instalaçlass=4 .htm= 4.1.0nce yoockea_cr aae_lc dasd to dclass=seOpenalaamockea>onhme=sveeto acceptlciontio

InstalaçãolaçãoTBODY>laçãoTR>laçãçãoTDslyign=middle>A ençãolaçãoTR>laçãçãoTDslyign=left>laçãçãçãoanTD>an
meanteso eaibswf ataskcoA cr aa claaanew mockea>R=ichaonly lc das
cr aaeBsanew mockea>r dourceeofl ntalaibswwf alllto dcla/H1>AF_INET you needed is ualn>SOMAXCONN you need, se/fHl you need to dclass=section>

Inocket-fc das">< name=swf.installatiockea_fc das( ion>
r

r dourceeon succelsHoioibswwf alllto dcla/H1>FALSE


Inocket-f at-error">< name=swf.installatiockea_f at_errorction>

Inocket-strerror">< name=swf.installatiockea_strerrorction>Nota: ion>Ifuywf wanteso cr aaeBsamockea>R=ichaonly lc das

Idocket-cr aae">< nam ction>

Inocket-b cd"t< nam ction>

Inil yo u need to dclass=section>

Inocket-fc das">< nam ction>
an
=sessSee also Hl you need to dclass=section>

Inocket-cr aae">< name=swf.installatiockea_cr aae( ion>

Inocket-b cd"t< name=swf.installatiockea_b cd( ion>

Inocket-fc das">< name=swf.installatiockea_fc das( ion>

Inocket-l at-error">< name=swf.installatiockea_f at_errorction>

Inil you need to dclass=section>

Inocket-strerror">< name=swf.installatiockea_strerrorction>

Instalaçlass=4 .htm= 4.1.0nce yoockea_cr aae_paird to dclass=seCr aaes aapair

InstalaçãolaçãoTBODY>laçãoTR>laçãçãoTDslyign=middle>A ençãolaçãoTR>laçãçãoTDslyign=left>laçãçãçãoanTD>an
laçãoTBODY>laçãoTR>laçãçãoTDslyign=middle>A ençãolaçãoTR>laçãçãoTDslyign=left>laçãçãçãoanTD>an

Instalaçlass=4 .htm= 4.1.0nce yoockea_cr aaed to dclass=seCr aaeBsamockea>(etdpointe eorlci municseed )

Instalon>InstalaçãoCr aaes a>Inr

r dource, also =seerr 0,to asi>A>Inanothsrsperass= class=srole you needesp

Onaln>InstalaçH1>Tabela 1. Availnotefaddrels/hrotocoleeamilOnalaçãoTHEAD>laçãoTR>laçãçãoTH vAyign=ceaserulyign=left>Domai lTH>laçãçãoTH vAyign=ceaserulyign=left>D/A>InstalaçãTH>laçãoTBODY>laçãoTR>laçãçãoTDsvAyign=ceaserulyign=left>AF_INETlaçãçãoTDsvAyign=ceaserulyign=left>IPv4 Iasernea>ba, 0,hrotocoleA>InUDPflaçãçãçãss=sci m hrotocole laçãoTR>laçãçãoTDsvAyign=ceaserulyign=left>AF_UNIXlaçãçãoTDsvAyign=ceaserulyign=left>Loalloci municseed hrotocoleeamilyA>Inou iovash adtmakecitsa gr aauftimeofiIPC (Iaserhrocelsan


e sbswwf all you need to ntal llação you needesc eioaln>Tabela 2. Availnotefmockea>ntalalaçãoTHEAD>laçãoTR>laçãçãoTH vAyign=ceaserulyign=left>Ttal lTH>laçãçãoTH vAyign=ceaserulyign=left>D/A>InstalaçãTH>laçãoTBODY>laçãoTR>laçãçãoTDsvAyign=ceaserulyign=left>SOCK_STREAMlaçãçãoTDsvAyign=ceaserulyign=left>Provide escquenctd,>relinote, l ll-duplex, laçãçãçãcoontio -ba, 0,bytnãhareams. An out-of-ba>Inoata transmisse=swmechanism laçãçãçãmay beBsuphave 0e T>e aCP>hrotocoleis ba, 0,ntallaçãoTR>laçãçãoTDsvAyign=ceaserulyign=left>SOCK_DGRAMlaçãçãoTDsvAyign=ceaserulyign=left>Suphavesnoatagu ns (coontio lels,HlaçãçãçãunrelinoteHmessageal=fi>>fixedAmaximumeleng <)e T>e UDPfhrotocoleis ba, 0,laçãçãçãntallaçãoTR>laçãçãoTDsvAyign=ceaserulyign=left>SOCK_SEQPACKETlaçãçãoTDsvAyign=ceaserulyign=left>Provide eaescquenctd,>relinote, two-wayeef="çãçãcoontio -ba, 0,oata transmisse=swpathuftiooatagu ns =fifixedAmaximumeef="çãçãleng <;ap_ltos clre h>laçãoTR>laçãçãoTDsvAyign=ceaserulyign=left>SOCK_RDMlaçãçãoTDsvAyign=ceaserulyign=left>Provide ea>relinoteooatagu n layeion>atadoe < ysteman
e sbswwf all you need to hrotocol llação you needescoaln>Oc/inhrotocole Oe0,sbswwf all you need to domai llaçãoto beBd, 0, whn> ci municseengud ty blr

td


I1. protobyname">< name=swf.installat1. protobynamection>SOL_aCPInibswbswf alllto dcla/H1>SOL_UDPTabela 3.ãCi m hrotocolelaçãoTHEAD>laçãoTR>laçãçãoTH vAyign=ceaserulyign=left>Naml lTH>laçãçãoTH vAyign=ceaserulyign=left>D/A>InstalaçãTH>laçãoTBODY>laçãoTR>laçãçãoTDsvAyign=ceaserulyign=left>icmplaçãçãoTDsvAyign=ceaserulyign=left>T>Control MessageaProtocol< A>Inhosts,to r =sveeerrorssinsoatagu n ef="çãçãco municseed e T>In(hreleassinsmostumidernãef="çãçãguyouaseeson>ataclA>oata packeasH_pt_BR.hrccesecd inswf anrdOn insR=ichaef="çãçãy by wsrnaleas. IouanyApackea>is momehu ilostuduru newi municseed , aCP>ef="çãçã_pt_Bsuto=refc=slylr ransmiton>untilwtssno a cseed thostuef="çãçãacknowledgeson>atapackea. Forãrelinoility>A>Inperass=anceercas s,> namaCP>ef="çãçãi pleclasseed titsc fno cide e namapproprihms octea>bneraarOnsean

R

r dourceeon succels,H oioibswwf alllto dcla/H1>FALSE


Inocket-l at-error">< name=swf.installatiockea_f at_errorction>

Inocket-strerror">< name=swf.installatiockea_strerrorction>Nota: ion>IfuatAinctiid sbswwf all you need to domai llaçãooioibswbs wwf all you need to ntal llação <=sect, secbs wwf all
defaults,to ibswbs wwf alllto dcla/H1>AF_INETInibswbs wwf alllto dcla/H1>SOCK_STREAMInaddi=slylemias
  • E_WARNINGan
    =sessSee also Hl you need to dclass=section>

    Inocket-accept"t< namwf all

    Inocket-b cd"t< name=swf.installatiockea_b cd( ion>

    Inocket-ctontio">< name=swf.installatiockea_ctontio( ion>

    Inocket-fc das">< name=swf.installatiockea_fc das( ion>

    Inocket-l at-error">< name=swf.installatiockea_f at_errorction>Inil you need to dclass=section>

    Inocket-strerror">< name=swf.installatiockea_strerrorction>nstadockea_get_o class=on>

    Instalaçlass=4 .htm= 4.3.0nce yoockea_get_o clasd to dclass=seGeasHmockea>opn yod coio n>

    InstalaçãolaçãoTBODY>laçãoTR>laçãçãoTDslyign=middle>A ençãolaçãoTR>laçãçãoTDslyign=left>laçãçãçãoanTD>an
    laçãoTBODY>laçãoTR>laçãçãoTDslyign=middle>A ençãolaçãoTR>laçãçãoTDslyign=left>laçãçãçãoanTD>an
    Nota: ion>T> tockea_getoptf alo rioiono tio 4.3.0 =Once BLOCKQUOTE>an
    e you have libswf all you needocket-getpeertallanstadockea_getpeertalls=on>

    Instalaçlass=4 .htm= 4.1.0nce yoockea_getpeertalld to dclass=se QuOnOnaln>R=ichamay eithsrsr dult inshost/paveeon insa UNIXo ciln>ystemapath,0d petdeassd tits>ntal

    Instalon>InstalaçãolaçãoTBODY>laçãoTR>laçãçãoTDslyign=middle>A ençãolaçãoTR>laçãçãoTDslyign=left>laçãçãçãoanTD>an
    iscoA ytalaibswwf alllto dcla/H1>AF_INET _pt_Br

    on>127.0.0.1ção you needeA>I,>if wf ao clasalaibswbswf all you need to have llação you neede iscoA ytalaibswwf alllto dcla/H1>AF_UNIX _pt_Br

    on>ystemapathc (e.g. sbswwf alllitere >/var/run/da moeedockção you needTRUEFALSE may also =s

    oibswbswf alllto dcla/H1>FALSEntale <.insanyAofoibswbswf alllto dcla/H1>AF_INETAF_UNIXerrorlcidef


    , Hl you need to dclass=section>
    Inil you need to dclass=section>

    Inocket-strerror">< name=swf.installatiockea_strerrorction>

    R=ichamay eithsrsr dult inshost/paveeon insa UNIXo ciln>ystemapath,0d petdeassd tits>ntal

    Instalon>InstalaçãolaçãoTBODY>laçãoTR>laçãçãoTDslyign=middle>A ençãolaçãoTR>laçãçãoTDslyign=left>laçãçãçãoanTD>an
    iscoA ytalaibswwf alllto dcla/H1>AF_INET _pt_Br

    on>127.0.0.1ção you needeA>I,>if wf ao clasalaibswbswf all you need to have llação you neede iscoA ytalaibswwf alllto dcla/H1>AF_UNIX _pt_Br

    on>ystemapathc (e.g. sbswwf alllitere >/var/run/da moeedockção you needTRUEFALSE may also =s

    oibswbswf alllto dcla/H1>FALSEntale <.insanyAofoibswbswf alllto dcla/H1>AF_INETAF_UNIXerrorlcidef


    Inocket-l at-error">< name=swf.installatiockea_f at_errorction>

    Inil you need to dclass=section>

    Inocket-strerror">< name=swf.installatiockea_strerrorction>

    Instalaçlass=4 .htm= 4.1.0nce yoockea_iovec_nddd to dclass=seAdd

    Instalon>InstalaçãolaçãoTBODY>laçãoTR>laçãçãoTDslyign=middle>A ençãolaçãoTR>laçãçãoTDslyign=left>laçãçãçãoanTD>an
    laçãoTBODY>laçãoTR>laçãçãoTDslyign=middle>A ençãolaçãoTR>laçãçãoTDslyign=left>laçãçãçãoanTD>an

    Instalaçlass=4 .htm= 4.1.0nce yoockea_iovec_nlioad to dclass=se...]) Buildrecvmsg,>writev, a>Inr advela

    Instalon>InstalaçãolaçãoTBODY>laçãoTR>laçãçãoTDslyign=middle>A ençãolaçãoTR>laçãçãoTDslyign=left>laçãçãçãoanTD>an
    laçãoTBODY>laçãoTR>laçãçãoTDslyign=middle>A ençãolaçãoTR>laçãçãoTDslyign=left>laçãçãçãoanTD>an

    InstalaçãolaçãoTBODY>laçãoTR>laçãçãoTDslyign=middle>A ençãolaçãoTR>laçãçãoTDslyign=left>laçãçãçãoanTD>an
    laçãoTBODY>laçãoTR>laçãçãoTDslyign=middle>A ençãolaçãoTR>laçãçãoTDslyign=left>laçãçãçãoanTD>an

    Instalaçlass=4 .htm= 4.1.0nce yoockea_iovec_fetchd to dclass=seR

    Oe0,byaiovec_id[iovec_posi]

    Instalação>laçãoTBODY>laçãoTR>laçãçãoTDslyign=middle>A ençãolaçãoTR>laçãçãoTDslyign=left>laçãçãçãoanTD>an
    laçãoTBODY>laçãoTR>laçãçãoTDslyign=middle>A ençãolaçãoTR>laçãçãoTDslyign=left>laçãçãçãoanTD>an

    Instalaçlass=4 .htm= 4.1.0nce yoockea_iovec_freed to dclass=seFrenaln>Oe0,byaiovec_id

    InstalaçãolaçãoTBODY>laçãoTR>laçãçãoTDslyign=middle>A ençãolaçãoTR>laçãçãoTDslyign=left>laçãçãçãoanTD>an
    laçãoTBODY>laçãoTR>laçãçãoTDslyign=middle>A ençãolaçãoTR>laçãçãoTDslyign=left>laçãçãçãoanTD>an

    ]

    Instalação,ãhared anew_val>laçãoTBODY>laçãoTR>laçãçãoTDslyign=middle>A ençãolaçãoTR>laçãçãoTDslyign=left>laçãçãçãoanTD>an
    laçãoTBODY>laçãoTR>laçãçãoTDslyign=middle>A ençãolaçãoTR>laçãçãoTDslyign=left>laçãçãçãoanTD>an

    errorl d ty bloockeaaia

    Instalon>InstalaçãolaçãoTBODY>laçãoTR>laçãçãoTDslyign=middle>A ençãolaçãoTR>laçãçãoTDslyign=left>laçãçãçãoanTD>an
    errorlcider dourcee errorlR=ichaoccur 0,latdr dourcee failtdtd

    Inocket-cr aae">< name=swf.installatiockea_cr aae( ion>oaamockea>onhfailur ef>

    Inocket-sc eio">< name=swf.installatiockea_sc eio( ion>

    Inocket-strerror">< name=swf.installatiockea_strerrorction>Inbiclass=s =sectAerrorlcidelaçãoTBODY>laçãoTR>laçãçãoTD>
    if (falibs== ($mockea>= @iockea_cr aae(AF_INET, SOCK_STREAM, SOL_aCP))) {laçãçãdie("Co bln't cr aaeBiockea, errorlcidefis: " . dockea_l at_error() .laçãçãçã  ",errorlmessagefis: " . dockea_strerrorcdockea_l at_error()));
    }lasRE>anTD>annc=se
    

    Nota: ion>Hection>

    Idocket-clear-error">< nam wwf all

    is purposee lass< BLOCKQUOTE>an
    e you have libswf all you needocket-lc dasinstadockea_lc dasnson>

    Instalaçlass=4 .htm= 4.1.0nce yoockea_lc dasd to dclass=seLc das

    Instalon>Instalação [,lnsta laçãoTBODY>laçãoTR>laçãçãoTDslyign=middle>A ençãolaçãoTR>laçãçãoTDslyign=left>laçãçãçãoanTD>an
    =se ben> cr aae0,la=s claHl you need to dclass=section>

    Inocket-cr aae">< name=swf.installatiockea_cr aae( ion>

    Inocket-b cd"t< name=swf.installatiockea_b cd( ion>inco= claciontio u _pt_BR.hqueutdBcoiohrocelsiclioIfuaaltontio requestAarrsecs< ECONNREFUSED<ãoif wf aeraerlyu nehrotocolesuphavesnlar ransmisse=s, y blrequestAmay beBignortdatar rie fmay succe 0e lass=se

    Nota: ion>T> aibswbs wwf all you need to you needehighly d petdsfSOMAXCONNif hawf 0,ibswbs wwf alllto dcla/H1>SOMAXCONN< ne <.i laçã dcldardAhrovise=swto find outon>an
    A namlection>
    SOCK_STREAMSOCK_SEQPACKETTRUEFALSE

    Inocket-l at-error">< name=swf.installatiockea_f at_errorction>

    Inocket-strerror">< name=swf.installatiockea_strerrorction>

    Inocket-accept"t< namwf all

    Inocket-b cd"t< name=swf.installatiockea_b cd( ion>

    Inocket-ctontio">< name=swf.installatiockea_ctontio( ion>

    Inocket-cr aae">< name=swf.installatiockea_cr aae( ion>

    Inocket-strerror">< name=swf.installatiockea_strerrorction>nstadockea_r adnson>

    Instalaçlass=4 .htm= 4.1.0nce yoockea_r add to dclass=seR ad

    Instalon>InstalaçãolaçãoTBODY>laçãoTR>laçãçãoTDslyign=middle>A ençãolaçãoTR>laçãçãoTDslyign=left>laçãçãçãoanTD>an
    e
    r adcr aae0, have lHl you need to dclass=section>

    Inocket-accept"t< namwf all
    Oe0,byat> aibswwf all you need to leng <çãlação you need rwiibsyouoh>\n,Horl\0"to e>Inr adu nl(d petdu nlonswf aibswbswf all you need to ntal llação you need,ise
    r

    FALSE


    Inocket-l at-error">< name=swf.installatiockea_f at_errorction>

    Inocket-strerror">< name=swf.installatiockea_strerrorction>Nota: ion>lection>
    may rc

    oaazeiooleng InoA ci municseed e(i.ne y blremoteoe>Inpointe=se laçãccof 0,t blctontio )an


    =sessO clasalaibswwf all you need to ntal llação you need< r ad( iooion>I laçãSafe coiorcadu nlb caryloata. (Default\nHorl\r. (Default

    Inocket-accept"t< namwf all

    Inocket-b cd"t< name=swf.installatiockea_b cd( ion>

    Inocket-ctontio">< name=swf.installatiockea_ctontio( ion>

    Inocket-lc das">< name=swf.installatiockea_fc das( ion>

    Inocket-l at-error">< name=swf.installatiockea_f at_errorction>

    Inocket-strerror">< name=swf.installatiockea_strerrorction>

    Inocket-write">< name=swf.installatiockea_writection>nstadockea_r advnson>

    Instalaçlass=4 .htm= 4.1.0nce yoockea_r advd to dclass=seR ad

    Instalon>InstalaçãolaçãoTBODY>laçãoTR>laçãçãoTDslyign=middle>A ençãolaçãoTR>laçãçãoTDslyign=left>laçãçãçãoanTD>an
    laçãoTBODY>laçãoTR>laçãçãoTDslyign=middle>A ençãolaçãoTR>laçãçãoTDslyign=left>laçãçãçãoanTD>an
    nstadockea_r cvnson>

    Instalaçlass=4 .htm= 4.1.0nce yoockea_r cvd to dclass=seR cesecsnoataofron aa ciontiotd

    Instalon>InstalaçãolaçãoTBODY>laçãoTR>laçãçãoTDslyign=middle>A ençãolaçãoTR>laçãçãoTDslyign=left>laçãçãçãoanTD>an
    laçãoTBODY>laçãoTR>laçãçãoTDslyign=middle>A ençãolaçãoTR>laçãçãoTDslyign=left>laçãçãçãoanTD>an
    nstadockea_r cvfronnson>

    Instalon>InstalaçãolaçãoTBODY>laçãoTR>laçãçãoTDslyign=middle>A ençãolaçãoTR>laçãçãoTDslyign=left>laçãçãçãoanTD>an
    laçãoTBODY>laçãoTR>laçãçãoTDslyign=middle>A ençãolaçãoTR>laçãçãoTDslyign=left>laçãçãçãoanTD>an
    nstadockea_r cvmsgnson>

    Instalaçlass=4 .htm= 4.1.0nce yoockea_r cvmsgd to dclass=seUf 0,to rccesecoaamockea, whethsrsctontio -orilasuc

    Instalon>InstalaçãolaçãoTBODY>laçãoTR>laçãçãoTDslyign=middle>A ençãolaçãoTR>laçãçãoTDslyign=left>laçãçãçãoanTD>an
    laçãoTBODY>laçãoTR>laçãçãoTDslyign=middle>A ençãolaçãoTR>laçãçãoTDslyign=left>laçãçãçãoanTD>an
    nstadockea_sc eionson>

    Instalaçlass=4 .htm= 4.1.0nce yoockea_sc eiod to dclass=seRu>Oe0,byatv_scc">

    InstalaçãolaçãoTBODY>laçãoTR>laçãçãoTDslyign=middle>A ençãolaçãoTR>laçãçãoTDslyign=left>laçãçãçãoanTD>an
    e
    acceptsAarrayscoA oockeas<>atatsosblsockeaInstavhseas< asrene aibswwf all you need to r adnslaçãoarraye_pt_BR.h watchtd to r dourcee

    Inocket-=sad">< name=swf.installatiockea_r ad( ion>oaazeiooleng aibswwf all you need to writenslaçãoarraye_pt_BR.h watchtd to writee_pt_B.insblock aibswwf all you need to exceptnslaçãoarraye_pt_B bnewatchtd,coioexceptid s< lass=se

    laçãoTBODY>laçãoTR>laçãçãoTDslyign=middle>A ençãolaçãoTR>laçãçãoTDslyign=left>laçãçãçãoOe0,to indOcsee R=ichamockea>r dourceelaçãçãçãacte=sly changedã dctus< anP>anTD>an
    arrayeto Hection>
    I laYouoh>arrayeoriibswbswf alllto dcla/H1>NULLatatsosblarraysc a nehawf 0,iSPAN cclassemp=seis Oe0,afeedelection>
    r

    <laçãoTBODY>laçãoTR>laçãçãoTD>

    /* Prepa ney blreadearraye*/
    $reade=earray($mockea1, $mockea2);
    
    if (falibs=== ($num_changed_oockeas = aa>onefanTD>annc=se
    

    Nota: ion>DueBsafcmisrefseciout> acurreassZe>InEngine itfis .inspossiote,=s="to pswf a lto dclahmodP>Oerulike Hbswwf alllto dcla/H1>NULL R=ichaexp is haru need temhavarylvaviaote,ors> temhavarylvaviaote: laçãoTABLE cellPadding=5 bgColor=#e0e0e0 bnrdOn=0>laçãçãoTBODY>laçãçãoTR>laçãçãçãoTD>
    anTD>annce BLOCKQUOTE>an
    =sessT> aibswwf all you need to yv_sccnslaçãoan0,ibswbswf all you need to yv_usccnslaçãotogethsrsass=ut> aiSPAN cclassemp=seis aiSPAN cclassemp=seis
    r

    .,ibswbswf all you need to yv_sccnslaçãomay beBzeioo,oh>=s claH name=swf.installatiockea_sc eio( ion>,to rc

    oims=seseelyion> < NULL,h>


    r

    lar dorcescdclaaine0,iout> amodP>Oe0,arrays,>R=ichamay beBzeiooif wf atimeouto expires,beforFALSEtd


    Inocket-l at-error">< name=swf.installatiockea_f at_errorction>Nota: ion>B sure,to uibsn>===ção
    may rc

    o0,t blctm yois=sw ==çãoTRUElaçãçãoTBODY>laçãçãoTR>laçãçãçãoTD>

    if (falibs=== failtd,ãr as
    : " . dockea_strerrorcdockea_l at_error()) . "\n";
    }lasRE>anTD>annce BLOCKQUOTE>an
    =se

    Nota: ion>B awa ney at soclomockea>impleclasstid ssnee0,to nahandled< vasy>ca nl llyioA few bseic rules: laçãoamlass=sçãoULs=s=" "hLIs=s="çãoamYouosho bl alwaysctry,to uibssection>
    =s="çã fPcultlto debugioannc=s=" "hLIs=s="çãoamNo r dourceemust naadde0,to anyAsetoif you do .insnstera,to chtckn ="çãiesnr dult afeedey blsection>
    cclA, a>Inr la In ="çãappropviaeelyioAfeedelection>
    r

    <, alln ="çãr dource r dourceey at iso=s="çãavailaoteaforswritu nlmust nawritdasBto, a>InanyAsockea>r dourceeavailaotea=s="çãcoior adu nlmust nareadefronioannc=s=" "hLIs=s="çãoamIf you read/writeeto a sockea>r

    aarrayscb awa ney at t> y do =s="çã.insnecelsyoily read/writeetheimpleclasstid ssy at t> Aonly exceptid oh>=ght =s="çã aibswwf all you need to exceptnslaçãoarraye anLlaçãULs=sçãoamlasse BLOCKQUOTE>an


    =sessSee also Hl you need to dclass=section>

    Inocket-=sad">< name=swf.installatiockea_r ad( ion>

    Inocket-write">< name=swf.installatiockea_writection>

    Inocket-l at-error">< name=swf.installatiockea_f at_errorction>

    Inil you need to dclass=section>

    Inocket-strerror">< name=swf.installatiockea_strerrorction>nstadockea_scndnson>

    Instalon>InstalaçãolaçãoTBODY>laçãoTR>laçãçãoTDslyign=middle>A ençãolaçãoTR>laçãçãoTDslyign=left>laçãçãçãoanTD>an
    laçãoTBODY>laçãoTR>laçãçãoTDslyign=middle>A ençãolaçãoTR>laçãçãoTDslyign=left>laçãçãçãoanTD>an
    nstadockea_scndmsgnson>

    InstalaçãolaçãoTBODY>laçãoTR>laçãçãoTDslyign=middle>A ençãolaçãoTR>laçãçãoTDslyign=left>laçãçãçãoanTD>an
    laçãoTBODY>laçãoTR>laçãçãoTDslyign=middle>A ençãolaçãoTR>laçãçãoTDslyign=left>laçãçãçãoanTD>an
    nstadockea_scndtonson>

    InstalaçãolaçãoTBODY>laçãoTR>laçãçãoTDslyign=middle>A ençãolaçãoTR>laçãçãoTDslyign=left>laçãçãçãoanTD>an
    laçãoTBODY>laçãoTR>laçãçãoTDslyign=middle>A ençãolaçãoTR>laçãçãoTDslyign=left>laçãçãçãoanTD>an
    nstadockea_sct_non locknson>

    Instavhfd

    Instalon>InstalaçãolaçãoTBODY>laçãoTR>laçãçãoTDslyign=middle>A ençãolaçãoTR>laçãçãoTDslyign=left>laçãçãçãoanTD>an
    laçãoTBODY>laçãoTR>laçãçãoTDslyign=middle>A ençãolaçãoTR>laçãçãoTDslyign=left>laçãçãçãoanTD>an
    nstadockea_sct_ostalaçãon>

    Instalaçlass=4 .htm= 4.3.0nce yoockea_sct_ostalad to dclass=seScoaldockea"ostalas coio y bloockeala

    Instalon>InstalaçãolaçãoTBODY>laçãoTR>laçãçãoTDslyign=middle>A ençãolaçãoTR>laçãçãoTDslyign=left>laçãçãçãoanTD>an
    laçãoTBODY>laçãoTR>laçãçãoTDslyign=middle>A ençãolaçãoTR>laçãçãoTDslyign=left>laçãçãçãoanTD>an
    Nota: ion>T> dockea_sctoptf alo riodan
    e you have libswf all you needocket-shutdowa>nstadockea_shutdowaçãon>

    Instalaçlass=4 .htm= 4.1.0nce yoockea_shutdowad to dclass=seShutsfdowa a sockea>coio rcceseu n,isetdu n,Horlboth.

    Instalon>InstalaçãolaçãoTBODY>laçãoTR>laçãçãoTDslyign=middle>A ençãolaçãoTR>laçãçãoTDslyign=left>laçãçãçãoanTD>an
    laçãoTBODY>laçãoTR>laçãçãoTDslyign=middle>A ençãolaçãoTR>laçãçãoTDslyign=left>laçãçãçãoanTD>an
    nstadockea_strerrorçãon>

    Instalaçlass=4 .htm= 4.1.0nce yoockea_strerrord to dclass=seR

    samared alad/A>Inbiclasamockea>errorla


    InstalaçãolaçãoTBODY>laçãoTR>laçãçãoTDslyign=middle>A ençãolaçãoTR>laçãçãoTDslyign=left>laçãçãçãoanTD>an

    takescasãiesnibswbswf all you need to errno llação you neederrorlcidecasãrc

    td,by Hl you need to dclass=section>


    Inr

    <, you just pswf iteto Hecame=swf.installatiockea_strerrorction>, a>Initetells you w at happete0iolass=sess=seTABLE cclassEXAMPLE cellSpaci n=0 cellPadding=0lction="100%" bnrdOn=0>laçãoTBODY>laçãoTR>laçãçãoTD>laçãçãção

    InstaçãçãçãoExemplo 1.election>
    exampleion>laçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    .ltm?>= @iockea_cr aae(AF_INET, SOCK_STREAM, 0))) {laçãçecho "failtd:ãr as
    : " . dockea_strerrorcdockea_l at_error()) . "\n";
    } 
    
    if (falibs== (@iockea_b cd($dockea,ã'127.0.0.1', 80))) {laçãçecho "failtd:ãr as
    : " . dockea_strerrorcdockea_l at_error($dockea)) . "\n";
    }
    ?.htmanTD>taçãçãçãoInstfis .inslaçãçãçãrusw
    
    laçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    Ieeatiockea_b cd( >failtd:ãr as
    : Permisse=s deniedanTD>sOnce you anTD>sOnc=sessSee also Hl you need to dclass=section>
    

    Inocket-accept"t< namwf all

    Inocket-b cd"t< namwf all

    Inocket-ctontio">< name=swf.installatiockea_ctontio( ion>

    Inocket-lc das">< name=swf.installatiockea_fc das( ion>Inil you need to dclass=section>

    Inocket-cr aae">< name=swf.installatiockea_cr aae( ion>nstadockea_writenson>

    Instalon>InstalaçãolaçãoTBODY>laçãoTR>laçãçãoTDslyign=middle>A ençãolaçãoTR>laçãçãoTDslyign=left>laçãçãçãoanTD>an
    e
    >writeslto t bloockeanibswbswf all you need to sockealalaçãofron ibswwf all you need to bufferlalaçãoeh>ys>
    is leng FALSE

    Inocket-l at-error">< name=swf.installatiockea_f at_errorction>

    Inocket-strerror">< name=swf.installatiockea_strerrorction>Nota: ion>lection>
    >doesã.insnecelsyoily =s="writeeat_BRytnsofron y bl=sectAbuffer. It's vlyidsy at, d petdu nlonswf a=s="networkAbuffers etc.,Aonly auderaainnamnertf Aresefan
    A n

    Nota: ion>Itfis perfeioly vlyidscoiolection>
    >=s=" o rc

    ozeiooR=ichamea><<.i Rytnsohaec litere >===çãoFALSEan


    A nssSee also Hl you need to dclass=section>

    Inocket-accept"t< namwf all

    Inocket-b cd"t< namwf all

    Inocket-ctontio">< name=swf.installatiockea_ctontio( ion>

    Inocket-lc das">< name=swf.installatiockea_fc das( ion>

    Inocket-=sad">< name=swf.installatiockea_r ad( ion>Inil you need to dclass=section>

    Inocket-strerror">< name=swf.installatiockea_strerrorction>nstadockea_writevnson>

    Instalaçlass=4 .htm= 4.1.0nce yoockea_writevd to dclass=seWriteseto a cilnBlad/A>Instav, fd,a=s clay blscataer-gathsrsarrayedefine0,byaiovec_id

    Instalon>InstalaçãolaçãoTBODY>laçãoTR>laçãçãoTDslyign=middle>A ençãolaçãoTR>laçãçãoTDslyign=left>laçãçãçãoanTD>an
    laçãoTBODY>laçãoTR>laçãçãoTDslyign=middle>A ençãolaçãoTR>laçãçãoTDslyign=left>laçãçãçãoanTD>an

    Instal

    XCVIII. Stream
    Instal

    nstaIetrodução tioçãoInothsrsopperated s R=ichamha ne a ci m=swsetooffou need so>dtream<ãor dourceçãoInmay beBaote,to il you need to dclass=section>

    Iectek">< name=swf.installatectekction>wrapper<ãoOcohrotocols/encodu ns. For example,sn> to <ãoHTTP/1.0<ão cilnBonsa remoteoserved rtioção

    ApêndOcne IInaddiclasal, custon wrapperslmay beBadde0,eithsrsRithu aa ass=o>Instf =s claHl you need to dclass=section>

    Intream-=sgc dar-wrapper">< name=swf.installatitream_=sgc dar_wrapper( ion>

    Capítul< la43=senanyAvavietyeoffwrapper may beBadde0,toAsbsw=swf alllitere >tioção< ne <.i setofcmis R=atfh> m= T< laaccelsethe lisef

    Intream-get-wrappers">< name=swf.installatitream_gea_wrappersction>cilter<ãotioçãoInstf=s claHl you need to dclass=section>

    Intream-=sgc dar-cilter">< name=swf.installatitream_=sgc dar_cilterction>

    Capítul< la43

    Intream-get-cilters">< name=swf.installatitream_gea_ciltersction> menslaçãoA namlass=seULs=sçãoLIs=s="namlbswwf all you need to sc> menslaçãoIn>

    ApêndOcne I lisefOe0,swf a=s="installaedefault< cileção- D petdsfis is typically sa y is is typically sahostu ne,ãofdasB=s="

    ApêndOcne I d/A>InstalacoA yaigets coiobuiltin itreams< anP>anLlaçãULs=slahave 1 classstio anyou hav

    lahave 1 classstio tioção m= anP>anyou hav

    lahave 1 classstio >anyou hav

    lahave 1 classstio

    Intream-=sgc dar-wrapper">< name=swf.installatitream_=sgc dar_wrapper( ion>wf alçãoIni

    Intream-=sgc dar-cilter">< name=swf.installatitream_=sgc dar_cilterction>anyou hav

    lahave 1 classstio Instalaçlass=seTABLE cclassCALSTABLE bnrdOn=1>laçãoTHEAD>laçãoTR>laçãçãoTH vAyign=claserslyign=left>Con dclaçãoH>laçãçãoTH vAyign=claserslyign=left>InstalaçãoH>laçãoTBODY>laçãoTR>laçãçãoTDsvAyign=claserslyign=left>ibswbs w wwf alllto dcla/H1>STREAM_USE_PATHlaçãçãoTDsvAyign=claserslyign=left>ibswwf alllitere >Flag<ãostream<ãolaçãoTR>laçãçãoTDsvAyign=claserslyign=left>ibswbs w w wwf alllto dcla/H1>STREAM_REPORT_ERRORSlaçãçãoTDsvAyign=claserslyign=left>ibswwf alllitere >Flag<ãowrapper<ão

    Iareggar-error">< nam w w wwf allinstallatareggar_errorction>

    is flagfis .inssea,ãyouosho bl .insraisenanyAerrors. laTD>talahave 1 classstio r laae0,installa, a>sopperated ,onsa stream vavietyeoffnss=alãr as s (i.e.: Unaote,to ctontio" o rcmoteohost, lacilnB.inscoun0,setc...)ioA stream=seny bldesiredtd,by sl you need to dclass=section>

    Intream-get-wrappers">< name=swf.installatitream_gea_wrappersction> liseftioçãofailure,occours atAsbswwf alllto dcla/H1>E_WARNINGInbiclatse nature,ofay bl1rrorlahave 1 classstio laçãoTBODY>laçãoTR>laçãçãoTD>laçãçãção

    InstaçãçãçãosssB>Exemplo 1.eUs claHl yo lçãçãu need to dclass=section>

    Iciln-get-dclalass">< nam w w wwf allinstallatciln_gea_dclalassction>laçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    .ltm?> met*/
    $localcilnB= ciln_gea_dclalassc"cilndcl/home/bar/foo.txt");
    
    /* R adercmoteocilnBfron www=example=comf=s claHTTPt*/
    $ to cilnBB= ciln_gea_dclalassc" to dclwww=example=com/foo.txt");
    
    /* R adercmoteocilnBfron www=example=comf=s claHTTPSt*/
    $ to scilnB= ciln_gea_dclalassc" to sdclwww=example=com/foo.txt");
    
    /* R adercmoteocilnBfron ass=example=comf=s claFTPt*/
    $fo cilnBBB= ciln_gea_dclalassc"co dclusOn:pswf@ass=example=com/foo.txt");
    
    /* R adercmoteocilnBfron ass=example=comf=s claFTPSt*/
    $fo scilnBB= ciln_gea_dclalassc"fo sdclusOn:pswf@ass=example=com/foo.txt");
    ?.htmanTD>e you anTD>sOnc=sesshavTABLE cclassEXAMPLE cellSpaci n=0 cellPadding=0lction="100%" bnrdOn=0>laçãoTBODY>laçãoTR>laçãçãoTD>laçãçãção
    

    InstaçãçãçãosssB>Exemplo 2. Maku nla POSTHrequestato atA to soservedion>laçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    .ltm?>I>In"bar"<
    
    I>ec$dock);
    ?.htmanTD>e you anTD>sOnc=sesshavTABLE cclassEXAMPLE cellSpaci n=0 cellPadding=0lction="100%" bnrdOn=0>laçãoTBODY>laçãoTR>laçãçãoTD>laçãçãção
    

    Exemplo 3. Write claoataoto a cimhrelsedlaçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    .ltm?>Inlinef=s cla'gzip -dscoo-bar.txt.gz'
     */
    $fpB= copet("comhrels.zlibdclaoo-bar.txt.gz","wb");
    if (!$fp) die("Unaote,to creaseBcile.");
    
    fwritec$fp, "n>
    <
    ec$fp);
    ?.htmanTD>e you anTD>sOnce you la

    Ls=sçãoDTssB>ÍndOcnion>=sçãoDTssl yo u need to dclass=section>

    Intream-dclalxt-cr aae">itream_dclalxt_cr aaellatd to dclass=seCreaseByo a itreamsudclalxt=sçãoDTssl yo u need to dclass=section>

    Intream-dclalxt-gct-ostalas">itream_dclalxt_gea_ostalasllatd to dclass=seR rieve yo ostalas coioa itream/wrapper/dclalxt=sçãoDTssl yo u need to dclass=section>

    Intream-dclalxt-sct-ostala">itream_dclalxt_sct_ostalaçãatd to dclass=seScoalyo an ostala coioa itream/wrapper/dclalxt=sçãoDTssl yo u need to dclass=section>

    Intream-dclalxt-sct- you s">itream_dclalxt_sct_ you sçãatd to dclass=seSco yo you needs coioa itream/wrapper/dclalxt=sçãoDTssl yo u need to dclass=section>

    Intream-cilter-appetd">itream_cilter_appetdçãatd to dclass=seAtss=hByo a cilterBto alstream==sçãoDTssl yo u need to dclass=section>

    Intream-cilter-prepetd">itream_cilter_prepetdçãatd to dclass=seAtss=hByo a cilterBto alstream==sçãoDTssl yo u need to dclass=section>

    Intream-get-cilters">itream_gea_ciltersllatd to dclass=seR rieve yo lisef

    Intream-get- nea-oata">itream_gea_ nea_oatallatd to dclass=seR rievealyo ader/ nea dataofron itreams/cileuponsters=sçãoDTssl yo u need to dclass=section>

    Intream-get-wrappers">itream_gea_wrappersllatd to dclass=seR rieve yo lisef

    Intream-=sgc dar-cilter">itream_=sgc dar_cilterllatd to dclass=seR gc darByo a itream cilterBimpleclaseInasaa ass=i=swf derseca,fron ibswyo wf alllitere >>

    Intream-=sgc dar-wrapper">itream_=sgc dar_wrapper<ãatd to dclass=seR gc darByo a URLewrapper impleclaseInasaa ass=i=swf=sçãoDTssl yo u need to dclass=section>

    Intream-sc eio">itream_sc eio<ãatd to dclass=seRunalyo y bl1quivaltnolofay blsc eio( >systemacall<Oe0,by tv_scc,a>Intv_uscc,=sçãoDTssl yo u need to dclass=section>

    Intream-sct- locku n">itream_sct_ locku nçãatd to dclass=seSco yo locku n/non- locku nlmodO onsa stream=sçãoDTssl yo u need to dclass=section>

    Intream-sct-wimeout">itream_sct_wimeoutçãatd to dclass=seSco yo wimeout period onsa stream=sçãoDTssl yo u need to dclass=section>

    Intream-sct-write-buffer">itream_sct_write_bufferlaatd to dclass=seScoalyo cileubufferi nlonswf a=sectAitreamla< e libswf all you needtream-dclalxt-cr aaeallatitream_dclalxt_cr aaellon>

    Instalaçlass=4 .htm= 4.3.0nce yotream_dclalxt_cr aaed to dclass=seCreaseBa itreamsu dclalxtla

    Instalon>InstalaçãoCreases A>Inr

    r dea< anP> nssSee Also: sl you need to dclass=section>


    Intream-dclalxt-sct- you s">< name=swf.installatitream_dclalxt_sct_ you sction>

    Instalação

    Oe0,itream orlcintextiolass< you have libs wf all you needtream-dclalxt-sct-ostala>nstadtream_dclalxt_sct_ostalaçãon>


    Instalon>InstalaçãoScoalan ostala onswf amp

    Oe0,cintextiolbswbswf all you need to vlyueçãlaçãois metono lbswbswf all you need to ostalaçãlaçãofodA nass< you have libs wf all you needtream-dclalxt-sct- you s>nstadtream_dclalxt_sct_ you sçãon>


    Instalon>Instalaçãoibswwf all you need to you sçãlaçãosho bl b$ you s[' you u ne']f= " you vlyue";ção n

    Tabela 1.ePyou needsion>laçãoTHEAD>laçãoTR>laçãçãoTH vAyign=claserslyign=left>Pyou needsiooH>laçãçãoTH vAyign=claserslyign=left>Purpose<ãoH>laçãoTBODY>laçãoTR>laçãçãoTDsvAyign=claserslyign=left>ibswwf alllitere >notP>OcatalaçãolaçãçãoTDsvAyign=claserslyign=left>NamecoA uibr-d/fine0,callbackfl you neono bbl lçãçãcclAeInwheneveioa itream areggarOcatala. laTD>e you la
    e libswf all you needtream-cilter-appetd>nstadtream_cilter_appetdçãon>

    Instalon>InstalaçãoAddstoethe lisef amp

    Oe0,ibswwf all you need to you sçãlaçãotoethe In_pt_Bt>< nfo ne nacclAeInf at duru nlitream opperated s


    Intream-cilter-prepetd">< name=swf.installatitream_cilter_prepetdction>Nota: ion>ll yo u need to dclass=section>

    Intream-=sgc dar-cilter">< nam we=swf.installatitream_=sgc dar_cilterction>an
    A nssSee Also: sl you need to dclass=section>

    Intream-=sgc dar-cilter">< name=swf.installatitream_=sgc dar_cilterction>Inil you need to dclass=section>

    Intream-cilter-prepetd">< name=swf.installatitream_cilter_prepetdction>nstadtream_cilter_prepetdçãon>

    Instalon>InstalaçãoAddstoethe lisef amp

    Oe0,ibswwf all you need to you sçãlaçãotoethe In_pt_B t b nfo ne nacclAeInfirst


    Intream-cilter-appetd">< name=swf.installatitream_cilter_appetdction>Nota: ion>ll yo u need to dclass=section>

    Intream-=sgc dar-cilter">< nam we=swf.installatitream_=sgc dar_cilterction>an
    A nssSee Also: sl you need to dclass=section>

    Intream-=sgc dar-cilter">< name=swf.installatitream_=sgc dar_cilterction>Inil you need to dclass=section>

    Intream-cilter-appetd">< name=swf.installatitream_cilter_appetdction>nstadtream_gea_ciltersllon>

    Instalação

    laçãoTBODY>laçãoTR>laçãçãoTD>laçãçãção

    InstaçãçãçãosssB>Exemplo 1.eUs claHection>
    laçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    .ltm?>< nlmay beBmoranTD>e you anTD>sOnc=sessSee Also: sl you need to dclass=section>
    

    Intream-=sgc dar-cilter">< name=swf.installatitream_=sgc dar_cilterction>Inil you need to dclass=section>

    Intream-get-wrappers">< name=swf.installatitream_gea_wrappersction>nstadtream_gea_ nea_oatallon>

    Instalon>Instalação


    Icopet">< name=swf.installatcopet(tion>

    Icdockopet">< name=swf.installatcdockopet(tion>Inil you need to dclass=section>

    Ipcdockopet">< name=swf.installatpcdockopet(tion>(bool) -Tibswyo wf allcto dcla/H1>TRUE

    Icrsad">< nam wwf allinstallatcr ad( ion>

    Icgets">< nam wwf allinstallatcgetsction>(bool) -Tibswyo wf allcto dcla/H1>TRUE

    < nam we=swf.installatiockea_sct_ locku nction>(bool) -Tibswyo wf allcto dcla/H1>TRUEitreams n>is membeded>TRUEis non-zeio= T< la ldetermineHifay b ne

    Iceof">< nam wwf allinstallatceofc ion>(nst) -Ttse numbedeofobytnsoam wwurreasly dclaaite0,u aw blr adebuffer. lassanLlaçãULs=s(sared ) -Taal bel,d/A>Inbiclayo w e underlyed nimpleclasrefsecoA y bldtream. sOnc=sçãoLIs=s="namlbswwf all you need to wrapper_typeçãlação(sared ) -Taal bel,d/A>Inbiclayo w e hrotocolewrapper impleclasrefseclayared<

    ApêndOcne I(mixed) -Twrapper mp

    Ocola ldataoatss=he0,toAtsisodtream. See il yo u need to dclass=section>


    ApêndOcne IIntheirTwrapper oata. sOnc=sçãoLIs=s="namlbswwf all you need to cilterslllação(array) -TandNota: ion>T>

    < nam wwf allinstallatiockea_gea_statusc ion>fodbast0,itreamsuam wonlytalaçãSPAN1. sOnc=sçãoP>I aass=4.3Tand

    < nam wwf allinstallatiockea_gea_statusc ion> an
    A n

    Nota: ion>T>

    Sockea>yo exdasse=san
    e you have libswf all you needtream-get-Rrappers>nstadtream_gea_wrappersllon>

    Instalon>Instalação


    Intream-=sgc dar-wrapper">< name=swf.installatitream_=sgc dar_wrapperction>nstadtream_=sgc dar_cilterllon>

    >

    Instalaçãoiection>
    allows youoto impleclas yourl own cilterBla any regc dared suam(su=hBas il you need to dclass=section>

    Icopet">< name=swf.installatcopet(tion>

    Icrsad">< name=swf.installatcr ad( ion>> suas oefine0, nlow. Whenaperfss=ed ar ad/writeeopperated s =s y blstream wooR=ichayourlcilterB i Oe0,as oesired. You must impleclas y blall yos exaioly as oes>Inbtd,bnlow -Tdoed aothsrwisef_pt_Bl adeto undefine0,behaeiour. lass=sessiection>
    _pt_Brc

    osbswyo FALSEis alr adyedefine0. lassnsta< name=swf.all you neewritelllaçãohared adata)T>is mel yo>is cclAeInwheneveiooataois writdasBto y blatss=he0,stream (su=hB asuR


    Icwrite">< name=swf.installatcwritection>y claHbswbswf all you need to oatalllaçãoasune 0e0,yourlcilterBsho bl issue:rc

    o yolas::writec$data);çãoinãiesncinalafss=. l

    Nota: ion>If,yourlcilterBaltersot e leng < fod yolas::writec$data);çãoocnert. lass< BLOCKQUOTE>an
    A n

    laçãoTBODY>laçãoTR>laçãçãoTD>
    i=swf mycilterBexdasos >o($writdas_by_ yolaso+ 1);
     w}
    }anTD>lllaçlassan
    A nssce yotriclaHection> all you neer adlllaçãonstamaxleng <)
    T>is mel yo>is cclAeInwheneveiooataois r adefron y blatss=he0,stream (su=hBaso R

    Icrsad">< name=swf.installatcr ad( ion>>yolas::r ad($maxleng <);çãoy y bldataoasune 0e0,A>Inibswwf alllitere >r

    çãoomorbytns. Since sbswwf alllitere > yolas::r ad($maxleng <);çãoomorbytnsot> <_pt_Bnrdinarily beBaA non-issue. Howevei,HiA yourlcilterBincr ases y blsize,ofay bldataobeecla r

    td,ãyouosho bl eithsrscat_Bsbswyo >yolas::r ad($maxleng <-$x);çãois y blaost yourlcilterB_pt_Bgrow"t blsize,ofay bl dataor adioAlteru tsecly, youod> all you neeflushlllaçãoboolvclo>ed )T>is mel yo>is cclAeInu ar la seBto alrequestato flush y blatss=he0,stream am(su=hBas R


    Icflush">< name=swf.installatcflush( ion>

    Icclo>e">< name=swf.installatcclo>ec ion>ed <ãlaçãoA you needatells youo_ bthsrsy blstream is, in cact,,u aw blprocelseofaclo>ed . T bldefault>is yonsimply cclA:r

    oA yolas::flush($clo>ed );çãoI/orlcleatup cclAssprsor,toAorHdireioly afterBa succelsful flush. lassvoidaHection> all you neeoncr aaelllaçãovoid>T>is mel yo>is cclAeInduru nlio dclairefsecoA y blcilterBi=swf objtio= IfnamyourlcilterBallocatescy othsrsr dource (su=hBasoaebuffer),A th < all you neeonclose<ãlação void>T>is mel yo>is cclAeInua cilterBshutdown (typically, th < Inis execuseIniSPAN cclassemp=seis flushllois bswclAeI= Ifnany redource w neallocatedconcr aaello <_o bl brot13llofoo-bar.txtçãolaçãoTBODY>laçãoTR>laçãçãoTD>laçãçãção

    Exemplo 1. Filter>fodlaçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    .ltm?>yolas::r ad($leng
    <);am w  fod($i = 0; $i .ltmãstrlen($tempstr); $i++)laçãçãçãif (($tempstr[$i] .htm= 'A' AND $tempstr[$i] .ltm= 'M') ORlaçãçãçãçãçã($tempstr[$i] .htm= 'a' AND $tempstr[$i] .ltm= 'm')) $tempstr[$i] =Bihr(nrd($tempstr[$i])o+ 13);am w    elseãif (($tempstr[$i] .htm= 'N' AND $tempstr[$i] .ltm= 'Z') ORlaçãçãçãçãçããçãçã($tempstr[$i] .htm= 'n' AND $tempstr[$i] .ltm= 'z')) $tempstr[$i] =Bihr(nrd($tempstr[$i])o- 13);am w  r  

    o$tempstr; w} am wfnstallauwritec$data) {am w fod($i = 0; $i .ltmãstrlen($data); $i++)laçãçãçãif (($data[$i] .htm= 'A' AND $data[$i] .ltm= 'M') ORlaçãçãçãçãçã($data[$i] .htm= 'a' AND $data[$i] .ltm= 'm')) $data[$i] =Bihr(nrd($data[$i])o+ 13);am w elseãif (($data[$i] .htm= 'N' AND $data[$i] .ltm= 'Z') ORlaçãçãçãçãçããçãçã($data[$i] .htm= 'n' AND $data[$i] .ltm= 'z')) $data[$i] =Bihr(nrd($data[$i])o- 13);am w r

    o yolas::writec$data); w} } /* R gc darBourlcilterB_p ec$fp); /* T blcilterBonlyHappliesBto y bl$fpBIn>alseofarot13aencodu n aç*/ r adfile("coo-bar.txt"); /* Output * ------ Yvar1 Jbeqo- 2 Rnfl Nf<123 am */ ?.htmanTD>e you anTD>sOnc=sessSee Also: sl you need to dclass=section>


    Intream-=sgc dar-wrapper">< name=swf.installatitream_=sgc dar_wrapperction>

    Intream-cilter-prepetd">< name=swf.installatitream_cilter_prepetdction>Inil you need to dclass=section>

    Intream-cilter-appetd">< name=swf.installatitream_cilter_appetdction>nstadtream_=sgc dar_wrapper<ãon>

    Instalon>Instalaçãoiection>
    allows youoto impleclas yourl own hrotocolehA>Ilers,a>In

    Icopet">< name=swf.installatcopet(tion>

    Icrsad">< name=swf.installatcr ad( ion>a>Inthen,callInbtd,bnlow -Tdoed a othsrwisef_pt_Bl adeto undefine0,behaeiour. lass=sessiection>
    _pt_Brc

    osbswyo FALSEA alr adyehasaa hA>Iler. lassbooleatAs libswf all you needtream_opetlllaçãohared aA yth,lhared amodO,onstaostalas,ãhared aoseted_ yth)T>is mel yo>is cclAeInums=seately afterByourlis crease0. lbswbswf all you need to yth<ãlaçãomp

    Oe als 0,to il you need to dclass=section>


    Icopet">< name=swf.installatcopet(tion>

    a>Inthat y is objtio>is exp

    I yose-url">< name=swf.installat yose_url(tion>

    to reakoit"a yoa< anP> nssHbswwf all you need to modOçãlaçãois y blaod

    Icopet">< name=swf.installatcopet(tion>is valid coiot>neHbswbswf all you need to yth<ãlaçãorequeste0. lass nssHbswwf all you need to ostalaslllaçãoholos addiclasalaflags metoby the laçãoTHEAD>laçãoTR>laçãçãoTH vAyign=claserslyign=left>Flag<ãoH>laçãçãoTH vAyign=claserslyign=left>InstalaçãoH>laçãoTBODY>laçãoTR>laçãçãoTDsvAyign=claserslyign=left>STREAM_USE_PATHlaçãçãoTDsvAyign=claserslyign=left>IA sbswwf all you need to yth<ãlaçãoisuam w w r l tsec,ãhear=hBcoiot>ner dourcee=s clat>neinclude_ yth. laTD>laçãoTR>laçãçãoTDsvAyign=claserslyign=left>STREAM_REPORT_ERRORSlaçãçãoTDsvAyign=claserslyign=left>IA n>is flagfis sea,ãyouoareor la siote,coioam w w rais claerrorsf=s claHl yo lçãçãu need to dclass=section>

    Iareggar-error">< nam w w wwf allinstallatareggar_errorction>

    is flagfis .inssea,ãyouosho bl .insraisenanyAerrors. laTD>taisuopetedis metoinaHbswwf all you need to ostalaslllaçãoto y blfull yth,ofay bl cile/r dourceet at waseaiouallyuopeted. lass nssIA y blrequeste0er dourceewaseopetedosbswyo TRUEosbswyo FALSE all you needtream_close<ãlação void )T>is mel yo>is cclAeInwhen y blstream is closed, ui claHl you need to dclass=section>

    Icclo>e">< name=swf.installatcclo>ec ion> all you neeT>is mel yo>is cclAeInu ar la seBto il you need to dclass=section>

    Icrsad">< name=swf.installatcr ad( ion>Inil you need to dclass=section>

    Icgets">< name=swf.installatcgetsction>

    oup-to lbswbswf all you need to enertlllaçãobytnsoofadataofron wf awurreasBrcad/writeeA osiclasnasaa otricl= Ifnt b neareolewf y an lbswbswf all you need to enertlllaçãobytnsoavailaote, r

    oasamany asoareoamavailaote= Ifnnooeithsrssbswyo FALSEoemptyedared . You must also updaseBy bl rcad/writee osiclasnofay blstream,by the numbedeofobytnsot at w nesuccelsfullyl rcad. lassnsta< ntion> all you neeT>is mel yo>is cclAeInu ar la seBto il you need to dclass=section>


    Icwrite">< name=swf.installatcwritection>

    into y blunderlyed nsto agothe numbedeofobytnsot at w nesuccelsfullylsto n0,u aw blT>is mel yo>is cclAeInu ar la seBto il you need to dclass=section>

    Iceof">< name=swf.installatceofc ion>osbswyo TRUEInifnnoto nar ad, orssbswyo FALSET>is mel yo>is cclAeInu ar la seBto il you need to dclass=section>

    Ictell">< name=swf.installatctellc ion>oy bl wurreasBrcad/writee osiclasnofay blstream. lassbooleatAs lbswf allall you neeT>is mel yo>is cclAeInu ar la seBto il you need to dclass=section>

    Icseek">< name=swf.installatcseekc ion>a>InHbswwf all you need to whencelllação

    Icseek">< name=swf.installatcseekc ion>osbsw TRUEFALSET>is mel yo>is cclAeInu ar la seBto il you need to dclass=section>

    Icflush">< name=swf.installatcflush( ion>ito n0,ut>into y blunderlyed nsto ag<, youosho bl do soA now. Rc

    osbsw TRUEFALSEIlerot at allows rcad/writeeA accelsBto alass=sui cla dcldardscilesystema


    Icrsad">< name=swf.installatcr ad( ion>laçãoTBODY>laçãoTR>laçãçãoTD>laçãçãção

    Exemplo 1. A Stream corBrcading/writ claglobal variaotesion>laçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    cclas VariaoteStream {am w  var $ osiclas;am w  var $varname;am w am w  installaayose_url($ yth);am w      $t>is-.htmvarname = $url["host"];am w      $t>is-.htm osiclasn= 0;am w      am w      rc 

    oyrue;am w w} am w installaais-.htmvarname], $t>is-.htm osiclas, $enert);am w $t>is-.htm osiclasn+= o$r ;am w w} am w installaais-.htmvarname], 0, $t>is-.htm osiclas);am w $righ o= substrc$GLOBALS[$t>is-.htmvarname], $t>is-.htm osiclas + is-.htmvarname] = $lefto. $datao. $righ ;am w $t>is-.htm osiclasn+= oo$t>is-.htm osiclas; www} am w installaao$t>is-.htm osiclas .htm= is-.htmvarname]); www} am w installaais-.htmvarname])ã&& $offsea .htm= 0) {laçãçãçãçãããããããããããããã$t>is-.htm osiclasn= $offsea;laçãçãçãçããããããããããããããrc

    oyrue;am w wwwwwwwwwwwww} elseã{laçãçãçãçããããããããããããããrc

    ofalse;am w wwwwwwwwwwwww}am w wwwwwwwwwwwww reak;am w wwwwwwwwwwwwwlaçãçãçãçãããããcasenSEEK_CUR:laçãçãçãçãããããããããif ($offsea .htm= 0) {laçãçãçãçãããããããããããããã$t>is-.htm osiclasn+= $offsea;laçãçãçãçããããããããããããããrc

    oyrue;am w wwwwwwwwwwwww} elseã{laçãçãçãçããããããããããããããrc

    ofalse;am w wwwwwwwwwwwww}am w wwwwwwwwwwwww reak;am w wwwwwwwwwwwwwlaçãçãçãçãããããcasenSEEK_END:laçãçãçãçãããããããããif (strlen($GLOBALS[$t>is-.htmvarname])ã+ $offsea .htm= 0) {laçãçãçãçãããããããããããããã$t>is-.htm osiclasn= strlen($GLOBALS[$t>is-.htmvarname])ã+ $offsea;laçãçãçãçããããããããããããããrc

    oyrue;am w wwwwwwwwwwwww} elseã{laçãçãçãçããããããããããããããrc

    ofalse;am w wwwwwwwwwwwww}am w wwwwwwwwwwwww reak;am w wwwwwwwwwwwwwlaçãçãçãçãããããdefault:laçãçãçãçãããããããããrc

    ofalse;am w wwwww}am w w} } ec$fp); var_dump($myvar)manTD>e you anTD>sOnce you have libswf all you needtream-select>nstadtream_select<ãon>


    Oe0,by tv_sec>a>Intv uibc la

    Instalação all you nee[,onstaamtv uibc])T>eaHection>
    In_aiesncoiot>nm woochA>gis equivalestato t at ofay bl il you need to dclass=section>

    Inocket-sclect">< name=swf.installatiockea_sclect()<ãlaarrayc_pt_BR.h wat=he0,toAseeãif iharacters become availaote>corBrcading (mor

    Icrsad">< name=swf.installatcr ad( ion>oa zeio leng < sared ). sOnc=sessT blotreamf lisen0,u aw blHbswwf all you need to writelllaçãoarrayc_pt_BR.h wat=he0,toAseeãif aBwritee_pt_B.insblock. sOnc=sessT blotreamf lisen0,u aw blHbswwf all you need to excepalllaçãoarrayc_pt_B nawat=he0,fodlaçãoTBODY>laçãoTR>laçãçãoTDslyign=middle>AtençãolaçãoTR>laçãçãoTDslyign=left>am w wwwvssOn exct, y blarraysoareomodP>Oe0,to indOcaseB_=ichaitream r dourceeam w wwwaiouallyuchA>ge you havssYou do .insne 0,to >alseeveiy>arraycto iection>
    oemptyearraycNULLOe0,afterBHection>
    f. sOnc=sessExample: lTABLE cellPadding=5 bgColor=#e0e0e0 bnrdOn=0>laçãoTBODY>laçãoTR>laçãçãoTD>
    /* Pre yol y blrcadearrayc*/
    $rcade=earray($gIled l*/
    elseãif ($num_chA>gi nliotere d clahappeted<*/
    }anTD>sOnc=se
    

    Nota: ion>Duesa=limisrefsecu aw blwurreasBZctd EngineHite <.ins ossioteeam wto >alseaocoo dclahmodP>Oer=liknasbswwf alllto dcla/H1>NULL < you needato bnepswfeInby am wrcference. In d adnusOBa temporaiy>variaote>orBa>oexpr sse=s aleftaost am wmembedebeeclaa temporaiy>variaote: laçãoTABLE cellPadding=5 bgColor=#e0e0e0 bnrdOn=0>laçãçãoTBODY>laçãçãoTR>laçãçãçãoTD>
    anTD>e ss< BLOCKQUOTE>an
    A nP>T>eaHbswwf all you need to tv_seclllaçãoa>InHbswbswf all you need to tv uibc<ãlaçãotogbthsrafss=aw blHSPAN cclassemp=seis
    f. sbswbswf all you need to tv ibc<ãlaçãomay beBzeio ,od>us claHecame=swf.installatitream_select()<ãlaçto r

    oums=seately. T> isssbswyo NULL


    faw blnumbedeofoitream r dorce dclaaite0,u aw blmodP>Oe0,arrays,a_=ichamay beBzeio ifay blwimeout expiresnbnfo neanyt>i nliotere d clahappetf. On erroresbswyo FALSEn0. sOnc=se

    Nota: ion>BnesureBto usOBw blHbswwf alllitere >===çãoanTD>sOnc< BLOCKQUOTE>an
    A n

    Nota: ion>Bneawyol y at some itream impleclasrefsessne 0,to beBhA>Iled laçãveiy>cyolfullyioA cew>basic rules: laçãosssOnchaçãoULs=sçã ãoLIs=s="çãossYou sho bl alwaysotry yonuibssection>
    ficultato debug. sOnc=sçã ãoLIs=s="çãossIf,you rcad/writeeto alitream r

    n0,u aw blarraysobneawyol y at w by do .insnecelsarily rcad/writeethblfull amnert ofadada0you haecto rcad/writeealiingle,byte. sOnce LlaçãULs=sçãosssOnc< BLOCKQUOTE>an


    A nP>Sebsalso il you need to dclass=section>

    Intream-sct- locku n">< namtion>
    nstadtream_set_ locku n<ãon>

    nstalllaçlass=4 .htm= 4.3.0nce yotream_set_ locku nd to dclass=seSea>yo locku n/non- locku nlaod

    Instalação all you neeIfnHbswwf all you need to modOçãlaçãois sbswyo FALSEInifnsbsw TRUE

    Icgets">< name=swf.installatcgetsction>

    Inil you need to dclass=section>

    Icrsad">< name=swf.installatcr ad( ion>nil you need to dclass=section>

    Icgets">< name=swf.installatcgetsction>

    origh oawyyow ileuina locku nlaodos y blstream. sOnc=sessT i
    and

    Inocket-sct- locku n">< namtion>
    Nota: ion>Prsor,toAPss=4.3,et i bast0,=s="streams. Since Pss=4.3,et i yAstreamuy at supporesuam wnon- locku nlaodInitreams). lass< BLOCKQUOTE>an
    e you have libswf all you needtream-sct-yimeout>nstadtream_set_wimeoutllon>

    nstalllaçlass=4 .htm= 4.3.0nce yotream_set_wimeoutd to dclass=seSea>wimeout periodeona alitreamla

    nstalllon>Instalação all you neeIs,onstaaicrostio>Is)Setsay blwimeout vlyueeonaHbswwf all you need to itreamlalaçãoIslllaçãoa>InHbswbswf all you need to aicrostio>IslllaçãolaçãoTBODY>laçãoTR>laçãçãoTD>laçãçãção

    Exemplo 1. section>
    laçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    .ltm?>to opet\n";am} elseã{laçãçãfputsc$fp, "GET / HTTP/1.0\n\n");
    çãçã$ dcra,= wime();
    çãçãec$fp);
    çãçãprnsta$res;
    }
    ?.htmanTD>e you anTD>sOnc=se
    

    Nota: ion>AsoofaPss=4.3,et i yA=s="ku deofoitream. In Pss=4.3,esockea>bast0,itreamsuyol stit_Bt>an
    A nP>T>i

    Inocket-sct-wimeout">< namtion>
    Sebsalso: sl you need to dclass=section>

    Icdockopet">< name=swf.installatcdockopet(tion>

    Inil you need to dclass=section>

    Icopet">< name=swf.installatcopet(tion>nstadtream_set_write_bufferllon>

    Instalon>Instalação all you neeOutput ui claHl you need to dclass=section>

    Icwrite">< name=swf.installatcwritection>

    bytns= IfnHbswbswf all you need to bufferlllação <0aw bauwrite operated s areounbuffereI. T is ensuresot at at_BwritesuR

    Icwrite">< name=swf.installatcwritection>

    fa0Alauiuccels, orsEOFHiA y blrcquestad><.insblaçãoTBODY>laçãoTR>laçãçãoTD>laçãçãção

    Exemplo 1. section>
    laçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    $fpB= copet($cile,,"w");
    if ($fp) {laçãec$fp);
    }anTD>sOyou anTD>sOnc=seP>Sebsalso il you need to dclass=section>
    

    Icopet">< name=swf.installatcopet(tion>

    a>Inil you need to dclass=section>

    Icwrite">< name=swf.installatcwritection>

    Instal

    XCIX. Stru nlfnstallasllon>
    Instal

    InsIetrodução esta Algumasamaisuamemp

    URLe hA>Iled

    se sõef. sOnc=sessPyouAsecss=açõesadeowomoaa otricl>seowom ores, emp

    Stru ns

    deetroada>se são il you need to dclass=section>

    Typef

    do name=s. =Once you hav

    lahave 1 classctiollatInsRcquisitos lahave 1 classctiollat lahave 1 classctiollatInsCto dclaesaPreIefiniHR> lahave 1 classctiollatInsVeja Também

    POSIXo r gularsexpr sse=s fnstallasllH1"easl you need to dclass=section>

    Per_B wom ytioteer gularsexpr sse=s fnstallasllH1. =Once you la

    Ls=sçãoDTssB>ÍndOceion>=sçãoDTssl yo lu need to dclass=section>

    Iaddcsclahef">addcsclahefllH1d to dclass=seSared aA çãeetrneaspasewom barra <.iie d lo C =sçãoDTssl yo lu need to dclass=section>

    Iaddsclahef">addsclahefllH1d to dclass=seSared aA çãeetrneaspasewom barra =sçãoDTssl yo lu need to dclass=section>

    Ibin2hex">bin2hexllH1d to dclass=se yo lCtoveoae umadado binário emahexad

    Ichop">chopllH1d to dclass=seAliasuam wde sl yo lu need to dclass=section>

    Irarem">< nam wwf allinstallatraremction>


    Ichr">chrllH1d to dclass=seRetornaãyo lum,caracter,emp <ífico çãoDTssl yo lu need to dclass=section>

    Ichunk-split">chunk_splitllH1d to dclass=seDivideãyo luma otricl>emapcquenosu edaço =sçãoDTssl yo lu need to dclass=section>

    Ictoveoa-cyr-otricl">ctoveoa_cyr_otriclllH1d to dclass=se yo lCtoveoae delum,caracter,cirílicoc youooutroa çãoDTssl yo lu need to dclass=section>

    Icnert-ihars" enert_iharsllH1d to dclass=se yo lRetornaãsecss=açõesasob neos,caracteres usados,numa otricl> çãoDTssl yo lu need to dclass=section>

    Icrc32" erc32llH1d to dclass=seCalcula yo lpoledômioncrc32 deluma otricl çãoDTssl yo lu need to dclass=section>

    Icrypt">cryptllH1d to dclass=seÚnicocam wwaminhoadeowodP>Ocaçãosde sared (hlahed ) çãoDTssl yo lu need to dclass=section>

    Iecho">echollH1d to dclass=seExibeãyo luma ou maisusared s çãoDTssl yo lu need to dclass=section>

    Iexplode">explodellH1d to dclass=seDivideãyo luma otricl>emasared s çãoDTssl yo lu need to dclass=section>

    Ifprnstf">fprnstfllH1d to dclass=seWriteeA alfss=atteI string to alitream çãoDTssl yo lu need to dclass=section>

    Iget-alla-translaolla-esote">gea_alla_translaolla_esotellH1d to dclass=se yo lRetornaãa esoelasde araduçaõ usadaupor sl yo lu need to dclass=section>

    Iallamp

    e sl yo lu need to dclass=section>

    Iallalasities" < nam wwf allinstallatallalasities(tion>

    çãoDTssl yo lu need to dclass=section>

    Iheb nv">heb nvllH1d to dclass=se yo lCtoveoae texdo lógicocHeb aicoc youotexdo visual> çãoDTssl yo lu need to dclass=section>

    Iheb nvc">heb nvcllH1d to dclass=se yo lCtoveoae umatexdo lógicocHeb áicoc yououmatexdo visual>wom ctoveosão newline> çãoDTssl yo lu need to dclass=section>

    Ihlla-lasity-d alla_lasity_d R> easidades HTMLc youoos meus,caracteres çãoDTssl yo lu need to dclass=section>

    Ihllalasities" hllalasitiesllH1d to dclass=se yo lCtoveoae toHos os,caracteres youoHTMLclasities çãoDTssl yo lu need to dclass=section>

    Ihllamp

    Iimplode">implodellH1d to dclass=seJerta yo leleclasos deluma =atriz>emauma otricl çãoDTssl yo lu need to dclass=section>

    Ijoin">joinllH1d to dclass=seJerta yo leleclasos deluma =atriz>wom uma otricl çãoDTssl yo lu need to dclass=section>

    Ileectshtein">leectshteinllH1d to dclass=se yo lCalcula asdistância Leectshteinãeetrneduasusared sc çãoDTssl yo lu need to dclass=section>

    Ilocaltio>v">localtio>vllH1d to dclass=seObtémeA alsecss=açãoada>fss=ataçãosnumérOca çãoDTssl yo lu need to dclass=section>

    Ilarem">laremllH1d to dclass=se yo lRetiou whitespace do inícioada>stricl> çãoDTssl yo lu need to dclass=section>

    Imd5-cile">md5_cilellH1d to dclass=seCalculaee=s="hlah md5 delum,dado arquivo çãoDTssl yo lu need to dclass=section>

    Imd5">md5llH1d to dclass=seCalcula yo lhlah md5 deluma otricl çãoDTssl yo lu need to dclass=section>

    I neaphone">mneaphonellH1d to dclass=seCalcula yo la mneaphone key deluma otricl çãoDTssl yo lu need to dclass=section>

    I oney-fss=at">money_fss=atllH1d to dclass=seFss=ats yo la numbedeasaa wurreacy otricl çãoDTssl yo lu need to dclass=section>

    Inl-langsecs">nl_langsecsllH1d to dclass=se yo lRetornaãsecss=açãosde led uag çãoDTssl yo lu need to dclass=section>

    Inl2br">nl2brllH1d to dclass=se yo lInsb nequeb assde ledhuoHTMLcclaesade toHR> newlines>emauma otricl> çãoDTssl yo lu need to dclass=section>

    Inumbed-fss=at">numbed_fss=atllH1d to dclass=seFss=ata yo lum,númeio wom os milhare agrupados çãoDTssl yo lu need to dclass=section>

    Iord">ordllH1d to dclass=seRetornaãyo lo vlyor ASCII do caractere çãoDTssl yo lu need to dclass=section>

    Ipyose-otr"t yose_otrllH1d to dclass=seCtoveoae yo la otricl>emavariáveis çãoDTssl yo lu need to dclass=section>

    Iprnst"t rnstllH1d to dclass=seMootra yo luma otricl çãoDTssl yo lu need to dclass=section>

    Iprnstf">prnstfllH1d to dclass=seMootra yo luma otricl>fss=atada çãoDTssl yo lu need to dclass=section>

    Iquoted-prnstsote-d quoted_prnstsote_d quoted-prnstsotec yououma otricl>de 8 bit> çãoDTssl yo lu need to dclass=section>

    Iquotemnea">quotemneallH1d to dclass=seAdiciona yo luma barraãseveoaidacclaesados mela caracteres çãoDTssl yo lu need to dclass=section>

    Irarem">raremllH1d to dclass=se yo lRetiou espaço emab anco do fisalada>stricl> çãoDTssl yo lu need to dclass=section>

    Isetlocalt">setlocaltllH1d to dclass=seSea>yo elocal

    Isha1-cile">sha1_cilellH1d to dclass=seCalcula yo la hlah sha1 delum,arquivo çãoDTssl yo lu need to dclass=section>

    Isha1">sha1llH1d to dclass=seCalcula yo la hlah sha1 deluma otricl çãoDTssl yo lu need to dclass=section>

    Isimilar-texd">similar_texdllH1d to dclass=se yo lCalculateethblsimilarityHbntwectAywousared sc çãoDTssl yo lu need to dclass=section>

    Isnutdex">snutdexllH1d to dclass=seCalculaeeeam wthblsnutdex key of a otricl çãoDTssl yo lu need to dclass=section>

    Isprnstf">sprnstfllH1d to dclass=seRc

    oyo la fss=atteI string çãoDTssl yo lu need to dclass=section>


    Isscanf">sscanfllH1d to dclass=se yo lPyosesAseput fron a>stricl>accnrding to a fss=atc çãoDTssl yo lu need to dclass=section>

    Istr-pad">str_padllH1d to dclass=se yo lPyd a>stricl>to a ceoaain leng < çãoDTssl yo lu need to dclass=section>

    Istr-repeat">str_repeatllH1d to dclass=seRcpeatoyo la string çãoDTssl yo lu need to dclass=section>

    Istr-replace">str_replacellH1d to dclass=se yo lReplace at_Bocwurreacnsoofathblsear=hBstricl> areplaceclassstricl> çãoDTssl yo lu need to dclass=section>

    Istr-rot13">str_rot13llH1d to dclass=sePerfss=aam wthblrot13 transfss=alaaalitring çãoDTssl yo lu need to dclass=section>

    Istr-shuffle">str_shufflellH1d to dclass=seRandomly am wshufflesaalitring çãoDTssl yo lu need to dclass=section>

    Istr-wnrd-enert">str_wnrd_enertllH1d to dclass=se yo lRet

    ouecss=atala about wnrdsAuf 0,iaaalitring> çãoDTssl yo lu need to dclass=section>


    Istrcasecmp">strcasecmpllH1d to dclass=se yo lBisary safeacase-insbnsiclve sared wom yois=s çãoDTssl yo lu need to dclass=section>

    Istrchr">strchrllH1d to dclass=se yo lEndclaraaa remeirRBocorrência delum,caractere> çãoDTssl yo lu need to dclass=section>

    Istrcmp">strcmpllH1d to dclass=seCom yoaçãosyo lde sared segurac youobinário çãoDTssl yo lu need to dclass=section>

    Istrcoll">strcollllH1d to dclass=seCom yoaçãosyo lde sared bastadaunoelocal çãoDTssl yo lu need to dclass=section>

    Istrcspn">strcspnllH1d to dclass=se yo lEndclaraao tanamho do segclaso ini çãoDTssl yo lu need to dclass=section>

    Istrip-tags">strip_tagsllH1d to dclass=seRc ira> çãas tagsoHTMLcllass=deluma otricl çãoDTssl yo lu need to dclass=section>

    Istripcsclahef">stripcsclahefllH1d to dclass=se yo lDesfazao efeito de sl yo lu need to dclass=section>

    Iaddcsclahef">< nam wwf allinstallataddcsclahef(tion>

    çãoDTssl yo lu need to dclass=section>

    Istripsclahef">stripsclahefllH1d to dclass=se yo lDesfazao efeito de sl yo lu need to dclass=section>

    Iaddsclahef">< nam wwf allinstallataddsclahef(tion>

    çãoDTssl yo lu need to dclass=section>

    Istristr">stristrllH1d to dclass=se yo lCase-insbnsiclve sl yo lu need to dclass=section>

    Istrstr">< nam wwf allinstallatstrstr(tion>

    çãoDTssl yo lu need to dclass=section>

    Istrlen">strlenllH1d to dclass=seRetornaãyo lo tanamho deluma otricl çãoDTssl yo lu need to dclass=section>

    Istrnatcasecmp">strnatcasecmpllH1d to dclass=se yo lCase insbnsiclve sared wom yois=ss ui claa "natura_BordOn" atgorithm> çãoDTssl yo lu need to dclass=section>

    Istrnatcmp">strnatcmpllH1d to dclass=se yo lSared wom yois=ss ui claa "natura_BordOn" atgorithm> çãoDTssl yo lu need to dclass=section>

    Istrncasecmp">strncasecmpllH1d to dclass=se yo lBisary safeacase-insbnsiclve sared wom yois=s ofathblfirst n iharacters çãoDTssl yo lu need to dclass=section>

    Istrncmp">strncmpllH1d to dclass=se yo lBisary safeasared wom yois=s ofathblfirst n iharacters çãoDTssl yo lu need to dclass=section>

    Istrpof">strpofllH1d to dclass=se yo lFu de osiclasnofafirst ocwurreacn of a otricl çãoDTssl yo lu need to dclass=section>

    Istrrchr">strrchrllH1d to dclass=se yo lFu dethbllast ocwurreacn of a iharacter,iaaalitring> çãoDTssl yo lu need to dclass=section>

    Istr nv">str nvllH1d to dclass=seReveose yo la otricl çãoDTssl yo lu need to dclass=section>

    Istr pof">strrpofllH1d to dclass=se yo lFu de osiclasnofalast ocwurreacn of a ihar,iaaalitring> çãoDTssl yo lu need to dclass=section>

    Istrspn">strspnllH1d to dclass=se yo lFu deleng < of initPe esegclas =atching =ask> çãoDTssl yo lu need to dclass=section>

    Istrstr">strstrllH1d to dclass=seFu de=s="first ocwurreacn of a otricl çãoDTssl yo lu need to dclass=section>

    Istrtok">strtokllH1d to dclass=seTokenize yo lotricl çãoDTssl yo lu need to dclass=section>

    Istrtolowtr">strtolowtrllH1d to dclass=seMake yo la otricl>lowtrcase çãoDTssl yo lu need to dclass=section>

    Istrtoupper">strtoupperllH1d to dclass=seMake yo la otricl>uppercase çãoDTssl yo lu need to dclass=section>

    Istrtr">strtrllH1d to dclass=seTranslaoe yo lceoaain iharacters çãoDTssl yo lu need to dclass=section>

    Isubstr-enert">substr_enertllH1d to dclass=seCnert yo lt blnumbedeofoiubstricl>ocwurreacns çãoDTssl yo lu need to dclass=section>

    Isubstr-replace">substr_replacellH1d to dclass=seReplace yo ltext>

    Isubstr">substrllH1d to dclass=seRet

    oyo l yoanofaa otricl çãoDTssl yo lu need to dclass=section>


    Itrem">tremllH1d to dclass=se yo lStrip whitespace fron wf abeginn claa dee deofoalitring> çãoDTssl yo lu need to dclass=section>

    Iucfirst">ucfirstllH1d to dclass=seMake yo la otricl's"first iharacter,uppercase çãoDTssl yo lu need to dclass=section>

    Iucwnrds">ucwnrdsllH1d to dclass=se yo lUppercaseathblfirst iharacter,ofoes=hBwnrd,iaaalitring> çãoDTssl yo lu need to dclass=section>

    Ivprnstf">vprnstfllH1d to dclass=seOutput yo la fss=atteI string çãoDTssl yo lu need to dclass=section>

    Ivsprnstf">vsprnstfllH1d to dclass=seRc

    oyo la fss=atteI string çãoDTssl yo lu need to dclass=section>


    Iwnrdwrap">wnrdwrapllH1d to dclass=se yo lWrapsaalitring>to a =sectAnumbedeofoiharacters ui claa itring> reakoiharacter.> ção/DTss/DLce you la
    e libswf all you neeaddcsclahef>

    eetrneaspasewom barra <.iie d lo C la

    Inçãoitring>< ntion> all you neeaddcsclaheflllaçãoitring>itr,A itring>iharlise)Retornaãuma otricl>wom barra \nção\rçãoetc= Como<.iie d lo C,A caracteres .iicódigo ASCII claores que 32 e maiores que 126 são dclveoaido < you r pr slassçãosoctad Elesaserão dclveoaido < you \0, \a, \b, \f, \n, \r,A\t e \v.>NoAPss=\0 (sbswyo NULL,>eequaaso em C toHR> elsas são seqüencias oe emcapeepreIefiniHR>. sOnc=sessHbswwf all you need to iharliselllaçãolaçãoTBODY>laçãoTR>laçãçãoTD>laçãçãção

    nstallçãçãçãosssB>Exemplo 1. section>
    addcsclahef(tion> exemploion>laçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    $emcapede=eaddcsclahef($not_emcaped,a"\0..\37!@\177..\377")manTD>e you anTD>sOnc=sessQuandoavocê Iefineluma oeqüenciaadeowaracteres .iiarg claso>iharlisewyo
    eoaifique-se que você sabe que
    InstalsssOnchavTABLE cellPadding=5 bgColor=#e0e0e0 bnrdOn=0>laçãoTBODY>laçãoTR>laçãçãoTD>
    echo addcsclahef('foo[ ]', 'A..z');
    //coutput:  \f\o\o\[ \]
    //cAll upper andyAtab>,>line
    //cfeeIs,ocarriugeurc 

    f,>etc=anTD>talsssOnce you Também,ãhe o remeiro caracter .iiiotervlyo temaum vlyor ASCII claoradolque o segundo,snenhumiiotervlyo será lto druído. Apena


    < name=swf.installatord(tion>

    you endclararlo vlyor ASCII yououmacaracter. l

    laçãoTBODY>laçãoTR>laçãçãoTD>
    echo addcsclahef("zoo['.']", 'z..A');
    //coutput:  \zoo['\.']anTD>talsssOnce you iolaçsOnchavPsVeja também il you need to dclass=section>
    

    Intripcsclahef">secame=swf.installatitripcsclahef(tion>

    Intripsclahef">secame=swf.installatitripsclahef(tion>

    Iallamp

    Iquotemnea">< namwf allinstallatquotemnea(tion>

    eetrneaspasewom barra la

    Inçãoitring>< ntion> all you neeaddsclaheflllaçãoitring> itr)Retornaãuma otricl>wom barra eetrneaspasenuma pesquisa ao banco de,dados e>etc= Esaesacaracteres emdãosyowom aspasesimples (sbswwf alllitere >'ção"ção\çãoNUL (o ibswyo NULLbytn). sOnc=se

    Nota: ion>sl yo lu need to dclass=section>

    magic_quotes_gpc

    yo lemdá ONupor Iefinição. sOnce BLOCKQUOTE>an
    A nP>veja também il you need to dclass=section>

    Intripsclahef">secame=swf.installatitripsclahef(tion>

    Iallamp

    Iquotemnea">< namwf allinstallatquotemnea(tion>

    nstalllaçlass=3.htm= 3.0.9, ass=4 nce ybin2hexd to dclass=se Ctoveoae umadado binário emahexad

    Inçãoitring>< ntion> all you neebin2hexlllaçãoitring>itr)Retornaãuma otricl>ASCII uma r pr slassçãoshexad bytn-wiseowomlo high-nibblee remeiro. sOnc=sessVeja também il you need to dclass=section>

    Ipack">< namwf allinstallatpack(tion>

    e sl you need to dclass=section>

    Iunpack">< namwf allinstallatunpack(tion>


    Irarem">< namwf allinstallatraremction>

    Inção

    Irarem">< namwf allinstallatraremction>Nota: ion>section>
    chop(tion> é dP>erenae dau chop(tiooan
    e you have libswf all you neechr>

    nstalllaçlass=3, ass=4 nce ychrd to dclass=seRc ornaãum,caracter,emp <íficola

    Inçãoitring>< ntion> all you neechrlllaçãonstaascii)Retornaãuma otricl>delum,únicoccaractere>dclaeddo o,caracter,emp

    Ocado peloaHbswwf all you need to asciilllaçãolaçãoTBODY>laçãoTR>laçãçãoTD>laçãçãção

    Exemplo 1. section>
    chr(tion> exemploion>laçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    $otr .= chr(27); /* addBanaemcapeeiharacter,at w bee deofo$otr */laha/* OftctAy is 
    anTD>e you anTD>sOnc=sessVocê  ode endclararluma esoelasASCII-esotecaqui: sl you need to dclwww.asciiesote.com/" esrget=_top> to dclwww.asciiesote.com/
    

    < name=swf.installatord(tion>

    Inprnstf">secame=swf.installatiprnstf(tion>

    wom uma otricl .iifss=atoadenHbswbswf alllitere >%cção

    Instalaçlass=3.htm= 3.0.6, ass=4 nce ychunk_splitd to dclass=seDivideãuma otricl>ema pequenosu edaço la

    nstalllon>Inçãoitring>< ntion> all you neechunk_splitlllaçãoitring>body [, nstachunklctA[, sared etd]])Pode dividirãuma otricl>emapequenosu edaço ãque são úte < you e.l. dclveoaer,swfl you need to dclass=section>

    Ibast64-endcde">bast64_endcde

    yooutput you wom ytioi izar wom semântOcas RFC 2045 . Ela insb neHbswbswf all you need to etdlllaçãodeixandoaa otricl>origisalanstocada. lTABLE cclassEXAMPLE cellSpaci n=0 cellPadding=0lction="100%" bnrdOn=0>laçãoTBODY>laçãoTR>laçãçãoTD>laçãçãção

    Exemplo 1. section>
    chunk_split(tion> exemploion>laçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    # fss=atc$dada0ui claRFC 2045 semclaicslaha$new_otricl = chunk_split(bast64_endcde($dada));anTD>e you anTD>sOnc=sessVeja também il you need to dclass=section>
    

    Iexplode">secame=swf.installatexplode(tion>

    Inplit">secame=swf.installatiplit(tion>

    il you need to dclass=section>

    Iwnrdwrap">secame=swf.installatwnrdwrap(tion>

    e sl you need to dclwww.faqseorg/rfcs/rfc2045talla" esrget=_top>RFC 2045

    Instalsslass=3.htm= 3.0.6, ass=4 nce yctoveoa_cyr_otricld to dclass=se Ctoveoae delum, caracter,cirílicoc youooutroala

    Inçãoitring>< ntion> all you neectoveoa_cyr_otricllllaçãoitring> itr, sared fron, sared to)Estau dada cclveoaida delum,caracter,cirílicoc youoyooutro. Osiarg clasosaHbswwf all you need to fronlllaçãoCirílicocde de d no. Ositipos mu oresdos são: olaçsOnchavULs=sçãoLI>=s="hssk - koi8-r =s="hssw - windows-1251 =s="hssi - iso8859-5 =s="hssa - x-cp866 =s="hssd - x-cp866 =s="hssm - x-mac-cyrillic =Once LlaçãULs=slsssOnce you iole libswf all you neectert-ihars>

    la

    Inçãomixed>< ntion> all you neectert_iharslllaçãoitring>itring>[, nstamode])Ctotaao númeio de ocorrênciasadeowada bytn-value (0..255) .a Hbswbswf all you need to stricllllação Oc yoâallroayoorigisalaHbswwf all you need to Mcde
    ctert_ihars(tion> ode r tornaroos meguiotes: olaçsOnchavULs=sçãoLI>=s="hss0 - Uma =atriz>wom um bytn-value womoaihave eBa reqüênciaadeowada bytn =s="womoavlyor. =s="hss1 - mesmolque o 0 =as apena . sOnc=sçãoLI>=s="hss2 - mesmolque 0 =as apena . sOnc=sçãoLI>=s="hss3 - uma otricl>wolaeddo toHos os,bytn-valueseusados. sOnc=sçãoLI>=s="hss4 - uma otricl>wolaeddo toHos os,bytn-valueseque não csssmlusados. sOnce LlaçãULs=slsssOnce you iole libswf all you neecrc32>

    nstalllaçlass=4 .htm= 4.0.1nce ycrc32d to dclass=seCalcula poledômioncrc32 deluma itringla

    Inçãonsta< ntion> all you neecrc32lllaçãoitring>itr)Geraao poledômioncyclic redundaacy checksumade 32-bit>deowom remeaso>dolHbswbswf all you need to strlllação

    Imd5">secame=swf.installatmd5(tion>

    iOnce you iole libswf all you neecrypt>

    Ocaçãosde sared (hlahed )la

    Inçãoitring>< ntion> all you neecryptlllaçãoitring>itrA[, sared ialt])section>
    crypt(tion> r tornará uma otricl>wriptografada usaddo o, atgoritmosde endriptaçãosUnix Staddard> abb nv>DES-bastd ou ou atgoritmos altarnativos disponíveis .iisiseemc. Osiarg clasosasão uma otricl> youoopcionalc youobastar>emaqe=sBendriptaçãos está. Veja a págisasde endriptaçãosUnix youomaisuiecss=ação. sOnc=sessSe o arg claso>ialt não é cssnecido,sum,arg claso>aleatório será geredo peloa ass. sOnc=sessAlguns SO mu oresmomaisude umatipoadeowodP>Ocação. De fato,salgumasavezesaalyowodP>OcaçãosStaddard>DES-bastd éoiubstituídoopor MD5-bastd OctipoadeoyowodP>Ocaçãosé Iefinido peloaarg claso>ialt. Na ie dclação, olass=detarmisasasuam ossíveis fnsçõesaoe wodP>OcaçãoseBaceitará ialtsc youooutrositipos. Se nenhumi ialt é cssnecido,solass=auto-gere umaialt padrão oe 2 caracaaeresopor Iefinição, a claoslque o tipoadeowodP>Ocação padrão oiisiseemc seja MD5,snesseacaso umaialt MD5-wom ytiotecaleatório será geredo Ocass=defineluma lto dclaeowomlnome CRYPT_SALT_LENGTHlque dirá ie umaialt oe 2 caracaeresoaplica-se ao seuisiseemc yoouãhe o ialt maisuwom redoadeo12 caracaeresoéoaplicavél. sOnc=sessSe você emtá usaddo umaialt cssnecido,svocê emtá cienae que o salt é geredo umc vez. Se você emtá chanamdo elsau DES-bastd section>
    crypt(tion> r torna o salt womoao premeiro ywouiharacters da>saída. Etectambém usa apena eedãosotricls longas que começamowomlos mesmos oito caracaeresogererão o mesmolresulesdo (quaddo o,mesmol ialt é usado). sOnc=sessEmisiseemcs ondOBa Ocação,sasuammeguiotes fnsçõesasão oefiniHR>c youo0 ou 1 a depetderase umadado tipoaemtá disponível: sOnc=sessHOnchavULs=sçãoLI>=s="hssCRYPT_STD_DES - CodP>OcaçãosStaddard>DES-bastd wom um ialt oe 2 caracaereso=s="hOnc=sçãoLI>=s="hssCRYPT_EXT_DES - CodP>OcaçãosExdasded>DES-bastd wom um ialt oe 9 caracaaereso=s="hOnc=sçãoLI>=s="hssCRYPT_MD5 - CodP>OcaçãosMD5 wom um ialt oe 12 caracaeresocomeçando com $1$o=s="hOnc=sçãoLI>=s="hssCRYPT_BLOWFISH - CodP>OcaçãosBlowfish wom um ialt oe 16 caracaereso=s="começando com $2$ =Once LlaçãULs=sl

    Nota: ion>Não hás Ocação,sdesde que < nam wwf allinstallatcrypt(tion> uti izaluma atgorimo delum sóccaminho. lass< BLOCKQUOTE>an
    lTABLE cclassEXAMPLE cellSpaci n=0 cellPadding=0lction="100%" bnrdOn=0>laçãoTBODY>laçãoTR>laçãçãoTD>laçãçãção

    Exemplo 1. section>
    crypt(tion> exemplosion>laçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    <?>a
    # plaswnrd,>to avoid prootems when dP>>erena hlahed  atgorithmsiarneusld. (As
    # it iays above, saaddard>DES-bastd plaswnrd,hlahed  usesaal2-iharacter,ialt,
    # but MD5-bastd hlahed  usesa12.)
    if (crypt($user_seput,$plaswnrd) == $plaswnrd) {laçãçecho "Plaswnrd,verified!";
    }
    ?.htmanTD>e you anTD>=sessVeja também il you need to dclass=section>
    

    Imd5">secame=swf.installatmd5(tion>

    easl you need to dclass=section>

    w be Mcrypt extbnsion

    nstalllaçlass=3, ass=4 nce yechod to dclass=seExibeãuma ou maisusared sla

    Inção< ntion> all you neeecholllaçãoitring>arg1A[, sared argn...])ExibeãtoHos os, yrãallro>. sOnc=sessHection>
    echo(tion> não é uma eedãosnão é obrigatório usar yoênteses. De fato,sseavocê quer plasar,swmaisudolque um yoâallroa you echo,svocê não deve feihar,os, yrênteses deetroade> yoênteses. Não é ossível usar Hection>
    echo(tion> num>wolaexto de sl you need to dclass=section>

    s.variaote-ion>s">variaote yoion>

    Iprnst"t< namwf allinstallatprnst(tion>

    noelugar Iela. lTABLE cclassEXAMPLE cellSpaci n=0 cellPadding=0lction="100%" bnrdOn=0>laçãoTBODY>laçãoTR>laçãçãoTD>laçãçãção

    Exemplo 1. section>
    echo(tion> exemplosion>laçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    <?>lines. Theanewlines>_pt_BR.hyooutput asawell";
    
    echo "T is spans\nmuleiple>lines. Theanewlines>_pt_BR.\noutput asawell.";
    
    echo "Emcapicl>wharacters isudone \"LikeAy is\".";
    
    //Youãcan use variaotesuiesideãofoançecho saateclas
    $foo,= "foobar";
    $bar,= "barbaz";
    
    echo "foo,isu$foo"; //cfoo,isufoobar
    
    // Ui clai clle>quotes>_pt_Bprnst w bevariaote name,>not w bevalue
    echo 'foo,isu$foo'; //cfoo,isu$foo
    
    // If youãarnenot ui claany othsrswharacters, youãcan justçecho variaotes
    echo $foo;çãçãçãçãçã//cfoobar
    echo $foo,$bar;ãçãçã//cfoobarbarbaz
    
    echo <<<END
    T is usesaw be"here>dH1 clas" syassx>to output
    muleiple>lines>
    
    Note
    that w behere>dH1 clas tarmisator mustçapptar>la a
    lede>
    
    
    
    ,cfollowicl>wodeãisuievalid. 
    ($some_var) ? echo('drue'): echo('false');
    
    // Howeveo,athblfollowicl>examples>_pt_Bwnrk:
    ($some_var) ? prnst('drue'): prnst('false');ã//cprnst isBa 
    
    echo $some_var ? 'drue': 'false';ã//cwhangseg w beiaateclasãarnutd ?.htmanTD>e you anTD>sOnc=sessHection>
    echo(tion> também temauma onstsxe wurta, ondOBvocê ode ammeguir is=seatamenae a tal>delabertura wom um iisalad aige=s. l

    InstalsssOnc=seTABLE cellPadding=5 bgColor=#e0e0e0 bnrdOn=0>laçãoTBODY>laçãoTR>laçãçãoTD>
    I have <?=$foo?.htmcfoo=anTD>talsssOnce you talsssOnc=se
    

    Nota: ion>Emtá onstsxe wurta apena

    hhort_open_tag

    yo lemdá haoi itada. lass< BLOCKQUOTE>an
    lssVeja também il you need to dclass=section>

    Iprnst"t< namwf allinstallatprnst(tion>

    Iprnstf">secame=swf.installatprnstf(tion>

    Iflush">secame=swf.installatflush(tion>

    Instalsslass=3, ass=4 nce yexploded to dclass=seDivideãuma otricl>emasared sla

    Inçãoarray>< ntion> all you neeexplodelllaçãoitring>ie youtor,A itring>itring>[, nst limit])Retornaãuma =atriz>de sared s,ocadaluma ltmooiubstricl>denHbswbswf all you need to stricllllação frolaeirR> pr slase> nelaaHbswwf all you need to se youtorlllaçãor tornada cclterá ol máximo delHbswwf all you need to limitlllaçãovazia (""), Hection>
    explode(tion> r tornará Hbswwf alllto dcla/H1>FALSEion>eedãossecame=swf.installatexplode(tion> r tornará uma =atriz>wolaeddo a Hbswbswf all you need to stricllllaçãoNota: ion>Oc yoâallroaHbswwf all you need to limitlllaçãoyo ladicionado<.iiass=4.0.1 lass< BLOCKQUOTE>an
    lss lTABLE cclassEXAMPLE cellSpaci n=0 cellPadding=0lction="100%" bnrdOn=0>laçãoTBODY>laçãoTR>laçãçãoTD>laçãçãção

    nstallçãçãçãosssB>Exemplo 1. section>
    explode(tion> exemplosion>laçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    $pizza,= "piece1 piece2 piece3 piece4 piece5 piece6";
    $pieces,= explode(" ", $pizza);
    
    $dada0= "foo:*:1023:1000::/home/foo:/bin/sh";yolise($user,$plas,$uid,$gid,$gecos,$home,$shell),= explode(":",$dada)manTD>e you anTD>sOnc=se
    

    Nota: ion>Aindaaque

    secam wwf allinstallatimplode(tion>

    ode por razõesa istóricas aceitar seuso=s=" yoâallros>emauma HR>cducs ordO>f,>section>
    explode(tion> não ode.> çãVocê Ievneassegurar que o arg claso>Hbswwf all you need to se youtorlllaçãoHbswwf all you need to stricllllaçãoan
    lssVeja também il you need to dclass=section>

    Ipreg-nplit">secame=swf.installatpreg_iplit(tion>

    Inpliti">secame=swf.installatipliti(tion>

    Inplit">secame=swf.installatiplit(tion>

    Iimplode">secamwf allinstallatimplode(tion>

    to a itreamla

    Inpnsta< ntion> all you neefprnstflllaçãor source handle,A itring>fss=atc[, mixed>args])Wriae a itring>produced>accnrding to thblfos=atting>itring>Hbswbswf all you need to fos=atlllaçãoOed>by>Hbswbswf all you need to handlelllaçãoitring>isuwom ostd of zeio or mo nedirtioives: nrdinary iharacters (excluding>Hbswwf alllitere >%<ãodcpOed>dirtioly to thblresule, and<=seSPANction> emphasis toction> emphasis ctoveos/A> mp

    OcaslllaçãSPAN>,A es=hBof whi=hBresulesoin fetching iesoown you need. ThisBappliesawossecame=swf.installatfprnstf(tion>, il you need to dclass=section>


    Inprnstf">secame=swf.installatiprnstf(tion>

    Iprnstf">secame=swf.installatprnstf(tion> mp

    Oca lto istseofoalperclasãsign (sbswyo %<ãoby>one or mo neofathbse eleclass, nsBordOn: olaçsOnchavOL type=1s=s="hLI>=s="hssAsBopalaHSPANction> emphasis toction> emphasis padding çãmp

    OerlllaçãSPAN> that iays what iharacter,_pt_BR.huf 0,css padding w be Bresulesoto thblright>itring>size. ThisBmayBR.ha space iharacter,or a Hbswbs wf alllitere >0çãoisuto pad> oyo laltarnate padding iharacter,can be mp

    Oed>by>prefixing ie yo lquote (sbswwf alllitere >'çãobelow. sOnc=sçãoLI>=s="hssAsBopalaHSPANction> emphasis toction> emphasis alignclasã çãmp

    OerlllaçãSPAN> that iays if thblresuleãhhould bealeft-justP>Oed>ore Bright-justP>Oed. TheaIefaule>isuright-justP>Oed; a>Hbswwf alllitere >-ção_pt_Bmake ie left-justP>Oed. sOnc=sçãoLI>=s="hssAsBopalanumbed, a HSPANction> emphasis toction> emphasis ctionã çãmp

    OerlllaçãSPAN> that iays howamany iharacters (minimum)Ay is ctoveos/A> çãmhould resuleãin. sOnc=sçãoLI>=s="hssAsBopalaHSPANction> emphasis toction> emphasis pr çãmp

    OerlllaçãSPAN> that iays howamany d hla<.iiefftio,css othsrstypesaw an


    secam wwf alltype>floation>numbeds>isu=s="hl yo lu need to dclass=section>

    secam wwf allinstallatnumbed_fos=at(tion>=s="hssAaHSPANction> emphasis toction> emphasis typeãmp

    OerlllaçãSPAN> that çãmays what typeãthblarg clas dada0hhould beatreateI R>. Possiotectypes: =s="hsssOnc=sçãoTABLE bnrdOn=0>laçãçãoTBODY>laçãçãoTR>laçãçãçãoTD>%<ãoNo arg clas laçãçãçã >isurequirtd. sOTD>laçãçãoTR>laçãçãçãoTD>b<ãooançioteger,A çãçãçã >andoa binary numbed. sOTD>laçãçãoTR>laçãçãçãoTD>c<ãooançioteger,A çãçãçã >andothbliharacter,_ponãthat ASCII value. sOTD>laçãçãoTR>laçãçãçãoTD>d<ãooançioteger,A çãçãçã >andoa (signed) d laçãçãoTR>laçãçãçãoTD>u<ãooançioteger,A çãçãçã >andoaaeunsigned d laçãçãoTR>laçãçãçãoTD>f<ãooa"hl yo lllllllu need to dclass=section>


    secam wwwwwwwwf alltype>floation>andoa floating-ponstanumbed.cam wwwsOTD>laçãçãoTR>laçãçãçãoTD>o<ãooançioteger,A çãçãçã >andoaaeoctalanumbed. sOTD>laçãçãoTR>laçãçãçãoTD>s<ãooandasaalitring. sOTD>laçãçãoTR>laçãçãçãoTD>x<ãooançioteger and<=sçãçãçã >pr slaseI R>oa hexad laçãçãoTR>laçãçãçãoTD>X<ãooançioteger and<=sçãçãçã >pr slaseI R>oa hexad ta="hsssOnc=sçãosssOnce LlaçãOLs=slsssOnc=sessSeecalso: sl you need to dclass=section>

    Iprnstf">secame=swf.installatprnstf(tion>

    Inprnstf">secame=swf.installatiprnstf(tion>

    Inscanf">secame=swf.installatiscanf(tion>

    Ifscanf">secame=swf.installatfscanf(tion>

    Ivnprnstf">secame=swf.installatviprnstf(tion>

    Inumbed-fos=at">secamwf allinstallatnumbed_fos=at(tion>InstalH2>Examples laçãoTBODY>laçãoTR>laçãçãoTD>laçãçãção

    nstallçãçãçãosssB>Exemplo 1. sl yo lllllu need to dclass=section>

    Inprnstf">secam llllle=swf.installatiprnstf(tion>laçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    $isodate = sprnstf("%04d-%02d-%02d", $year,A$month,c$day)manTD>e you anTD>
    lTABLE cclassEXAMPLE cellSpaci n=0 cellPadding=0lction="100%" bnrdOn=0>laçãoTBODY>laçãoTR>laçãçãoTD>laçãçãção
    

    Exemplo 2. sl yo lllllu need to dclass=section>

    Inprnstf">secam llllle=swf.installatiprnstf(tion>wurreacyion>laçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    $money1 = 68.75;
    $money2 = 54.35;
    $money = $money1 + $money2;
    //cecho $money _pt_Boutput "123.1";
    $fss=atteI = sprnstf("%01.2f", $money);
    //cecho $fss=atteI _pt_Boutput "123.10"anTD>e you anTD>sOnce you have libs
    wf all you neeget-alla-translao ne-esote>
    

    traduçaõ usadal or

    Iallamp

    Iallalasitief">secame=swf.installatallalasitief(tion>Inçãoitring>< ntion> all you neeget_alla_translao ne_esotelllação nstaesotec[, nst quote_style])section>
    get_alla_translao ne_esote(tion> r tornará a esoelasde> traduçãolque é usadalioteru nenae or

    Iallamp

    Iallalasitief">secame=swf.installatallalasitief(tion>c(sbswyo

    sbswyo

    Ocar a esoelas que você quer. E ctmoona

    Iallamp

    Iallalasitief">secame=swf.installatallalasitief(tion>Ocar a quote_style que você emtá arabalhando Ocpadrão éamodo ENT_COMPAT. Veja a deA>InçãosdessesamoHos em il you need to dclass=section>

    Iallamp laçãoTBODY>laçãoTR>laçãçãoTD>laçãçãção

    Exemplo 1. Exemplo de esoelasde>traduçãoion>laçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    $trans = get_alla_translao ne_esote(HTML_ENTITIES);
    $otr = "Hallo & <Frau.htmc& Krämer";
    $endcdeI = strtr($otr, $trans)manTD>e you anTD>l yovariável $endcdeI<ão"Hallo 
    &amp; &lt;Frau.amp;htmc&amp; Kr&auml;mer".<ão
    

    Iarray-flip">secame=swf.installatarray_flip(tion>

    aouomudar aidirtçãosda>tradução. l

    laçãoTBODY>laçãoTR>laçãçãoTD>
    $trans = array_flip($trans)m
    $origisala= strtr($endcdeI, $trans)manTD>iolaçsOnce you O wclaeúdo delHbswwf alllitere >$origisal<ão
    

    Iallamp

    Iallalasitief">secame=swf.installatallalasitief(tion>

    Intrtr">secame=swf.installatstrtr(tion>

    Iarray-flip">secame=swf.installatarray_flip(tion>

    nstall

    nstalllon>Inçãoitring>< ntion> all you neeheb nvlllaçãoitring>heb nw_aext>[, nstamax_ihars_par_lede])Oc yoâallroaopcionalcHbswwf all you need to max_ihars_par_ledelllação queb aHR> sOnc=sessVeja também il you need to dclass=section>

    Iaeb nvc">secame=swf.installataeb nvc(tion>

    Inçãoitring>< ntion> all you neeheb nvclllaçãoitring>heb nw_aext>[, nstamax_ihars_par_lede])É similar aiil you need to dclass=section>

    Iaeb nv">secame=swf.installataeb nv(tion>erença é que elasdclveoaeanewlines>(\n)c youo"<br.htm\n" Oc yoâallroaopcionalcHbswyo

    sOnc=sessVeja também il you need to dclass=section>

    Iaeb nv">secame=swf.installataeb nv(tion>

    casu=slasidades HTMLc youoos seusocaracaeresola

    Inçãoitring>< ntion> all you neealla_lasity_d itring>[, nst quote_style [, sared iharset]])section>
    alla_lasity_d élo opostoodaa

    Iallalasitief">secame=swf.installatallalasitief(tion>casulasidades HTMLc youoos seusocaracaeresodelHbswwf all you need to stricllllaçãosbswyo

    ENT_COMPATion>nstalllaçH1>Tsoelas1. Cto dclaes disponíveis youosbswyo

    laçãoTR>laçãçãoTH vAlign=claser align=left>Nome daaCto dclaeçãoH>laçãçãoTH vAlign=claser align=left>InçãolaçãoTBODY>laçãoTR>laçãçãoTD vAlign=claser align=left>vTswwf alllto dcla/H1>ENT_COMPATion>laçãçãoTD vAlign=claser align=left>Irá ctoveoaer aspas eaIeixar,os,laçãapostrofos.anTD>laçãoTR>laçãçãoTD vAlign=claser align=left>vTswwf alllto dcla/H1>ENT_QUOTESion>laçãçãoTD vAlign=claser align=left>Irá ctoveoaer ambos.anTD>laçãoTR>laçãçãoTD vAlign=claser align=left>vTswyo ENT_NOQUOTESion>laçãçãoTD vAlign=claser align=left>Irá Ieixar,ambos semsyowooveoaer.anTD>e you talsssOnc=seP O wcljunto delcaracaeresoISO-8859-1 é usado ctmoopadrão you o tlrceiro yoâallro,lque é opcional,>sbsw

    laçãoTBODY>laçãoTR>laçãçãoTD>laçãçãção

    InstaçãçãçãosssB>Exemplo 1. D Ocaddo lasidades allaion>laçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    <?> unallalasitief ($otring)
    {
    	$trans_tbl = get_alla_translao ne_esote (HTML_ENTITIES);
    	$trans_tbl = array_flip ($trans_tbl);
    	return strtr ($otring, $trans_tbl);
    }
    
    $c = unallalasitief($a);
    
    echo $c;ã//cI'll "walk" thbl<b.htmdog</b.htm"now
    
    ?.htmanTD>e you anTD>sOnc=sessVeja também il you need to dclass=section>
    

    Iallalasitief">secame=swf.installatallalasitief(tion>

    Iallamp

    Iget-alla-translao ne-esote" < namwf allinstallatget_alla_translao ne_esote(tion>

    Iallamp

    Iurld

    Instalaçlass=3, ass=4 nce yhllalasitiefd to dclass=se Ctoveoae aoHos os,caracaereso=s you HTMLclasitief la

    nstallInçãoitring>< ntion> all you neeallalasitieflllaçãoitring>itring>[, nstaquote_style [, sared iharset]])Estau

    Iallamp Ctmooil you need to dclass=section>

    Iallamp leve umaiegundocarg claso> opcionalcque indOcaao que seria feitoswom aspas simples e dupla. vTswyo ENT_COMPATion>ENT_QUOTESion>caspas simples e dupla,oneHbswbswf alllto dcla/H1>ENT_NOQUOTESion>cdeA>clveoaida> sOnc=sessNo>pr slase moclaso,solwcljunto delcaracaeresoISO-8859-1 é usado ctmoopadrão. Su oree you o iegundocarg claso>opcionalcfoi>adicionado<.iiass=3.0.17oneass= 4.0.3 sOnc=sessCtmooil you need to dclass=section>

    Iallamp leve umatlrceiro arg claso> opcionalcque definelo wcljunto delcaracaeresousados nasdclveosão. Su oree you esse arg claso>foi>adicionado<.iiass=4.1.0. sOnc=sessNão háso opostoodestau Inar,umc você róprio. Aqui emtá um exemplo delctmoofazer isso. sOnc=seTABLE cclassEXAMPLE cellSpaci n=0 cellPadding=0lction="100%" bnrdOn=0>laçãoTBODY>laçãoTR>laçãçãoTD>laçãçãção

    Exemplo 1. Opostoode>section>
    allalasitief(tion>laçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    <?> unallalasitief ($otring)
    {
    	$trans_tbl = get_alla_translao ne_esote (HTML_ENTITIES);
    	$trans_tbl = array_flip ($trans_tbl);
    	return strtr ($otring, $trans_tbl);
    }
    ?.htmanTD>e you anTD>=sessVeja também il you need to dclass=section>
    

    Iallamp

    Inl2br">secame=swf.installatnl2br(tion>

    Inçãoitring>< ntion> all you neeallamp itring>[, nst quote_style [, sared iharset]])Ceoaos,caracaeresoaem,signP>Ocado elp pr slrvanado seus,signP>Ocados. Esaau wom algumasadestas ctoveosõesafeitas; As transfss=açõesa ieitas são aquelas maisuúteis youoprogra=ação web. Se você pr

    Iallalasitief">secame=swf.installatallalasitief(tion> opcional, quote_style, colaa àu ctransfss=adas e se ENT_NOQUOTESonmdá Iefinida nenhuma HR>cducs são modP>Ocada> sOnc=sessAs traduçõesaexecueadR> são: olaçsOnchavULs=sçãoLI>=s="hss'.amp;' (ampeosand) torna-se '&amp;' =s="hss'"' (aspas dupla) torna-se '&quot;' quaddo ENT_NOQUOTESonão emtá Iefinida. sOnc=sçãoLI>=s="hss''' (aspas iimples) torna-se '&#039;' apena =s="hss'<' (claor que) torna-se '&lt;' sOnc=sçãoLI>=s="hss'>' (caioraque) torna-se '&gt;' sOnce LlaçãULs=slTABLE cclassEXAMPLE cellSpaci n=0 cellPadding=0lction="100%" bnrdOn=0>laçãoTBODY>laçãoTR>laçãçãoTD>laçãçãção

    Exemplo 1. section>
    allamp exemplolaçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    $new0= allamp
    anTD>e you anTD>
    lsssOnc=seP Note que estau
    liseado a
    

    Iallalasitief">secame=swf.installatallalasitief(tion>opcionalc ioi>adicionado<.iiass=3.0.17oneass=4.0.3 sOnc=sessOatlrceiro arg claso>definelo wcljunto delcaracaeresousados nasdclveosão. O yowoljunto delcaracaeresopadrão éaISO-8859-1. Su oree you o tlrceiro arg claso> foi>adicionado<.iiass=4.1.0. sOnc=sessVeja também il you need to dclass=section>

    Iallalasitief">secame=swf.installatallalasitief(tion>

    Inl2br">secame=swf.installatnl2br(tion>

    emauma itringla

    Inçãoitring>< ntion> all you neeimplodelllaçãoitring>glue, array> pieces)Retornaãuma otricl>wolaeddo os eleclasos da =atriz>na,mesmaBordOmowomluma ligaçãoseetrnecadaleleclaso. lTABLE cclassEXAMPLE cellSpaci n=0 cellPadding=0lction="100%" bnrdOn=0>laçãoTBODY>laçãoTR>laçãçãoTD>laçãçãção

    Exemplo 1. section>
    implode(tion> exemplolaçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    <?>= array('clatname', 'ecail', 'phone');
    $womma_se youteI = implode(",", $array);
    
    prnst $womma_se youteI;ã//cclatname,ecail,phone
    
    ?.htmanTD>e you anTD>sOnc=se
    

    Nota: ion>section>
    implode(tion> ode, por razõesa istóricas,A çãaceitar seuso yoâallrosona f.cPyou cto istênciaawomlsl yollu need to dclass=section>

    Iexplode">secamlle=swf.installatexplode(tion>an
    lssVeja também il you need to dclass=section>

    Iexplode">secame=swf.installatexplode(tion>

    Inplit">secame=swf.installatiplit(tion>

    womluma itringla

    Inçãoitring>< ntion> all you neejoinlllaçãoitring>glue, array> pieces)section>
    join(tion> élum alias youosl you need to dclass=section>

    Iimplode">secamwf allinstallatimplode(tion>

    Iexplode">secame=swf.installatexplode(tion>

    Iimplode">secamwf allinstallatimplode(tion>

    Inplit">secame=swf.installatiplit(tion>

    Inçãoista< ntion> all you neel veHshteinlllaçãoitring>itr1, sared sar2) all you neel veHshteinlllaçãoitring>itr1, sared sar2, nstacost_ins, nst cost_rep, nst cost_del)itr1, sared sar2, l you ne yowost)RetornaãaaL veHshtein-Diseanceseetrneducs stringf arg clasos ou -1,ssea nenhuma HR>cstringf arg clasos é maisulongaaque o o limiteode 255 caracaereso=s(255 seria maisudolque o ba dclaeo you o nome ouãcom aração deodicionário, e ninguém sério estaria fazeddo análisesagenéticas womlass) sOnc=sessA distânciaaL veHshteinsé Iefinida womo o númeio mínimo delcaracaeresoque você aem, you iubstituir, nsserir ouãapagar yoactransfss=ar sbswyo

    Hbswwf all you need to str2lllaçãoO(m*n)<ãoondOBsbswyo nçãomda Hbswbswf all you need to str1Hbswwf all you need to str2lllação

    Isimilar-aext">secame=swf.installatiimilar_aext(tion>itpt_B expeHsive) sOnc=sessNu iua fss=a maisuiimples au cducs stringf womo yoâallros e ce iulará apena HR>copereçõesade nsserção, iubstituiçãose deletação. Esaaué a maisugere le sdapatável dolque a varialaeoum, masanão tão>eficilase sOnc=sessA tlrceira varialaeo(que aindaanão é impleclassda) será a maisugere le sdaptável, masatambém alaltarnativa maisualasa. Eta ihamará uma youocadal ossível opereção. sOnc=sessA =s="hssopereu ne so>apply: 'I', 'R' ouã'D' sOnc=sçãoLI>=s="hssacaualawharacaer nsBsared 1 sOnc=sçãoLI>=s="hssacaualawharacaer nsBsared 2 sOnc=sçãoLI>=s="hss osiu ne nsBsared 1 sOnc=sçãoLI>=s="hss osiu ne nsBsared 2 sOnc=sçãoLI>=s="hssrecained iharacters nsBsared 1 sOnc=sçãoLI>=s="hssrecained iharacters nsBsared 2 sOnce LlaçãULsTheauser-supplied l you ne hla< to,r turn al osioiveçioteger deA>Inbed thbliost css y is pyotiiular opereu ne, but>itBmayBd accnustaehblrelevencesofoand/ss dif>erencesbetweenãcertansBsymbols (iharacters)c ss veH thblionaext>l yse symbols appear nsBto detarmise thbliost ofonssert, replace andat thbliost ofoloi cllallBop thblothsrstwo variala> sOnc=sessVeja também il you need to dclass=section>

    Isnusdex">secame=swf.installatinusdex(tion>

    Isimilar-aext">secame=swf.installatiimilar_aext(tion>

    Iallaphone">secame=swf.installatallaphone(tion>

    Inparray>< ntion> all you neelo Retornaãuma =atriz>on>ociativa wolaeddo numérico lo
    lo r tornaodados ba eados naslo

    Isetlo secame=swf.installatietlo on>ociativa que é r tornada ccltémsyoos seguiasesacam os: ol

    laçãoTR>laçãçãoTH vAlign=claser align=left>Array>nleclas<ãoH>laçãçãoTH vAlign=claser align=left>InçãolaçãoTBODY>laçãoTR>laçãçãoTD vAlign=claser align=left>d laçãçãoTD vAlign=claser align=left>Caracaer dblponto delaçãoTR>laçãçãoTD vAlign=claser align=left>l yusands_se laçãçãoTD vAlign=claser align=left>T yusands se youtorllTD>laçãoTR>laçãçãoTD vAlign=claser align=left>groupinglaTD>laçãçãoTD vAlign=claser align=left>Matriz>wolaeddo agrupaclasos numéricosllTD>laçãoTR>laçãçãoTD vAlign=claser align=left>nst_wurr_symbollaTD>laçãçãoTD vAlign=claser align=left>Intarnationalcwurreacy symbol (i.e.> USD)llTD>laçãoTR>laçãçãoTD vAlign=claser align=left>wurreacy_symbollaTD>laçãçãoTD vAlign=claser align=left>Simbolo da moedaslo < symbol (i.e.>$)llTD>laçãoTR>laçãçãoTD vAlign=claser align=left>mon_d laçãçãoTD vAlign=claser align=left>Caracaere monetário dblponto delaçãoTR>laçãçãoTD vAlign=claser align=left>mon_l yusands_se laçãçãoTD vAlign=claser align=left>Se youdor monetário dblmilanTD>laçãoTR>laçãçãoTD vAlign=claser align=left>mon_groupinglaTD>laçãçãoTD vAlign=claser align=left>Matriz>wolaeddo agrupaclasos monetáriosllTD>laçãoTR>laçãçãoTD vAlign=claser align=left> osioive_signlaTD>laçãçãoTD vAlign=claser align=left>Sinalc youovaloreso osioivosllTD>laçãoTR>laçãçãoTD vAlign=claser align=left>negaoive_signlaTD>laçãçãoTD vAlign=claser align=left>Sinalc youovaloresonegaoivosllTD>laçãoTR>laçãçãoTD vAlign=claser align=left>nst_frac_digieslaTD>laçãçãoTD vAlign=claser align=left>Dígieos deãfração IntarnacionaisllTD>laçãoTR>laçãçãoTD vAlign=claser align=left>frac_digieslaTD>laçãçãoTD vAlign=claser align=left>Dígieos deãfração lo isllTD>laçãoTR>laçãçãoTD vAlign=claser align=left>p_cs_pr laçãçãoTD vAlign=claser align=left>vTswwf alllto dcla/H1>TRUEion>sbswyoçãçã uwf alllto dcla/H1>FALSEion>laçãoTR>laçãçãoTD vAlign=claser align=left>p_se _by_spacelaTD>laçãçãoTD vAlign=claser align=left>vTswwf alllto dcla/H1>TRUEion>sbswyoçãçã uwf alllto dcla/H1>FALSEion>laçãoTR>laçãçãoTD vAlign=claser align=left>n_cs_pr laçãçãoTD vAlign=claser align=left>vTswwf alllto dcla/H1>TRUEion>sbswyoçãçã uwf alllto dcla/H1>FALSEion>laçãoTR>laçãçãoTD vAlign=claser align=left>n_se _by_spacelaTD>laçãçãoTD vAlign=claser align=left>vTswwf alllto dcla/H1>TRUEion>sbswyoçãçã uwf alllto dcla/H1>FALSEion>laçãoTR>laçãçãoTD vAlign=top align=left>p_sign_posnlaTD>laçãçãoTD vAlign=top align=left>yoçãçã ulaçsOnc=sçãçã ulTABLE bnrdOn=0>laçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>0laTD>laçãçãçãçãçãoTD>ParêasesesanalaçãçãçãçãoTR>laçãçãçãçãçãoTD>1laTD>laçãçãçãçãçãoTD>A sared sinalc r laçãçãçãçãoTR>laçãçãçãçãçãoTD>2laTD>laçãçãçãçãçãoTD>A sared sinalcsulaçãçãçãçãoTR>laçãçãçãçãçãoTD>3laTD>laçãçãçãçãçãoTD>A sared sinalc r laçãçãçãçãoTR>laçãçãçãçãçãoTD>4laTD>laçãçãçãçãçãoTD>A sared sinalcsuta="çãçãoaçsOncllTD>laçãoTR>laçãçãoTD vAlign=top align=left>n_sign_posnlaTD>laçãçãoTD vAlign=top align=left>yoçãçã ulaçsOnc=sçãçã ulTABLE bnrdOn=0>laçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>0laTD>laçãçãçãçãçãoTD>ParlasêsesanalaçãçãçãçãoTR>laçãçãçãçãçãoTD>1laTD>laçãçãçãçãçãoTD>A sared sinalc r laçãçãçãçãoTR>laçãçãçãçãçãoTD>2laTD>laçãçãçãçãçãoTD>A sared sinalcsulaçãçãçãçãoTR>laçãçãçãçãçãoTD>3laTD>laçãçãçãçãçãoTD>A sared sinalc r laçãçãçãçãoTR>laçãçãçãçãçãoTD>4laTD>laçãçãçãçãçãoTD>A sared sinalcsuta="çãçãoaçsOncllTD>taoaçsOncll
    lsssOnc=sessOsacam ossdelagrupaclaso ccltéms=atrizescque definemlo modo delctmooos, númeioseseriam agrupados. Pss xemplo,solwam osdelagrupaclaso you aslo deo2 itlas wom os,valoreso3 e 3. Oamaisualso índOce na =atriz, maisudi dclaeodasesquerdasdo agrupaclaso está. Se umwnleclaso da =atriz>é igualaa CHAR_MAX, até aqui nenhum agrupaclaso é feito. Se umwnleclaso de =atriz>é igualaa 0,solprévio eleclaso seria usado. sOnc=seTABLE cclassEXAMPLE cellSpaci n=0 cellPadding=0lction="100%" bnrdOn=0>laçãoTBODY>laçãoTR>laçãçãoTD>laçãçãção

    Exemplo 1. section>
    lo exemplolaçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    ietlo
    anTD>e you anTD>
    lssA lto dclae CHAR_MAX também nmdá Iefinida  you o uso clacionado
    

    Isetlo secame=swf.installatietlo

    Inçãoitring>< ntion> all you neeltrimlllaçãoitring>itr [, sared ameharlise])Nota: ion>O segundoc yoâallro>foi>adicionado<.iiass=4.1.0 iolance BLOCKQUOTE>an
    lssEstau wom whitlspacesretirados do início dOBsbswyo

    r tirará essesacaracters: olaçsOnchavULs=sçãoLI>=s="hss" " (ASCII Hbswwf alllitere >32<ão0x20<ão=s="hss"\t" (ASCII Hbswwf alllitere >9<ão0x09<ão=s="hss"\n" (ASCII Hbswwf alllitere >10<ão0x0A<ão=s="hss"\r" (ASCII Hbswwf alllitere >13<ão0x0D<ão=s="hss"\0" (ASCII Hbswwf alllitere >0<ão0x00<ãoNUL<ão=s="hss"\x0B" (ASCII Hbswwf alllitere >11<ão0x0B<ãoOcar os caracaeresoque você quer r tirar, por meio do yoâallro Hbswwf all you need to eharliselllaçãoCtm Hbswwf alllitere >..<ãoOcar umwordOmodelcaracaeres. sOnc=seTABLE cclassEXAMPLE cellSpaci n=0 cellPadding=0lction="100%" bnrdOn=0>laçãoTBODY>laçãoTR>laçãçãoTD>laçãçãção

    Exemplo 1. Exemplo do uso de>section>
    ltrim(tion>laçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    <?>= "\t\tThese arelaanTD>e nce you anTD>
    lssVeja também il you need to dclass=section>
    

    Itrim">secame=swf.installattrim(tion>

    Irtrim">secame=swf.installatrtrim(tion>

    Inçãoitring>< ntion> all you neemd5_fitelllaçãoitring> fiteu ne)Ce iula o hash MD5sdelum Hbswwf all you need to fiteu nelllaçãoOcado usaddo ooil u need to dclwww.faqs.org/rfcs/rfc1321talla" target=_top>RSA Daea Security, Inc. MD5sMessage-Digest Algorithm

    Imd5">secame=swf.installatad5(tion>

    Icrc32">secame=swf.installatcrc32(tion>

    nstall

    nstalllon>Inçãoitring>< ntion> all you neemd5lllaçãoitring>itr)Ce iula o hash MD5sdelHbswwf all you need to strlllaçãoRSA Daea Security, Inc. MD5sMessage-Digest Algorithm

    Icrc32">secame=swf.installatcrc32(tion>

    Iad5-fite">secame=swf.installatad5_fite(tion>

    Inçãoitring>< ntion> all you neemllaphonelllaçãoitring>itr)Ce iula a,melaphone keysdelHbswwf all you need to strlllação

    Isnusdex">secame=swf.installatinusdex(tion>Ina a,mesmaBkeys you palavrR> ionoras iimilares. Eta é maisupr

    Isnusdex">secame=swf.installatinusdex(tion> sãoadelctmpriclasos variados.>iolanc=sessMelaphone foi>d slavolvedoapor LawrencesPhilipsl<lphilips@verity.ctm.htm.>ioEta é deA>Inta em ["Pracaical Algorithms css Progra=meis", Binstockc& Rex, Addiion Wesley, 1995]. =Once you have libswf all you neemoney-css=au>

    Inpitring>< ntion> all you neemoney_css=aulllaçãoitring>css=au, float number)section>
    money_css=au(tion> r turns au ss=auteI veos ne of sbswyo

    wraps thblC leb ary l you ne yosection>
    itrfmon(tion>, with thbldif>erencesthat y is impleclassu ne yodclveous only one number at auticl sOnc=sessThea ss=au mp

    Ocau ne cto ists of thblfollowing>iequence:ç olaçsOnchavULs=sçãoLI>=s="hssa Hbswwf alllitere >%ção=s="hssopalcflagssOnc=sçãoLI>=s="hssopalcfieldlctionsOnc=sçãoLI>=s="hssopalcleftupr =s="hssopalcrightupr =s="hssasrequireI dclveos ne iharactersOnce LlaçãULs=slsssOnc=se

    se>Flags. ion>Onelor more of thblopalcflags belowlcan beaused:ç olaçsOnchav

    Hbswwf alllitere >=ção=s="hssTheawharacaer Hbswwf alllitere >=ção space sOnc=sçãoDT>Hbswwf alllitere >^ção=s="hssDisaote theause of grouping iharacters (as defineI by thbliurreat lo Hbswwf alllitere >+ção(ção=s="hssSp

    y thblfos=auting>ityle foro osioive and+ção+ção-ção(çãoOcau ne isugiven, thbldefaultcisuHbswwf alllitere >+çãoHbswwf alllitere >!ção=s="hssSuppr ss thbliurreacy symbol frtm thbloutputoitring sOnc=sçãoDT>Hbswwf alllitere >-ção=s="hssIf pr slas,>itBwit_Bmake allBfieldscleft-justP>Oedç(paddeI tooehblright),A çãa>copposedçtooehbldefaultcwhi=hBisucss y eBfieldscto bearight-justP>Oedç çã(paddeI tooehblleft). =Once yD> lsssOncla


    se>Fieldlction. ion> olaçsOnchav

    Hbswwf allreplacesote>=s="hssA deip

    ying>a,minimum fieldlction. Fieldlctt_Bbea=s="right-justP>Oedçunl ss thblflag-ção lsssOncla


    se>Leftupr . ion> olaçsOnchav

    Hbswwf alllitere >#ção=s="hssTheamaximum number of digies (sbswwf allreplacesote>Ocau ne isuignored sOnc=sçãossIf grouping hla^çãoapplieI toofit_Biharacters, veH if yoçãy eBfit_Biharacter isuaadigie sOnc=sçãossToseesurelalignmlas,>any iharacters appearing before ss after thblnumber in yoçãy eBfss=auteI outputosu=hBas wurreacy ss sign symbols areo yddeI la lsssOncla

    se>Rightupr . ion> olaçsOnchav

    Hbswwf alllitere >.ção=s="hssA periodlfolloweI by thblnumber of digies (sbswyoçãwf allreplacesote> isuincluded, thbl=s="defaultcwtt_BdictuteI by thbliurreat lo < in use T e amnustBbeing>css=autedç çãisurnusdeI tooehblmp

    OeI number of digies prior toofos=auting.>iolance yD> lsssOncla


    se>Cclveos ne iharacters . ion> olaçsOnchav

    Hbswwf alllitere >ição=s="hssTheanumber is>css=autedçaccnrding tooehbllo alcwurreacy =s="fss=au (e.g css y eBUSA lo Hbswwf alllitere >nção=s="hssTheanumber is>css=autedçaccnrding tooehbllo alcwurreacy fss=au =s="(e.g css y eBde_DE lo Hbswwf alllitere >%ção=s="hssR turns y eBy eBHbswwf alllitere >%ção lsssOncla

    Nota: ion>T eBHbswwf alllto dcla/H1>LC_MONETARYion> . Use sl yollu need to dclass=section>

    Isetlo secamlle=swf.installatietlo

    . sOnc=sçãossCharacters before anditring ctt_Bbear turnedç çãunihanged sOnce BLOCKQUOTE>an
    lss seTABLE cclassEXAMPLE cellSpaci n=0 cellPadding=0lction="100%" bnrdOn=0>laçãoTBODY>laçãoTR>laçãçãoTD>laçãçãção

    Exemplo 1. section>
    money_css=au(tion> Exampleerentcao Ocau nes toBillustoute taçãçãçãthbluse of y is
    . sOnc=sçãçãçãoTABLE cellPadding=5 bgColor=#e0e0e0 bnrdOn=0>laçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    <?>alc
    ss=au css y eBen_UScao
    alc
    ss=au with 2ld
    alc
    ss=au, ui cll() css negaoive numbers
    çãçã//cand<10 digies css leftupr
    
    çãçãietlo
     and<'*' asla fit_Biharacter
    çãçãecho money_css=au('%=*(#10.2n',ã$number)."\n";
    çãçã//c($********1,234.57)
    çãçã
    çãçã//cLet's justP>yãtooehblleft, with 14  osiu nes of ction, 8 digies of
    çãçã//cceftupr
    , 2 of rightupr
    , withouth grouping iharacter
    çãçã//candalc
    ss=au css y eBde_DE lo
    Ocau ne
    çãçãietlo
    = 'T eBfinalcvaaue is %i (after a<10%%udi cnust)';
    çãçãecho money_css=au($fmt,ã1234.56)."\n";
    çãçã//cT eBfinalcvaaue is  GBP 1,234.56 (after a<10%udi cnust)
    
    ?.htmanTD>e you anTD>sOnc=seP>Seelalso: il you need to dclass=section>
    

    Isetlo secame=swf.installatietlo

    Inumber-css=au">secame=swf.installatnumber_css=au(tion>

    Ispristf">secame=swf.installatipristf(tion>

    Ipristf">secame=swf.installatpristf(tion>

    Isscanf">secame=swf.installatiscanf(tion>

    nstalllaçlass=4 .htm= 4.1.0nce ynl_langiecsd to dclass=se Retornaoiecss=ação de l cluagem bllo < la

    Inçãoitring>< ntion> all you neenl_langiecslllaçãoistaitem)

    lsssOnc seTABLE cclasswarned lction="100%" bnrdOn=1s=s="hTBODY>laçãoTR>laçãçãoTD align=middle>AteHçãoion>laçãoTR>laçãçãoTD align=left>yoçãçã ulaçEstau e you lsssOncla
    e libswf all you neenl2br>

    nstalllaçlass=3, ass=4 nce ynl2brd to dclass=se Issere quebras de ledhaaHTMLcclaes de todlaemauma itring>

    Inçãoitring>< ntion> all you neenl2brlllaçãoitring>itring)RetornaãHbswwf all you need to stringlalaçãoNota: ion>Começa<.iiass=4.0.5, section>
    nl2br(tion> nmdá agoraslaçãemaXHTMLcwomplaclase. Todla ao invés de '<br />' sOnce BLOCKQUOTE>an
    lssVeja também il you need to dclass=section>

    Iallamp secame=swf.installatallamp

    Iallaeasitief">secame=swf.installatallalasitief(tion>

    Iwnrdwrap">secame=swf.installatwnrdwrap(tion>

    nstall

    nstalllon>Inçãoitring>< ntion> all you neenumber_css=aulllaçãofloat number [, nstad section>
    number_css=au(tion> r tornaouma veosãoc ss=auadasdelsbswyowf all you need to numberlllaçãoé dado,ãHbswwf all you need to numberlllaçãoiolanc=sessSe dois yoâallros sãoadados,ãHbswwf all you need to numberlllaçãoOcadR> emlsbswyowf all you need to d lanc=sessSe aoHos os,quatro yoâallros foremadados,ãHbswyowf all you need to numberlllação casas deNota: ion>Somease olprimeiro caracaeresdelsbswyoçãwf all you need to l yusands_se fooção1000<ão
    number_css=au(tion> irá r tornar1f000<ãoan
    lss seTABLE cclassEXAMPLE cellSpaci n=0 cellPadding=0lction="100%" bnrdOn=0>laçãoTBODY>laçãoTR>laçãçãoTD>laçãçãção

    Exemplo 1. Exemplo section>
    number_css=au(tion>Isso é feito wom a ledhaa: sOnc=sçãçãçãoTABLE cellPadding=5 bgColor=#e0e0e0 bnrdOn=0>laçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    <?>anTD>e you anTD>sOnc=seP>Veja também: il you need to dclass=section>
    

    Ispristf">secame=swf.installatipristf(tion>

    Ipristf">secame=swf.installatpristf(tion>

    Isscanf">secame=swf.installatiscanf(tion>

    Inçãoista< ntion> all you neenrdlllaçãoitring>itring)Retornaão valoroASCII do primeiro caracaeresdelsbswyowf all you need to stringlalação

    Ichr">secame=swf.installatchr(tion>laçãoTBODY>laçãoTR>laçãçãoTD>laçãçãção

    Exemplo 1. Exemplo section>
    nrd(tion>laçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    if (nrd($itr) == 10) {laçãçãecho "O primeiro caracaeresdel\$itr éluma<.iva ledha.\n";
    }anTD>e you anTD>sOnc=seP>Você  ode aihar a esoela ASCII aqui:oil u need to dclwww.asciiesote.ctm/" 
    target=_top> to dclwww.asciiesote.ctm/
    

    Ichr">secame=swf.installatchr(tion>


    emsyovariáveis

    nstalllon>Inçãovoida< ntion> all you nee yose_strlllaçãoitring>itr [, array>amarr])Cclveoue Hbswwf all you need to strlalação variáveis.oSe o segundoc yoâallro>sbswyowf all you need to arr variáveis sãoacolo dR> nesta variável womoouma =atriz>deoeleclasos sOnc=se

    Nota: ion>Suporaeo you o segundoc yoâallro,lque é opcional, foi>=s="adicionado<.iiass=4.0.3 sOnce BLOCKQUOTE>an
    l

    Nota: ion>Pyou egar aiiSPAN1 classemphasis towyoçãwf allemphasis QUERY_STRING aaual, você deve usar

    $_SERVER['QUERY_STRING']

    variáveis yolldblfosaadoltioan
    lss seTABLE cclassEXAMPLE cellSpaci n=0 cellPadding=0lction="100%" bnrdOn=0>laçãoTBODY>laçãoTR>laçãçãoTD>laçãçãção

    nstallçãçãçãosssB>Exemplo 1. Usaddo section>
    yose_str(tion>laçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    <?>anTD>e you anTD>sOnc=seP>Veja também sl you need to dclass=section>
    

    Ipyose-url">secame=swf.installatpyose_url(tion>

    Ipathiecs">secame=swf.installatpythiecs(tion>

    Iset-magic-quotes-runticl">secame=swf.installatiet_magic_quotes_runticl(tion>

    Iurldecode">secame=swf.installaturldecode(tion>


    nstall

    nstalllon>Inção< ntion> all you nee rnstlllaçãoitring>arg)MostoulHbswwf all you need to arglalaçãoTRUEion>FALSEion>
    rnst(tion> não é aaualmease uma flaçãoTBODY>laçãoTR>laçãçãoTD>laçãçãção

    Exemplo 1. Exemplos section>
    rnst(tion>laçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    <?> também";
    
    prista"Isso secide\nem múltipcla ledhas. As quebras de ledhaaslrão\nmostoudR> também";
    
    prista"/A>apar caracaeresoé feito \"womooisso\".";
    
    //cVocê  ode usarcsobar
    
    //cUsaddo apóstoofos irá exibir o nome da variável, não o valor
    prista'foo is $foo';ã//cfoo is>$foo
    
    //cSe você não estiver usaddo oulros caracaeres, somease mostoeanTD>e you anTD>=seP>Veja também sl you need to dclass=section>
    

    Iecho">secame=swf.installatecho(tion>

    Ipristf">secame=swf.installatpristf(tion>

    Iflush">secame=swf.installatflush(tion>


    nstalllon>Inçãovoida< ntion> all you nee rnstflllaçãoitring>css=au [, mixedç args])Produzluma oaídasdelacnrdo wom Hbswwf all you need to css=aulllaçãoIntosnaodH1 classção you il you need to dclass=section>

    Ispristf">secame=swf.installatipristf(tion>

    Iprist">secame=swf.installatprist(tion>

    Ispristf">secame=swf.installatipristf(tion>

    Isscanf">secame=swf.installatiscanf(tion>

    Ifscanf">secame=swf.installatfscanf(tion>

    Iflush">secame=swf.installatflush(tion>

    Inçãoitring>< ntion> all you neequoted_pristable_decodelllação itring>itr)Estau del8-bit>cnrres ondeedo aoitring> quoted-pristable decodP>OcadR Estau

    Iimap-qprist">secame=swf.installatimap_qprist(tion>

    nstalllaçlass=3, ass=4 nce yquoteallad to dclass=seAdicionaouma barra inveoaidasalaes Hos alla caracaeres

    Inçãoitring>< ntion> all you neequoteallalllaçãoitring>itr)R tornaouma veosãocde strawomluma barra inveoaidas(oTswwf alllitere >\<ãolaçãoTBODY>laçãoTR>laçãçãoTD>
    Ieen1. \\ + * ? [ ^ ]ção$ nce RE>anTD>e nc
    lssVeja também il you need to dclass=section>
    

    Iaddsclahef">secame=swf.installataddsclahef(tion>

    Iallaeasitief">secame=swf.installatallalasitief(tion>

    Iallamp secame=swf.installatallamp

    Inl2br">secame=swf.installatnl2br(tion>

    Istripsclahef">secame=swf.installatstripsclahef(tion>

    Inçãoitring>< ntion> all you neertrimlllaçãoitring>itr [, sared ameharlise])Nota: ion>O Segundoc yoâallro>foi>adicionado<.iiass=4.1.0 iolance BLOCKQUOTE>an
    lssEstau womooos,nspaços em brenco retirados do finalcde olTswwf all you need to strlalação irá r tirar oseseguinsesacaracteres: olsssOnc seULs=sçãoLI>=s="hss" " (ASCII Hbswwf alllitere >32<ão0x20<ão=s="hss"\t" (ASCII Hbswwf alllitere >9<ão0x09<ão=s="hss"\n" (ASCII Hbswwf alllitere >10<ão0x0A<ão=s="hss"\r" (ASCII Hbswwf alllitere >13<ão0x0D<ão=s="hss"\0" (ASCII Hbswwf alllitere >0<ão0x00<ãoNULL<ão=s="hss"\x0B" (ASCII Hbswwf alllitere >11<ão0x0B<ãoOcar os caracaeresoque você d slja r tirar, pelo yoâallro Hbswwf all you need to eharliselllaçãoCtm Hbswwf alllitere >..<ãoOcar umwintarvalo de caracaeres. sOnc=seTABLE cclassEXAMPLE cellSpaci n=0 cellPadding=0lction="100%" bnrdOn=0>laçãoTBODY>laçãoTR>laçãçãoTD>laçãçãção

    nstallçãçãçãosssB>Exemplo 1. Exemplo de uso da laçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    <?>= "\t\tThese arelaanTD>e nce you anTD>
    lssVeja também il you need to dclass=section>
    

    Itrim">secame=swf.installattrim(tion>

    Iltrim">secame=swf.installatltrim(tion>

    nstallInpitring>< ntion> all you neeietlo ao < ntion> all you neeietlo lo sbswwf all you need to Categorylllaçãoitring) ip

    ying>thbldategory of thbll you nes affecteI by thblao =s="hssLC_ALL css allBof thblbelowlsOnc=sçãoLI>=s="hssLC_COLLATE1fnr>itring wompariion,ssee sl yollu need to dclass=section>


    Istrcoll">secamlle=swf.installatitrcoll(tion>=s="hssLC_CTYPE1fnr>characaer e=swfP>Ocau ne andexample sl yollu need to dclass=section>

    Istrtoupper">secamlle=swf.installatitrtoupper(tion>=s="hssLC_MONETARY1fnr>sl yollu need to dclass=section>

    Iao secamlle=swf.installatao =s="hssLC_NUMERIC1fnr>d sl yollu need to dclass=section>

    Iao secamlle=swf.installatao =s="hssLC_TIME1fnr>dute andwith sl yollu need to dclass=section>

    Istrfticl">secamlle=swf.installatitrfticl(tion>

    ""çãofrtm "LANG". =Onc lssIf sbswwf all you need to lo "0"çãonr>followeI by addiallaallpyou needs y en ea=hBarray>eleclas>nr>pyou need is yrieI toobeaset R> newlao erentc nameslne dif>erentcsyseems>nr>for provid cllasfallback css a ossibly not available lo Nota: ion>PswfPcllmultipce lo an
    lssSetlo FALSEion>OeI lo causes a warned lmessage. sOnc=se

    Nota: ion>T eBr turnlvaaue of section>
    ietlo >d pends yolloosthblsyseem that ass=is runned . ItBr turns exactly what thblsyseem yollietlo an
    lss seTABLE cclassEXAMPLE cellSpaci n=0 cellPadding=0lction="100%" bnrdOn=0>laçãoTBODY>laçãoTR>laçãçãoTD>laçãçãção

    Exemplo 1. section>
    ietlo >ExampleslaçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    <?>erentc ossiblblao
    cof ass=4.3.0 */
    $ao
    _de = ieuao
    anTD>e you anTD>=Once you have libswf all you neeiha1-fiteallatiha1_fitellon>
    

    Inçãoitring>< ntion> all you neeiha1_fitelllaçãoitring> nos=soarquivo)Ce iula a,hash iha1 de sbswwf all you need to nos=soarquivolllaçãoUS Secure Hash Algorithm 1FALSEion>iolanc=sessVeja também il you need to dclass=section>

    Iiha1">secame=swf.installatsha1(tion>

    Icrc32">secame=swf.installatcrc32(tion>

    Iad5-fite">secame=swf.installatad5_fite(tion>

    Inçãoitring>< ntion> all you neeiha1lllaçãoitring>itr)Ce iula a,hash iha1 de sbswwf all you need to strlalaçãoUS Secure Hash Algorithm 1

    Iiha1-fite">secame=swf.installatiha1_fite(tion>

    Icrc32">secame=swf.installatcrc32(tion>

    Iad5">secame=swf.installatad5(tion>

    nstalllaçlass=3.htm= 3.0.7, ass=4 nce yiimilar_aextd to dclass=se Ce iulateBy eB iimilarity betweenãtwooitrings>

    Inpista< ntion> all you neeiimilar_aextlllaçãoitring>cirst, itring>sedcld [, float perclas])T is ce iulates thbliimilarity betweenãtwooitrings>as deA>InbedçiosOliver [1993]ecNite that y is impleclassu ne does not use a otack asçiosOliver's pseudo swcode, butBr cursive ce lscwhi=hBmay>nr>may>not mp edçup thblwholblprothat thblwomplexity of y is algorithm is O(N**3)lwheresN is y eBalagth of =sthbllongestoitring. lanc=sessByap al cllas neerencesas y irdlarg clas,lsecame=swf.installatiimilar_aext(tion>>ctt_Bce iulateBy eBiimilarity ios erclas css you. ItBr turns thblnumber of mat=hing whars iosboth strings. =Once you have libswf all you neeinusdexallatinusdexllon>

    Inpitring>< ntion> all you neeinusdexlllaçãoitring>itr)Ce iulates thblinusdex key of lTswwf all you need to strlalaçãothat wnrds pronnuscedçiimilarly produceBy eB iame inusdex key, andyãsearches iosdatabases wheres you knowBy eBpronuscisu ne butBnot thblmp lling. T is inusdex l you ne r turns a itring=4 iharacters long, saarting>with accetter.>lanc=sessT is partiiular inusdex l you ne islnee deA>Inbedçby Dlaald Knuth ios"T eBArt Of>Ctmpueed Progou ming, vol. 3: Sorting>Andlanc=sess seTABLE cclassEXAMPLE cellSpaci n=0 cellPadding=0lction="100%" bnrdOn=0>laçãoTBODY>laçãoTR>laçãçãoTD>laçãçãção

    nstallçãçãçãosssB>Exemplo 1. Snusdex ExampleslaçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    inusdex("Euler") == inusdex("Ellery") == 'E460';
    inusdex("Gauss") == inusdex("Ghosh") == 'G200';
    inusdex("Hilbert") == inusdex("Heilbronn") == 'H416';
    inusdex("Knuth") == inusdex("Kcla") == 'K530';
    inusdex("Lloyd") == inusdex("Ladd") == 'L300';
    inusdex("Lukasiewicz") == inusdex("Lissajous") == 'L222'manTD>e you anTD>sOnc=seP>Seelalsoasl you need to dclass=section>
    

    Il veHshtein">secame=swf.installatl veHshtein(tion>

    Iallaphnee">secame=swf.installatallaphnee(tion>

    Isimilar-aext">secame=swf.installatiimilar_aext(tion>

    nstalllaçlass=3, ass=4 nce yi rnstfd to dclass=seR turnlasfos=autedçitring

    Inpitring>< ntion> all you neei rnstflllaçãoitring>css=au [, mixedçargs])R turns a itring>producedçaccnrding tooehblfos=auting>stringãHbswame=swf. you need to css=aulllaçãolanc=sessT blfos=au>stringãisawomposed of zeioBor more dir ctives: nrdinary iharacters (excludingãHbswe=swf.litere >%çãothat arelcopOeI dir ctlyãtooehblresult, and<=seSPAN1 classemphasis tow classemphasis dclveos ne mp

    Ocau nes, ea=hBof chi=hBresults iosfet=hing ies own>pyou need. T is applies toBboth secame=swf.installatipristf(tion> and


    Ipristf">secame=swf.installatpristf(tion>lanc=sessEa=hBdclveos ne mp

    Ocau ne dcl ises of as erclas sign (Hbswame=swf.litere >%çãofolloweI by nee or more of thbseoeleclass, iosnrdOn: olsssOnc seOL type=1s=s="hLI>=s="hssAosnp < lSPAN1 classemphasis tow classemphasis padd cllyollip

    Oer that says what characaer ctt_Bbeaused for padd clly eByollresults tooehblrightuitring>iize. T is may>be a opace characaer ss a sbswyoçãwf alllitere >0çãowith opaces. An yoçãaltarnaOeI by prefixing ie>with acl cl'ção=s="hssAosnp < lSPAN1 classemphasis tow classemphasis alignmentc llip

    Oer that says iflthblresult should bblleft-justP>OeI orOeI T e defaultcis right-justP>OeI; aãHbswe=swf.litere >-çãoleft-justP>OeI sOnc=sçãoLI>=s="hssAosnp < number, aiiSPAN1 classemphasis tow classemphasis ctionc llip

    Oer that says howBnamy iharacters (minimum) y is dclveos ne llihould result in sOnc=sçãoLI>=s="hssAosnp < lSPAN1 classemphasis tow classemphasis pr llip

    Oer that says howBnamy d has<.iieffect for other types than sl yollu need to dclass=section>


    secamlle=swf.type>floation>(Another l you ne usefut for fos=auting>numbers is yo sl yollu need to dclass=section>

    Inumber-css=au">secamlle=swf.installatnumber_css=au(tion>=s="hssA lSPAN1 classemphasis tow classemphasis typelip

    Oer that lliays what typelthblarg classdata should bbltreatedçR> Possiblbltypes: =s="hsssOnc=sçãoTABLE bnrdOn=0>laçãçãoTBODY>laçãçãoTR>laçãçãçãoTD>%çãolaçãçãoTR>laçãçãçãoTD>bção an intager, laçãçãçã and a bisary>number sOTD>laçãçãoTR>laçãçãçãoTD>cção an intager, laçãçãçã and thblwharacaer ctth that ASCII vaaue sOTD>laçãçãoTR>laçãçãçãoTD>dção an intager, laçãçãçã and a (signed) d laçãçãoTR>laçãçãçãoTD>ução an intager, laçãçãçã and an ussigned d laçãçãoTR>laçãçãçãoTD>fção a sl yollllllllu need to dclass=section>


    secamlllllllle=swf.type>floation> a float cl-ponst number.camllllsOTD>laçãçãoTR>laçãçãçãoTD>oção an intager, laçãçãçã and an octallnumber sOTD>laçãçãoTR>laçãçãçãoTD>sção andlaçãçãoTR>laçãçãçãoTD>xção an intager and<=sçãçãçã pr slasedçR> a uexad laçãçãoTR>laçãçãçãoTD>Xção an intager and<=sçãçãçã pr slasedçR> a uexad ="hsssOnc=sçãosssOnce LlaçãOLs=slsssOnc=sessA>cof ass=veos ne 4.0.6oehblfos=auuitring>iuppores arg classlanumbering/swapping Heresi> an example: olTABLE c=swf.EXAMPLE cellSpaci n=0 cellPadding=0lction="100%" bnrdOn=0>laçãoTBODY>laçãoTR>laçãçãoTD>laçãçãção

    Exemplo 1. Arg classswappinglaçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    $fos=auu=s"T ere arel%d monkeys iosthbl%s";
     ristf($fos=au,$num,$ao
    au ne)manTD>e you anTD>T is 
    mightuoutput,s"T ere arel5 monkeys iosthblyree". But imagineãwe arelcreaticllas
    fss=at>stringãinlasse youtblfi
    andas: 
    olTABLE c=swf.EXAMPLE cellSpaci n=0 cellPadding=0lction="100%" bnrdOn=0>laçãoTBODY>laçãoTR>laçãçãoTD>laçãçãção
    

    nstallçãçãçãosssB>Exemplo 2. Arg classswappinglaçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    $fos=auu=s"T el%s colaainsl%d monkeys";
     ristf($fos=au,$num,$ao
    au ne)manTD>e you anTD>We amnowBhaveBa>problbm
     T e nrdOnBof thblplaclholders iosthblfss=at>stringãdoes not 
    mat=hsthblnrdOnBof thblarg class iosthblcode. We would like tooleaveBy eBcode as yoi> andstringãchi=hBarg class thblplaclholders 
     neer to. We would write thblfss=at>stringãlike t is instead: 
    olTABLE c=swf.EXAMPLE cellSpaci n=0 cellPadding=0lction="100%" bnrdOn=0>laçãoTBODY>laçãoTR>laçãçãoTD>laçãçãção
    

    Exemplo 3. Arg classswappinglaçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    $fos=auu=s"T el%2\$s colaainsl%1\$d monkeys";
     ristf($fos=au,$num,$ao
    au ne)manTD>e you anTD>An yoaddeI benefie>heresi> that you ean repeat thblplaclholders ctthout add cllmore 
    arg class iosthblcode. Fnr>example: 
    olTABLE c=swf.EXAMPLE cellSpaci n=0 cellPadding=0lction="100%" bnrdOn=0>laçãoTBODY>laçãoTR>laçãçãoTD>laçãçãção
    

    Exemplo 4. Arg classswappinglaçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    $fos=auu=s"T el%2\$s colaainsl%1\$d monkeys.laçãçãçãçãçã T at's a nicel%2\$s fut_Bof %1\$d monkeys.";
     ristf($fos=au,ã$num,ã$ao
    au ne)manTD>e you anTD>sOnc=seP>Seelalsoasl you need to dclass=section>
    

    Ipristf">secame=swf.installatpristf(tion>

    Isscanf">secame=swf.installatiscanf(tion>

    Ifscanf">secame=swf.installatfscanf(tion>

    Ivspristf">secame=swf.installatvipristf(tion>

    Inumber-css=au">secame=swf.installatnumber_css=au(tion>nstalllon>Examples=sess seTABLE cclassEXAMPLE cellSpaci n=0 cellPadding=0lction="100%" bnrdOn=0>laçãoTBODY>laçãoTR>laçãçãoTD>laçãçãção

    Exemplo 5. section>
    ipristf(tion>: zeio-paddeI ioçãçãçãintagerslaçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    $isodute = ipristf("%04d-%02d-%02d",ã$year, $month, $day)manTD>e you anTD>
    seTABLE cclassEXAMPLE cellSpaci n=0 cellPadding=0lction="100%" bnrdOn=0>laçãoTBODY>laçãoTR>laçãçãoTD>laçãçãção
    

    nstallçãçãçãosssB>Exemplo 6. section>
    ipristf(tion>: fos=auting>llçãçãçãiurreacylaçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    $money1 = 68.75;
    $money2 = 54.35;
    $money = $money1 + $money2;
    //cecho $money ctt_Boutput "123.1";
    $fos=autedç= ipristf("%01.2f", $money);
    //cecho $fos=autedçctt_Boutput "123.10"çãsRE>anTD>e you anTD>=Once you have libswf all you neeiscanf>nstaiscanfllon>
    

    accnrding tooasfos=au>

    nstalllon>Inpmixedç< ntion> all you neeiscanflllaçãoitring>itr, sared amcss=au [, sared var1])T e l you ne section>
    iscanf(tion> is y eBioput analog of ll you need to dclass=section>

    Ipristf">secame=swf.installatpristf(tion>lection>
    iscanf(tion> reads frtm thbl itring>OeI If only twolpyou needs weres p aled tooehis l you ne,ãthblvaaues pyosed ctt_Bbear turnedçR> an array.>lanc=sessAny whiteopace iosthblfss=at>stringãmat=hes any whiteopace iosthblioput itring. T is mean> that veH a eso \t iosthblfss=at>stringãean mat=hsacl cllaçãoTBODY>laçãoTR>laçãçãoTD>laçãçãção

    nstallçãçãçãosssB>Exemplo 1. lection>
    iscanf(tion> ExamplelaçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    //cgeuting thblseriallnumber
    $ieriall= iscanf("SN/2350001","SN/%d");
    //canddute of manufacauring
    $mandute = "Jame=ry 01 2000";
    lise($month, $day,ã$year)l= iscanf($mandute,"%sl%d %d");
    echo "Ieem $ieriallwas manufacauredçon:ã$year-".substr($month,0,3)."-$day\n";çãsRE>anTD>e you anTD>If =snp
    < pyou needs arelp aled,ãthbll you ne ctt_Br turnlthblnumber of  aligned yovaaues
     T e np
    < pyou needs mustBbeap aled bys neerence. 
    seTABLE cclassEXAMPLE cellSpaci n=0 cellPadding=0lction="100%" bnrdOn=0>laçãoTBODY>laçãoTR>laçãçãoTD>laçãçãção
    

    Exemplo 2. lection>
    iscanf(tion> - ul cllnp
    < llçãçãçãpyou needslaçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    //cgeu aul yr iofocandanTD>e you anTD>sOnc=seP>Seelalsoasl you need to dclass=section>
    

    Ifscanf">secame=swf.installatfscanf(tion>

    Ipristf">secame=swf.installatpristf(tion>

    Ispristf">secame=swf.installatipristf(tion>

    nstalllaçlass=4 .htm= 4.0.1nce yitr_padd to dclass=se Pyd aoitring>tooasceraainBalagth with another itring>

    Inpitring>< ntion> all you neeitr_padlllaçãoitring>ioput, iots p d_alagth [, sared p d_sared [, iotsp d_type]])T is l you nes r turns y eBOeI padd cllalagth.>If =sthblnp < arg classis paddeI with iharacters frtm Hbswame=swf. you need to p d_sared lllação < arg classIf Hbswame=swf. you need to p d_typelllaçãoOeI ie>is swfumeI toobea STR_PAD_RIGHT. lanc=sessIfãthblvaaue of lTswwf all you need to p d_alagthlllaçãolaçãoTBODY>laçãoTR>laçãçãoTD>laçãçãção

    Exemplo 1. lection>
    itr_pad(tion> examplelaçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    $ioput = "Alien";
     rist itr_pad($ioput, 10);çãçãçãçãçããããããããããããã//cproduces "Alienããããã"
     rist itr_pad($ioput, 10, "-=", STR_PAD_LEFT);ãã//cproduces "-=-=-Alien"
     rist itr_pad($ioput, 10, "_", STR_PAD_BOTH);çãç//cproduces "__Alien___"çãsRE>anTD>e you anTD>=Once you have libswf all you neeitr-repeat>
    

    Inpitring>< ntion> all you neeitr_repeatlllaçãoitring>ioput, nstlmultipcier)R turns equa_Btoo0.>If =sthbllaçãoTBODY>laçãoTR>laçãçãoTD>laçãçãção

    nstallçãçãçãosssB>Exemplo 1. lection>
    itr_repeat(tion> examplelaçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    echo itr_repeat("-=", 10);anTD>e you anTD>
    seP>T is ctt_Boutput "-=-=-=-=-=-=-=-=-=-=". =Onc
    lssSeelalsoasl you need to dclass=section>
    


    Istr-pad">secame=swf.installatitr_pad(tion>

    Isubstr-coust">secame=swf.installatsubstr_coust(tion>

    nstalllaçlass=3.htm= 3.0.6, ass=4 nce yitr_replacld to dclass=se Replacl allBlaociurreaces of thblsearch>stringãcith thblreplaclclassstring>

    Inpmixedç< ntion> all you neeitr_replacllllaçãomixedçsearch, mixedçreplacl, mixedçsubjtio)T is l you ne r turns a string>ss an array>with at_Bociureaces of =bswame=swf. you need to searchlalaçãorules, you should always useãehis l you ne instead of =sHl you need to dclass=section>

    Iereg-replacl">secame=swf.installatereg_replacl(tion>

    Ipreg-replacl">secame=swf.installatpreg_replacl(tion>pyou need to secame=swf.installatitr_replacl(tion> ean bblan array.>lanc=sessIf sbswwf all you need to subjtiolalação an array,ãthbn thblsearch>and<=sreplacl>is perfss=ldãcith very>eetry of =bswame=swf. you need to subjtiolalaçãor turnlvaaue i> an arrayçR> well.>iolanc=sessIf sbswwf all you need to searchlalação takes alvaaue frtm ea=hBarray>andandonlIf Hbswame=swf. you need to replacllllação used for the>r se sf<=sreplaclclassvaaues If sbswwf all you need to searchlalação an arrayçRnd<=sebswwf all you need to replacllllaçãoi> used for very>vaaue of lTswwf all you need to searchlalaçãolaçãoTBODY>laçãoTR>laçãçãoTD>laçãçãção

    Exemplo 1. lection>
    itr_replacl(tion> examplelaçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    $bodytagl= itr_replacl("%body%", "black", "<body aext=%body%.htm")manTD>e you anTD>sOnc=seP>T is l you ne is bisary>safe. sOnc=se
    

    Nota: ion>lection>
    itr_replacl(tion> was addeI in ass=3.0.6, =s="butBwas buggy up until ass=3.0.8. =Once BLOCKQUOTE>an
    lssSeelalsoasl you need to dclass=section>

    Iereg-replacl">secame=swf.installatereg_replacl(tion>

    Ipreg-replacl">secame=swf.installatpreg_replacl(tion>

    Istrtr">secame=swf.installatstrtr(tion>

    nstalllaçlass=4 .htm= 4.2.0nce yitr_rot13d to dclass=sePerfss= the>rot13 transfss= A> a otriclla

    nstalllon>Inpitring>< ntion> all you neeitr_rot13lllaçãoitring> str)T is l you ne perfss=s y eBROT13 eacod clloosthblsbswame=swf. you need to strlalaçãostring T e ROT13 eacod cllsimply shifts very>cetter bys13 placls iosthblalphabet whi arg classctt_Br turnlthblorigi> < llveos ne. =Once you have libswf all you neeitr-shuffll>

    Inpitring>< ntion> all you neeitr_shufflllllaçãoitring> str)lection>
    itr_shuffll(tion> shufflls a string Oee permussu ne of llBla ossiblblis created. lanc=sess seTABLE cclassEXAMPLE cellSpaci n=0 cellPadding=0lction="100%" bnrdOn=0>laçãoTBODY>laçãoTR>laçãçãoTD>laçãçãção

    Exemplo 1. lection>
    itr_shuffll(tion> examplelaçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    <?>like: bfdaec
     rist $shufflld;
    ?.htmanTD>e you anTD>=Onc
    lssSeelalsoasl you need to dclass=section>
    

    Ishuffll">secame=swf.installatshuffll(tion>

    Irand">secame=swf.installatrand(tion>

    Inpmixedç< ntion> all you neeitr_wnrd_coustlllaçãoitring>itring> [, iotscss=au])Cousts thblnumber of wnrds inside lTswwf all you need to sared lllaçãoIf =sthblnp < OeI,ãthbn thbl nturnlvaaue ctt_Bbeaan intager repr slasing>thblnumber of wnrds fnusd.>In thbl veHtsthblsbswwf all you need to css=aulllaçãoOeI,ãthb>r turnlvaaue wit_Bbeaan array,ãcolaeHtsof chi=hBis>d pendeHtsoosthblsbswame=swf. you need to css=aulllaçãoT e ossiblblvaaue for the>sbswame=swf. you need to css=aulllaçãor sultcla outputs arelliseedlbelow swfP>lOnc lULs=sçãoLI>=s="hss1 - r turns an arrayçcolaainingçRt_Bthe>wnrds fnusd inside the>sbswam wwf all you need to sared lllação=s="hss2 - r turns an associsu ve array,ãwheresthe>key is thblnumeric osiu ne of =s="the>wnrd inside the>sbswwf all you need to sared lllaçãovaaue i> =s="the>acauallwnrd itself. =Once LlaçãULs=slsssOnc=sessFor the>purpose of y is l you ne,a'wnrd'Bis>d finedçR> a lo colaainingçRtphabetic iharacters,ãchi=hBalsoamayçcolaain, butBnot saart with "'"cand<"-" iharacters. =Once you have libswf all you neeitrcasecmp>

    safewamease-insensiu ve itring>compariion>

    nstalllon>Inpiots< ntion> all you neeitrcasecmplllaçãoitring>itr1, sared amsar2)R turns < 0 iflsbswwf all you need to sar1lllação greater than sbswwf all you need to sar2lllaçãolaçãoTBODY>laçãoTR>laçãçãoTD>laçãçãção

    Exemplo 1. lection>
    itrcasecmp(tion> examplelaçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    $var1 = "Hello";
    $var2 = "hello";
    ifl(!itrcasecmp($var1, $var2)) {laçãçãecho '$var1 i> equa_Btoo$var2 inlasease-insensiu ve itring>compariion';
    }anTD>e you anTD>=Onc
    lssSeelalsoasl you need to dclass=section>
    

    Iereg">secame=swf.installatereg(tion>

    Iitrcmp">secame=swf.installatstrcmp(tion>

    Iiubstr">secame=swf.installatsubstr(tion>

    Iitristr">secame=swf.installatstristr(tion>

    Iitrncasecmp">secame=swf.installatstrncasecmp(tion>

    Istrstr">secame=swf.installatstrstr(tion>

    primeiraBocorrêscis de um yocaracaere>

    Inçãoitring>< ntion> all you neeitrchrlllaçãoitring>hayotack, itring>neldle)Esta l yção élum apelidolpyou

    Istrstr">secame=swf.installatstrstr(tion>

    nstalllaçlass=3, ass=4 nce yitrcmpd to dclass=seComparação de itring>seguou

    Inçãoiots< ntion> all you neeitrcmplllaçãoitring>itr1, sared amsar2)R tornao< 0 se>sbswwf all you need to sar1lllaçãosbswwf all you need to sar1lllaçãocssem iguais. lanc=sessNite qublesta l yção dieerencis maiúsiula> e minúsiula>. lanc=sessVeja também il you need to dclass=section>

    Iereg">secame=swf.installatereg(tion>

    Iitrcasecmp">secame=swf.installatstrcasecmp(tion>

    Iiubstr">secame=swf.installatsubstr(tion>

    Iitristr">secame=swf.installatstristr(tion>

    Iitrncasecmp">secame=swf.installatstrncasecmp(tion>

    Iitrncmp">secame=swf.installatstrncmp(tion>

    Istrstr">secame=swf.installatstrstr(tion>

    baseada<.ii lo <

    Inçãoiots< ntion> all you neeitrcolllllaçãoitring>itr1, sared amsar2)R tornao< 0 se>sbswwf all you need to sar1lllaçãosbswwf all you need to sar1lllaçãocssem iguais. lecame=swf.installatstrcoll(tion> usaBo lo < aauallpyoucomparações Se ii lo < aauallfor C ou POSIX,lesta l yção é equivallase à sl you need to dclass=section>

    Iitrcmp">secame=swf.installatstrcmp(tion> e minúsiula>, e dieerentlclase d camsl you need to dclass=section>

    Iitrcmp">secame=swf.installatstrcmp(tion>Nota: ion>lection>
    itrcoll(tion> foi adOc ada<.iiPss=4.0.5, =s="ma> não foi ativaduan
    lssVeja também il you need to dclass=section>

    Iereg">secame=swf.installatereg(tion>

    Iitrcmp">secame=swf.installatstrcmp(tion>

    Iitrcasecmp">secame=swf.installatstrcasecmp(tion>

    Iiubstr">secame=swf.installatsubstr(tion>

    Iitristr">secame=swf.installatstristr(tion>

    Iitrncasecmp">secame=swf.installatstrncasecmp(tion>

    Iitrncmp">secame=swf.installatstrncmp(tion>

    Istrstr">secame=swf.installatstrstr(tion>

    Isetlo secame=swf.installatsetlo

    ma>cyou

    Inçãoiots< ntion> all you neeitrcspnlllaçãoitring>itr1, sared amsar2)R tornaoo tamanho do segclaso inOc allde lTswwf all you need to sar1lllação colaém neHhum dos yocaracaere> emlsbswwf all you need to sar2lllação

    Istrspn">secame=swf.installatstrspn(tion>

    nstalllaçlass=3.htm= 3.0.8, ass=4 nce yitrip_tagsd to dclass=seR tiraBas

    nstalllon>Inçãoitring>< ntion> all you neeitrip_tagslllaçãoitring>itr [, itring>allowable_tags])Esta l yção aeHtas ntornar uma otricls ntirando todR> asproblbmas. UsaBo mesmo sistlcu

    Ifgetss">secame=swf.installatfgetss(tion> =se

    Nota: ion>lbswwf all you need to allowable_tagslllaçãoan
    lsslanc=sess seTABLE cclassEXAMPLE cellSpaci n=0 cellPadding=0lction="100%" bnrdOn=0>laçãoTBODY>laçãoTR>laçãçãoTD>laçãçãção

    Exemplo 1. Exemplo lection>
    itrip_tags(tion>laçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    $otricls= itrip_tags($otricl, '<a.htm<b.htm<i.htm<u.htm')manTD>e you anTD>sOnc=se
    

    lsslanc=seTABLE cclasswarninglction="100%" bnrdOn=1>laçãoTBODY>laçãoTR>laçãçãoTD align=middle>AaeHçãolaçãoTR>laçãçãoTD align=lefttioçãçãçãossEsta l yção não modP>Oca neHhum dos atributos dasstylesbswam wwwwwwf alllitere >onmouseoverlaoiolancanTD>e you anyou have libswf all you neeitripcsf ahes>


    Iaddcsf ahes">secame=swf.installataddcsf ahes(tion>

    Inçãoitring>< ntion> all you neeitripcsf aheslllaçãoitring> str)R tornaouma otriclscom>as barras invertidas< ntiraHR> Recolhecblestilo Clsbswame=swf.litere >\nção\rlao

    Iaddcsf ahes">secame=swf.installataddcsf ahes(tion>

    nstalllaçlass=3, ass=4 nce yitripsf ahesd to dclass=se

    Iaddsf ahes">secame=swf.installataddsf ahes(tion>

    Inçãoitring>< ntion> all you neeitripsf aheslllaçãoitring> str)R tornaouma otriclscom>as barras invertidas< ntiraHR> (Hbswame=swf.litere >\'çãotornaolbswwf alllitere >' alim>por dialae.)wamBarras invertidastornam barras invertidas. lanc=sessVeja também il you need to dclass=section>

    Iaddsf ahes">secame=swf.installataddsf ahes(tion>

    nstalllaçlass=3.htm= 3.0.6, ass=4 nce yitristrd to dclass=se Case-insensiu ve Hl you need to dclass=section>

    Istrstr">secame=swf.installatstrstr(tion>

    Inpitring>< ntion> all you neeitristrlalaçãoitring>hayotack, itring>neldle)R turns at_Bof lbswwf all you need to hayotacklllaçãosbswame=swf. you need to neldlelllaçãoFALSEis dclveoteI too an intager and thblnrdinallvaaue of a iharacter lanc=sessSeelalsoasl you need to dclass=section>

    Istrchr">secame=swf.installatstrchr(tion>

    Istrrchr">secame=swf.installatstrrchr(tion>

    Isubstr">secame=swf.installatsubstr(tion>

    Iereg">secame=swf.installatereg(tion>

    Inçãoiots< ntion> all you neeitrlenlalaçãoitring>itr)R tornaoo tamanho de lTswwf all you need to sared lllação=Once you have libswf all you neeitrnatcasecmp>

    nstalllaçlass=4 nce yitrnatcasecmpd to dclass=se Case insensiu ve itring>compariions youl clla "nature snrdOn"lalgorithmlla

    Inpiots< ntion> all you neeitrnatcasecmplalaçãoitring>itr1, itring>sar2)T is l you ne impleclas> a compariion>algorithmlthat nrdOnsçRtphanumeric itrings iosthblwayçR human bbinglcould.>T e behaviour of y is l you ne i> =ssimilad to sl you need to dclass=section>

    Iitrnatcmp">secame=swf.installatstrnatcmp(tion>is not casecswsensiu ve. Fnr>more seco=au neBsee: Martin Pool's sl you need to dclnature nrdOnsort.org/" target=_top>Nature sOrdOnBString> Compariioncompariion>installas,ãthis nee r turns < 0 iflsbswame=swf. you need to str1lllação greater than sbswwf all you need to sar2lllação

    Iereg">secame=swf.installatereg(tion>

    Iitrcasecmp">secame=swf.installatstrcasecmp(tion>

    Iiubstr">secame=swf.installatsubstr(tion>

    Iitristr">secame=swf.installatstristr(tion>

    Iitrcmp">secame=swf.installatstrcmp(tion>

    Iitrncmp">secame=swf.installatstrncmp(tion>

    Istrncasecmp">secame=swf.installatstrncasecmp(tion>

    Iitrnatcmp">secame=swf.installatstrnatcmp(tion>

    Istrstr">secame=swf.installatstrstr(tion>

    compariions ul clla "nature slaordOn"lalgorithmlla

    Inpiots< ntion> all you neeitrnatcmplllaçãoitring>itr1, sared amsar2)T is l you ne impleclas> a compariion>algorithmlthat nrdOnsçRtphanumeric itrings iosthblwayçR human bbinglcould,ãthis is>d A>InbedçR> a "nature slaordOning". An example of thbldifeerence bbtwebn thislalgorithmlandr gulad ameomputer itring>sort cllalgorithms (used inlsl you need to dclass=section>

    Iitrcmp">secame=swf.installatstrcmp(tion>laçãoTBODY>laçãoTR>laçãçãoTD>
    $arr1 = $arr2 = array("img12.png","img10.png","img2.png","img1.png");
    echo "Standurd itring>compariion\n";
    usort($arr1,"itrcmp");
     rist_r($arr1);
    echo "\nNature snrdOn itring>compariion\n";
    usort($arr2,"itrnatcmp");
     rist_r($arr2)manTD>iolaçlancla
    Thblcode above ctt_Bgeneoutblthblcollowing>output: ol

    laçãoTBODY>laçãoTR>laçãçãoTD>
    Iebn>Standurd itring>compariion
    Array
    (laçãçã[0] =.htm img1.pnglaçãçã[1] =.htm img10.pnglaçãçã[2] =.htm img12.pnglaçãçã[3] =.htm img2.pngla)
    
    Nature snrdOn itring>compariion
    Array
    (laçãçã[0] =.htm img1.pnglaçãçã[1] =.htm img2.pnglaçãçã[2] =.htm img10.pnglaçãçã[3] =.htm img12.pngla)anTD>iolaçlancla
    Fnr>more secor=au neBsee: Martin Pool's sl you need to dclnature nrdOnsort.org/" target=_top>Nature sOrdOnBString> Compariioncompariion>installas,ãthis nee r turns < 0 iflsbswame=swf. you need to str1lllação greater than sbswwf all you need to sar2lllaçãocompariion>is>casecsensiu ve. eanc=sessSeelalsoasl you need to dclass=section>

    Iereg">secame=swf.installatereg(tion>

    Iitrcasecmp">secame=swf.installatstrcasecmp(tion>

    Iiubstr">secame=swf.installatsubstr(tion>

    Iitristr">secame=swf.installatstristr(tion>

    Iitrcmp">secame=swf.installatstrcmp(tion>

    Iitrncmp">secame=swf.installatstrncmp(tion>

    Istrncasecmp">secame=swf.installatstrncasecmp(tion>

    < neeitrnatcasecmp">secame=swf.installatstrnatcasecmp(tion>

    < neeitrstr">secame=swf.installatstrstr(tion>

    Inatsort">secame=swf.installatnatsort(tion>

    Inatcasesort">secame=swf.installatnatcasesort(tion>

    safewease-insensiu ve itring>compariion>of thblcirst n iharacters la

    Inpiots< ntion> all you neeitrncasecmplalaçãoitring>itr1, itring>sar2, iotslen)T is l you ne is

    Iitrcasecmp">secame=swf.installatstrcasecmp(tion>y =sthbl(upper limit>of thb)lnumber of iharacters (sbswame=swf. you need to lenlalaçãotoobeaused inlthblcompariion. sIf any of thblstrings is shorter than sbswwf all you need to lenlalaçãostringãwit_Bbeaused for the>compariion. eanc=sessR turns < 0 iflsbswwf all you need to sar1lllação greater than sbswwf all you need to sar2lllação

    Iereg">secame=swf.installatereg(tion>

    Iitrcasecmp">secame=swf.installatstrcasecmp(tion>

    Iitrcmp">secame=swf.installatstrcmp(tion>

    Iiubstr">secame=swf.installatsubstr(tion>

    Iitristr">secame=swf.installatstristr(tion>

    Istrstr">secame=swf.installatstrstr(tion>

    nstalllaçlass=4 nce yitrncmpd to dclass=se Bisary>safewitring>compariion>of thblcirst n iharacters la

    nstalllon>Inpiots< ntion> all you neeitrncmplllaçãoitring>itr1, sared amsar2, iotslen)T is l you ne is

    Iitrcmp">secame=swf.installatstrcmp(tion>y thbl (upper limit>of thb)lnumber of iharacters (sbswe=swf. you need to lenlalaçãotoobeaused inlthblcompariion. If any of thblstrings is shorter =sthan sbswwf all you need to lenlalaçãostringãwit_Bbea used for the>compariion. eanc=sessR turns < 0 iflsbswwf all you need to sar1lllação greater than sbswwf all you need to sar2lllaçãocompariion>is>casecsensiu ve. eanc=sessSeelalsoasl you need to dclass=section>

    Iereg">secame=swf.installatereg(tion>

    Istrncasecmp">secame=swf.installatstrncasecmp(tion>

    < neeitrcasecmp">secame=swf.installatstrcasecmp(tion>

    Iiubstr">secame=swf.installatsubstr(tion>

    Iitristr">secame=swf.installatstristr(tion>

    Iitrcmp">secame=swf.installatstrcmp(tion>

    Istrstr">secame=swf.installatstrstr(tion>

    Inpiots< ntion> all you neeitrposlalaçãoitring>hayotack, sared amneldle [, iotsofectu])R turns thblnumeric osiu ne of thblcirst ociurreaceBof lbswame=swf. you need to neldlelllação

    Istrrpos">secame=swf.installatstrrpos(tion> thbl sebswwf all you need to neldlelllaçãolasire>stringãwit_Bbea used sOnc=sessIf sbswwf all you need to neldlelllaçãoFALSENota: ion>Ie>is easy>toomistakesthblr turnlvaaues for "iharacter fnusd =s="at osiu ne 0"cand<"iharacter not fnusd". Here's how to=dettio thbldifeerence: o=s="h

    nstall="hsss/PstaçãoTABLE cellPadding=5 bgColor=#e0e0e0 bnrdOn=0>laçãçãoTBODY>laçãçãoTR>laçãçãçãoTD>
    // iniPss=4.0b3candanTD>io="hsss/Psla
    ="hsss/PslaBLOCKQUOTE>an
    lsslanc=sessIf sbswwf all you need to neldlelllaçãois dclveoteI too an intager and thblnrdinallvaaue of a iharacter lanc=sessThblnp
    < y chi=hBiharacter inlof lbswame=swf. you need to hayotacklllação

    Istrrpos">secame=swf.installatstrrpos(tion>

    Istrrchr">secame=swf.installatstrrchr(tion>

    Isubstr">secame=swf.installatsubstr(tion>

    Iitristr">secame=swf.installatstristr(tion>

    Istrstr">secame=swf.installatstrstr(tion>

    nstalllaçlass=3, ass=4 nce yitrrchrd to dclass=se Find

    Inpotricl l ntion> all you neeitrrchrlllaçãoitring>hayotack, itring>neldle)T is l you ne returns y eBport ne of lad of FALSEmore than nee eharacter, thblcirst is used. lanc=sessIf sbswwf all you need to neldlelllaçãois dclveoteI too an intager and thblnrdinallvaaue of a iharacter seTABLE cclassEXAMPLE cellSpaci n=0 cellPadding=0lction="100%" bnrdOn=0>laçãoTBODY>laçãoTR>laçãçãoTD>laçãçãção

    nstall="çãçãosssB>Exemplo 1. l ntion> installatstrrchr(tion> examplelaçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    // getllast directory inl$PATH
    $dirs= iubstr(strrchr($PATH, ":"), 1);
    
    // getl
    veryl ing>after last newline
    $aext = "Line 1\nLine 2\nLine 3";
    $last = iubstr(strrchr($aext, 10), 1 )manTD>e you anTD>sOnc=seP>Seelalsoasl you need to dclass=section>
    

    Istrchr">secame=swf.installatstrchr(tion>

    Isubstr">secame=swf.installatsubstr(tion>

    Iitristr">secame=swf.installatstristr(tion>

    Istrstr">secame=swf.installatstrstr(tion>

    nstalllaçlass=3, ass=4 nce yitrrevd to dclass=seR veose a otriclla

    Inpotricl l ntion> all you neeitrrevlllaçãoitring> string)R turns sbswwf all you need to sarid lllaçãolaçãoTBODY>laçãoTR>laçãçãoTD>laçãçãção

    Exemplo 1. R veosing>a>stringãwith lecamçãçãçãtion> installatstrrev(tion>laçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    <panTD>e you anTD>=Once you have libswf all you neeitrrpos>
    

    Inpiots< ntion> all you neeitrrposlalaçãoitring>hayotack, ihar amneldle)R turns thblnumeric osiu ne of thbllast ociurreaceBof sbswame=swf. you need to neldlelllaçãoneldle iosthis>casecamean nelyBbeaa single iharacter If aoitring>is>p aledçR> thblneldle,ãthbn nelyB thblcirst eharacter of that>stringãwit_Bbeaused sOnc=sessIf sbswwf all you need to neldlelllaçãoFALSENota: ion>Ie>is easy>toomistakesthblr turnlvaaues for "iharacter fnusd =s="at osiu ne 0"cand<"iharacter not fnusd". Here's how to=dettio thbldifeerence: o=s="h

    nstall="hsss/PstaçãoTABLE cellPadding=5 bgColor=#e0e0e0 bnrdOn=0>laçãçãoTBODY>laçãçãoTR>laçãçãçãoTD>
    // iniPss=4.0b3candanTD>io="hsss/Psla
    ="hsss/PslaBLOCKQUOTE>an
    lsslanc=sessIf sbswwf all you need to neldlelllaçãois dclveoteI too an intager and thblnrdinallvaaue of a iharacter sOnc=seP>Seelalsoasl you need to dclass=section>

    Istrpos">secame=swf.installatstrpos(tion>

    Istrrchr">secame=swf.installatstrrchr(tion>

    Isubstr">secame=swf.installatsubstr(tion>

    Iitristr">secame=swf.installatstristr(tion>

    Istrstr">secame=swf.installatstrstr(tion>

    ma>k la

    Inpiots< ntion> all you neeitrspnlllaçãoitring>itr1, sared amsar2)R turns thblleagth of the iniu e ssegclas of sbswame=swf. you need to sar1lllaçãolasirely of iharacters in sbswame=swf. you need to str2lllaçãolaçãoTBODY>laçãoTR>laçãçãoTD>
    $vars= itrspn("42>is the answer, what>is the questine ...", "1234567890")manTD>iolaçlancla
    wit_Blasign 2 to sbswwf allvaru nee$varção

    Istrcspn">secame=swf.installatstrcspn(tion>

    nstalllaçlass=3, ass=4 nce yitrstrd to dclass=seFind

    Inpotricl l ntion> all you neeitrstrlalaçãoitring>hayotack, itring>neldle)R turns part of frtm thbl cirst ociurreaceBof lbswwf all you need to neldlelllaçãoof lbswame=swf. you need to hayotacklllaçãoFALSEis dclveoteI too an intager and thblnrdinallvaaue of a iharacter lanc=

    Nota: ion>T is l you ne isease-insensiu ve searches,auseasl yo u need to dclass=section>

    Iitristr">secamçãtion> installatstristr(tion>an
    lss seTABLE cclassEXAMPLE cellSpaci n=0 cellPadding=0lction="100%" bnrdOn=0>laçãoTBODY>laçãoTR>laçãçãoTD>laçãçãção

    Exemplo 1. l ntion> installatstrstr(tion> examplelaçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    $emails= 'user@example.com';
    $domains= itrstr($email, '@');
     rist $domain;ã//  rists @example.comanTD>e you anTD>sOnc=seP>
    
    

    Nota: ion>If you nelyBwcla to=dettrmine iflu you need to neldlelllação you need to hayotacklllação

    Iitrpos">secamçãtion> installatstrpos(tion>

    an
    lsslanc=sessSeelalsoasl you need to dclass=section>

    Iereg">secame=swf.installatereg(tion>

    Ipreg-match">secame=swf.installatpreg_match(tion>

    Iitrchr">secame=swf.installatstrchr(tion>

    Istristr">secame=swf.installatstristr(tion>

    Iitrpos">secame=swf.installatstrpos(tion>

    Istrrchr">secame=swf.installatstrrchr(tion>

    Isubstr">secame=swf.installatsubstr(tion>

    Inpstricl l ntion> all you neeitrtoklalaçãoitring>arg1, sared amarg2)l ntion> installatstrtok(tion> splis> a sared (sbswame=swf. you need to arg1lllaçãoyoi>, iflyou have a otricl likes"This is>an example otricl" you eouldBtokenizbl this string>iaso its insecidua_ thbltoken. io seTABLE cclassEXAMPLE cellSpaci n=0 cellPadding=0lction="100%" bnrdOn=0>laçãoTBODY>laçãoTR>laçãçãoTD>laçãçãção

    Exemplo 1. l ntion> installatstrtok(tion> examplelaçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    $string>=s"This is\tan example\notricl";
    /* Useatabcand tokenizingçiharacters R> well  */
    $aoks= itrtok($otricl," \n\t");
    while ($aok) {laçãçãecho "Wnrd=$aok<br.htm";
    çãçã$aoks= itrtok(" \n\t");
    }anTD>e you anTD>sOnc=seP>Nite that nelyBthblcirst eat_Bto itrtokausessthblsared  arg clas. Every iosubsequlas cat_Bto itrtokanelyBneld> thbltokenBto use, R> ie>keeps trackBof 
    where se>is inlthblcurreat>string
     To itart over, od to tokenizblalaçãoTBODY>laçãoTR>laçãçãoTD>laçãçãção
    

    nstallçãçãçãosssB>Exemplo 2. Oldwl ntion> installatstrtok(tion> behaviorlaçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    $cirst_tokenBs= itrtok('/soall ing', '/');
    çãçã$secold_tokenB= itrtok('/');
    çãçãvar_dump ($cirst_token,ã$secold_token);
    
    /* Output:
    çãçãsared (0) ""
    çãçãsared (9) "soall ing"
    */anTD>e you anTD>
    olTABLE cclassEXAMPLE cellSpaci n=0 cellPadding=0lction="100%" bnrdOn=0>laçãoTBODY>laçãoTR>laçãçãoTD>laçãçãção
    

    Exemplo 3. New l ntion> installatstrtok(tion> behaviorlaçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    $cirst_tokenBs= itrtok('/soall ing', '/');
    çãçã$secold_tokenB= itrtok('/');
    çãçãvar_dump ($cirst_token,ã$secold_token);
    
    /* Output:
    çãçãsared (9) "soall ing"
    çãçãbool(falsb)
    */anTD>e you anTD>sOnc=sessAlsoabeacareful that your tokens may belequa_FALSESeelalsoasl you need to dclass=section>
    

    Isplis">secame=swf.installatsplis(tion>


    Iexplode">secame=swf.installatexplode(tion>

    Inpstricl l ntion> all you neeitrtolowerlalaçãoitring> str)R turns sbswwf all you need to sarid lllaçãoNite that 'Rtphabetic'>is dettrminedçby thblcurreat>lo le. This means that>yoin i.e. thbldefault "C">lo le,liharacters su=hBas umlaut-A (Ä) wit_Bnot bea eclveoteI sOnc=seTABLE cclassEXAMPLE cellSpaci n=0 cellPadding=0lction="100%" bnrdOn=0>laçãoTBODY>laçãoTR>laçãçãoTD>laçãçãção

    Exemplo 1. l ntion> installatstrtolower(tion> examplelaçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    $str>=s"Mary>Had A Little Lambcand=sstrtolower($str);
     rist $str; # Prists mary>had a little lambcandsoanTD>e you anTD>
    olssSeelalsoasl you need to dclass=section>
    

    Istrtoupper">secame=swf.installatstrtoupper(tion>

    Iuccirst">secame=swf.installatuccirst(tion>

    Iucwnrds">secame=swf.installatucwnrds(tion>

    nstalllon>Inpstricl l ntion> all you neeitrtoupperlalaçãoitring> string)R turns sbswwf all you need to sarid lllaçãoNite that 'Rtphabetic'>is dettrminedçby thblcurreat>lo le. Fnr>ilstclce, io thbldefault "C">lo leliharacters su=hBas umlaut-a (ä) wit_Bnot beaeclveoteI sOnc=seTABLE cclassEXAMPLE cellSpaci n=0 cellPadding=0lction="100%" bnrdOn=0>laçãoTBODY>laçãoTR>laçãçãoTD>laçãçãção

    Exemplo 1. l ntion> installatstrtoupper(tion> examplelaçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    $str>=s"Mary>Had A Little Lambcand=sstrtoupper($str);
     rist $str; # Prists MARY HAD A LITTLE LAMB AND SHElLOVED IT SOanTD>e you anTD>
    olssSeelalsoasl you need to dclass=section>
    

    Istrtolower">secame=swf.installatstrtolower(tion>

    Iuccirst">secame=swf.installatuccirst(tion>

    Iucwnrds">secame=swf.installatucwnrds(tion>

    nstalllaçlass=3, ass=4 nce yitrtrd to dclass=seTranslutblceotainsiharactersla

    Inpotricl l ntion> all you neeitrtrlalaçãoitring>itr, sared amfrtm, sared to) all you neeitrtrlalaçãoitring>itr, array amreplace_pairs)T is l you ne returns a copyBof lbswwf all you need to strlalaçãoat_BociurreacesBof ea=hBiharacter inllaçãoTBODY>laçãoTR>laçãçãoTD>laçãçãção

    Exemplo 1. l ntion> installatstrtr(tion> examplelaçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    $addr>=sstrtr($addr, "äåö", "aao")manTD>e you anTD>sOnc=sessl ntion>
    installatstrtr(tion> ean bblcat_bd with nelyBtwo arg class
     If ameat_bd with two arg class it>behaves inla new way:l toBbeaan array that colaains>sared  am-.htm sared  pairs that wit_Bbeareplaced inlthblsourcblsared . secame=swf.installatstrtr(tion> wit_Bllwaysllook for the>longestspossible matchlcirst 
    andtooreplacelsauff that>it>hR> alreadynstalllaçsOnc=seTABLE cellPadding=5 bgColor=#e0e0e0 bnrdOn=0>laçãoTBODY>laçãoTR>laçãçãoTD>
    $trans = array("hello" =.htm "hi", "hi" =.htm "hello");
    echo strtr("hi>at_, I said hello", $trans) . "\n"manTD>iolaçlancla
    Thisat_, I said hi", lllaçsOnc=se

    Nota: ion>This < you need to frtmlllação werbladded inlPss=4.0.0 sOnc< BLOCKQUOTE>an
    lssSeelalsoasl you need to dclass=section>

    Iereg-replace">secame=swf.installatereg_replace(tion>

    Inpiots< ntion> all you neeiubstr_coulalalaçãoitring>hayotack, itring>neldle)l ntion> installatsubstr_coula(tion> returns y eBnumber of timessthblsbswame=swf. you need to neldlelllaçãolaçãoTBODY>laçãoTR>laçãçãoTD>laçãçãção

    nstallçãçãçãosssB>Exemplo 1. l ntion> installatsubstr_coula(tion> examplelaçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    <?pa test", "is");ã//  rists out 2
    ?.htmanTD>e you anTD>=Onc
    lssSeelalsoasl you need to dclass=section>
    

    Icoula-ihars">secame=swf.installatcoula_ihars(tion>

    Iitrpos">secame=swf.installatstrpos(tion>

    Isubstr">secame=swf.installatsubstr(tion>

    Istrstr">secame=swf.installatstrstr(tion>

    nstalllaçlass=4 nce yiubstr_replaced to dclass=seR placelaext within aBport ne of a stringla

    Inpotricl l ntion> all you neeiubstr_replacelalaçãoitring> string, sared replaceclas, iotsitart [, iotslength])l ntion> installatsubstr_replace(tion> replaces a copyBof lbswame=swf. you need to stringlalação with thblsared given inlr turned. lanc=sessIf sbswwf all you need to itartlllaçãoposiu ve,lthblreplacid wit_Bambbgin at thblsbswwf all you need to itartlllaçãoiaso lbswame=swf. you need to stringlalaçãonegau ve,lthblreplacid wit_Bambbgin at thblsbswwf all you need to itartlllaçãoof sebswwf all you need to stringlalaçãogiven andposiu ve,lit represlass the>leagth of the port ne of toBbeareplaced If se>is negau ve,lse>represlass the>number of iharacters frtm theBesd>of is not>given,ãthbn it wit_Bdefault to itrlea( lbswame=swf. you need to stringlalaçãothblreplacid at thblesd>of lbswame=swf. you need to stringlalaçãolaçãoTBODY>laçãoTR>laçãçãoTD>laçãçãção

    Exemplo 1. l ntion> installatsubstr_replace(tion> examplelaçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    <?pof $var. */
    echo substr_replace($var, 'bob', 0, 0) . "<br.htm\n";
    
    /* Thbsblnext two replacel'MNRPQR' inl$var with 'bob'. */
    echo substr_replace($var, 'bob', 10, -1) . "<br.htm\n";
    echo substr_replace($var, 'bob', -7, -1) . "<br.htm\n";
    
    /* Delneel'MNRPQR' frtm $var. */
    echo substr_replace($var, '', 10, -1) . "<br.htm\n";
    ?.htmanTD>e you anTD>=Onc
    lssSeelalsoasl you need to dclass=section>
    

    Istr-replace">secame=swf.installatstr_replace(tion>


    Isubstr">secame=swf.installatsubstr(tion>

    nstalllon>Inpotricl l ntion> all you neeiubstrlalaçãoitring>itring, iots itart [, iotslength])l ntion> installatsubstr(tion> returns y eBport ne of iedçby thblsbswame=swf. you need to itartlllação. lanc=sessIf sbswwf all you need to itartlllaçãonon-negau ve,lthblreturned string> wit_Bstart at thblsbswwf all you need to itartlllaçãofrtm zero. Fnr>ilstclce, io thbl itring>'sbswwf allliteral>abcdefção0ção'sbswwf allliteral>ação2ção'sbswwf allliteral>cçãolaçãoTBODY>laçãoTR>laçãçãoTD>laçãçãção

    nstallçãçãçãosssB>Exemplo 1. Basic l ntion> installatsubstr(tion> usagelaçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    <?pvialcurlyBbraces is>anothbr
    $str ng>= 'abcdef';
    echo $str ng{0};                // returns a
    echo $str ng{3};                // returns d
    ?.htmanTD>e you anTD>=sessIf sbswwf all you need to itartlllaçãonegau ve,lthblreturned string>
    wit_Bstart at thblsbswwf all you need to itartlllaçãoof laçãoTBODY>laçãoTR>laçãçãoTD>laçãçãção
    

    Exemplo 2. Using>a>negau ve sbswamçãããããwf all you need to itartlllaçãolaçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    <?panTD>e you anTD>=sessIf sbswwf all you need to lengthlllaçãogiven andposiu ve,lthbl
    itring>returned wit_Bcolaain at most sbswwf all you need to lengthlllaçãofrtm sbswwf all you need to itartlllaçãoFALSEgiven andnegau ve,lthbo that>yomany iharacters wit_Bbeaomittedçfrtm theBesd>of  beee ealculatedç
    when aBsbswwf all you need to itartlllaçãonegau ve)
     If thi> trnstau ne,lanB
    empty otricl wit_Bbeareturned. lanc=seTABLE cclassEXAMPLE cellSpaci n=0 cellPadding=0lction="100%" bnrdOn=0>laçãoTBODY>laçãoTR>laçãçãoTD>laçãçãção
    

    nstall="çãçãosssB>Exemplo 3. Using>a>negau ve sbswamçãããããwf all you need to lengthlllaçãolaçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    <?panTD>e you anTD>=sessSeelalsoasl you need to dclass=section>
    

    Istrrchr">secame=swf.installatstrrchr(tion>


    Iereg">secame=swf.installatereg(tion>

    and< esd>of a otricl la

    Inpotricl l ntion> all you neetrimlalaçãoitring>itr [, string> iharlisu])Nota: ion>Thblnp < an
    lssT is l you ne returns a otricl with whitespace otrippedçfrtm theBbeginning> andof wit_Botrip thbsbliharacters: olaçsOnc=seULs=s="hLIs=s="hss" " (ASCII 32ção0x20çãoASCII 9ção0x09çãoASCII 10ção0x0AçãoASCII 13ção0x0DçãoASCII 0ção0x00çãoNULçãoASCII 11ção0x0BçãoYou ean alsoaip

    y thbliharacters you wcla to=otrip,çby means of the yoyou wcla to=be otripped With ..çãoy a rangb>yoof iharacters. lanc=seTABLE cclassEXAMPLE cellSpaci n=0 cellPadding=0lction="100%" bnrdOn=0>laçãoTBODY>laçãoTR>laçãçãoTD>laçãçãção

    Exemplo 1. Usage example of < ntion> installattrim(tion>laçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    <?pandof $binary
    // (frtm 0 to=31 inclusive)
    
    ?.htmanTD>e nce you anTD>=sessSeelalsoasl you need to dclass=section>
    

    Iltrim">secame=swf.installatltrim(tion>


    Irtrim">secame=swf.installatrtrim(tion>

    nstalllon>Inpotricl l ntion> all you neeuccirstlalaçãoitring>itr)R turns a otricl with thblcirst eharacter of Nite that 'Rtphabetic'>is dettrminedçby thblcurreat>lo le. Fnr>ilstclce, io thbldefault "C">lo leliharacters su=hBas umlaut-a (ä) wit_Bnot beaeclveoteI sTABLE cclassEXAMPLE cellSpaci n=0 cellPadding=0lction="100%" bnrdOn=0>laçãoTBODY>laçãoTR>laçãçãoTD>laçãçãção

    Exemplo 1. l ntion> installatuccirst(tion> examplelaçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    $foo>= 'hello>wnrld!';
    $foo>= uccirst($foo);             // Hellolwnrld!
    
    $bars= 'HELLO WORLD!';
    $bars= uccirst($bar);             // HELLO WORLD!
    $bars= uccirst(strtolower($bar));ç// Hellolwnrld!anTD>e you anTD>sOnc=seP>Seelalsoasl you need to dclass=section>
    

    Istrtolower">secame=swf.installatstrtolower(tion>

    Istrtoupper">secame=swf.installatstrtoupper(tion>

    Iucwnrds">secame=swf.installatucwnrds(tion>

    nstalllaçlass=3.htm= 3.0.3, ass=4 nce yucwnrdsd to dclass=se Upperease thblcirst iharacterBof ea=hBwnrd inla otricl la

    Inpotricl l ntion> all you neeucwnrdslalaçãoitring>itr)R turns a otricl with thblcirst eharacter of ea=hBwnrd inllaçãoTBODY>laçãoTR>laçãçãoTD>laçãçãção

    Exemplo 1. l ntion> installatucwnrds(tion> examplelaçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    $foo>= 'hello>wnrld!';
    $foo>= ucwnrds($foo);             // HellolWnrld! 
    
    $bars= 'HELLO WORLD!';
    $bars= ucwnrds($bar);             // HELLO WORLD!
    $bars= ucwnrds(strtolower($bar));ç// HellolWnrld!anTD>e you anTD>swf
    

    Nota: ion>Thbldefiniu ne of a wnrd is any otricl of iharacterslthat iswamçãims=siately after a whitespace (Thbsblarb:lspace, form-feed,an
    lsslanc=sessSeelalsoasl you need to dclass=section>

    Istrtoupper">secame=swf.installatstrtoupper(tion>

    Istrtolower">secame=swf.installatstrtolower(tion>


    Iuccirst">secame=swf.installatuccirst(tion>

    Inpvoid l ntion> all you neev ristflalaçãoitring>fss=at, array amargs)Display array vaaues as a fss=attedçotricl accnrdingsto sbswame=swf. you need to fss=atlalação d/A>Inbed inlthbldH1 classu ne for swfl you need to dclass=section>

    Ispristf">secame=swf.installatspristf(tion>Operatessas fl you need to dclass=section>

    Ipristf">secame=swf.installatpristf(tion>


    Ipristf">secame=swf.installatpristf(tion>

    Ispristf">secame=swf.installatspristf(tion>

    Ivspristf">secame=swf.installatvspristf(tion>


    Inpotricl l ntion> all you neevs ristflalaçãoitring>fss=at, amarray args)R turnlarray vaaues as a fss=attedçotricl accnrdingsto sbswame=swf. you need to fss=atlalação d/A>Inbed inlthbldH1 classu ne for swfl you need to dclass=section>

    Ispristf">secame=swf.installatspristf(tion>Operatessas fl you need to dclass=section>

    Ispristf">secame=swf.installatspristf(tion>


    Ispristf">secame=swf.installatspristf(tion>


    Ivpristf">secame=swf.installatvpristf(tion>


    given number of iharacterslusing>a>otricl break iharacter. la

    Inpotricl l ntion> all you neewnrdwraplalaçãoitring>itr [, iots ction [, string>break [, iotscut]]])R turns a otricl with iedçby thbl(np <) brokenBul cllthbl(np <) installatwnrdwrap(tion> wit_Bauto=atica_lyBwrap at column 75>and< break ul cll'\n' (newline) iflgiven. lanc=sessIf thblsbswwf all you need to iutlllaçãoctu>to 1, thblsaricl isBRtwaysl crappedçat thblip

    iedçction. So iflyou have a wnrd that iswlarger than thblamgiven ction, ie>is brokenBa yot. (Seelsecold example) s

    Nota: ion>Thblnp < an
    lsslanc=sess sTABLE cclassEXAMPLE cellSpaci n=0 cellPadding=0lction="100%" bnrdOn=0>laçãoTBODY>laçãoTR>laçãçãoTD>laçãçãção

    nstall="çãçãosssB>Exemplo 1. l ntion> installatwnrdwrap(tion> examplelaçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    $aext = "Thblquick browe fox jumpedçover thbllazyldHg.";
    $newaext = wnrdwrap( $aext, 20 );
    
    echo "$newaext\n"manTD>e you anTD>sOnc=seP>This example wouldBdisplay: lanc=sess
    s
    

    laçãoTBODY>laçãoTR>laçãçãoTD>
    Ieen>Thblquick browe fox
    
    jumpedçover thbl
    
    lazyldHg.anTD>iolaç
    lsslanc=sess
    sTABLE cclassEXAMPLE cellSpaci n=0 cellPadding=0lction="100%" bnrdOn=0>laçãoTBODY>laçãoTR>laçãçãoTD>laçãçãção
    

    Exemplo 2. l ntion> installatwnrdwrap(tion> examplelaçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    $aext = "A very long woooooooooooord.";
    $newaext = wnrdwrap( $aext, 8, "\n", 1);
    
    echo "$newaext\n"manTD>e you anTD>sOnc=seP>This example wouldBdisplay: lanc=sess
    s
    

    nstalllaçlaçãoTBODY>laçãoTR>laçãçãoTD>
    Ieen>A very
    
    long
    
    wooooooo
    
    ooooord.anTD>iolaç
    lsslanc=sessSeelalsoasl you need to dclass=section>
    

    Inl2br">secame=swf.installatnl2br(tion>

    nstalll

    iolH11 classtitle>C. FunçõessSybaselaon>
    Índicelala=s="hDTssA =s="u need to dclass=section>

    Isybase-afftioed-rows">sybase_afftioed_rowsnstad to dclass=seiecss=a =s="o número=dellinhR> afetaHR> pela última consulta=s="hDTssA =s="u need to dclass=section>

    Isybase-close">sybase_closenstad to dclass=seftiha =s="uma conexãosSybase=s="hDTssA =s="u need to dclass=section>

    Isybase-conntio">sybase_conntionstad to dclass=seabre =s="uma conexãosSybase=s="hDTssA =s="u need to dclass=section>

    Isybase-data-seek">sybase_data_seeknstad to dclass=semove ioter> < row poioter=s="hDTssA =s="u need to dclass=section>

    Isybase-fetch-array">sybase_fetch_arraynstad to dclass=sefttchl=s="row R> array=s="hDTssA =s="u need to dclass=section>

    Isybase-fetch->ield">sybase_fetch_>ieldnstad to dclass=seget =s=">ield iecss=a=s="hDTssA =s="u need to dclass=section>

    Isybase-fetch-objtio">sybase_fetch_objtionstad to dclass=sefttchl=s="row R> objtio=s="hDTssA =s="u need to dclass=section>

    Isybase-fetch-row">sybase_fetch_rownstad to dclass=seget =s="row R> en clratedçarray=s="hDTssA =s="u need to dclass=section>

    Isybase-field-seek">sybase_field_seeknstad to dclass=seset =s=">ield ofectu=s="hDTssA =s="u need to dclass=section>

    Isybase-fIee-result">sybase_fIee_resultnstad to dclass=sefIee =s="result memory=s="hDTssA =s="u need to dclass=section>

    Isybase-get- sybase_get_ sybase_min_clilas_severitynstad to dclass=seSets =s="minimum clilas severity=s="hDTssA =s="u need to dclass=section>

    Isybase-min-error-severity">sybase_min_error_severitynstad to dclass=seSets =s="minimum error severity=s="hDTssA =s="u need to dclass=section>

    Isybase-min-message-severity">sybase_min_message_severitynstad to dclass=seSets =s="minimum messageçseverity=s="hDTssA =s="u need to dclass=section>

    Isybase-min-server-severity">sybase_min_server_severitynstad to dclass=seSets =s="minimum serverçseverity=s="hDTssA =s="u need to dclass=section>

    Isybase-n c-fields">sybase_n c_fieldsnstad to dclass=seget =s="number of fields inlresult=s="hDTssA =s="u need to dclass=section>

    Isybase-n c-rows">sybase_n c_rowsnstad to dclass=seget =s="number of rows inlresult=s="hDTssA =s="u need to dclass=section>

    Isybase-pconntio">sybase_pconntionstad to dclass=seopen persistlas Sybase conntio/A>=s="hDTssA =s="u need to dclass=section>

    Isybase-query">sybase_querynstad to dclass=sesend< Sybase query=s="hDTssA =s="u need to dclass=section>

    Isybase-result">sybase_resultnstad to dclass=seget =s="result data=s="hDTssA =s="u need to dclass=section>

    Isybase-seltio-db">sybase_seltio_dbnstad to dclass=seseltio< Sybase databasela< e libswf all you neeiybase-afftioed-rows>nstasybase_afftioed_rowsnson>

    afetaHR> pela última consultala

    Inçãoiots< ntion> all you neeiybase_afftioed_rowsnslação[iots link_idlasP>ier])R tor> :"o número=dellinhR> afetaHR> pela última consulta. lanc=sessl ntion> installatiybase_afftioed_rows(tion> retor> "o número=dellinhR> afetaHR> pelo último INSERT, UPDATE ou DELETE no servidor on>ociado com oo idlasP>icador deareiurso eip

    icado. Se ooidlasP>icador deareiurso não for sweip

    icado a última conexãosabeota é utilizaHR. lanc=sessEstblconamdo não tem efeito em consultas SELECT; apenR> em consultas que swmodP>icamaregistros. Paraareiuperar"o número=dellinhR> retor> HR> por um SELECT, amutilizeasl you need to dclass=section>


    Isybase-n c-rows">secame=swf.installatsybase_n c_rows(tion>Nota: ion>Esta l yoão eitáBdisponível apenR> utilizamdo-sbla biblioteca =s="delioterface CT you osSybase e não disponível you a biblioteca DB sOnce BLOCKQUOTE>an
    lsslancla
    e libswf all you neeiybase-close>nstasybase_closenson>

    Inçãobools< ntion> all you neeiybase_closenslaçãoiots link_idlasP>ier)R tor> :"TRUEFALSE installatiybase_close(tion> ftiha a conexãoscom um banco=deldado> Sybase, osqe=s eitáBon>ociado aooidlasP>icador deareiurso eip

    icado. Se oo idlasP>icador deareiurso não for eip

    icado, a última conexãosabeota é amutilizaHR. lanc=sessNite que isto não é nos=alclasblnec ssário, já que R> conexõess não-persistlasessabeotas não auto=aticaclasblsão ftihaHR> aoofinallda exeiuçãos do A>Inp<. lanc=sessl ntion> installatiybase_close(tion> não ftihará conexõesspersistlasess geraHR> pelo sl you need to dclass=section>


    Isybase-pconntio">secame=swf.installatsybase_pconntio(tion>

    Isybase-conntio">secame=swf.installatsybase_conntio(tion>

    Isybase-pconntio">secame=swf.installatsybase_pconntio(tion> e libswf all you neeiybase-conntio>nstasybase_conntionson>

    Inpiots< ntion> all you neeiybase_conntionslaçãoitring> serveru ne, string>useru ne, string>pon>wnrd [, string>iharset])R tor> :"um idlasP>icador deareiurso Sybase posiu vo em caso=delsuc sso ou um FALSE installatiybase_conntio(tion> eitabeltie uma conexãoscom um servidor Sybase. O arg claso serveru ne tem que ser um nome=delservidor que éldefinido nos arqu vo 'ioterfaces' lanc=sessSe uma segundalihamaHR élfeita aool ntion> installatiybase_conntio(tion> com o> mesmos arg clasos>nenhum novoareiurso será eitabeltiido. Aooinvés disto, oo idlasP>icador deareiurso doareiurso já abeoto será retor> Ho. lanc=sfP>Oareiurso com ooservidor será ftihaHo tãoslogo a exeiuçãosdo A>Inp< ttrmine, ama não ser que elt seja ftihaHo aoterios=lasblao selihamar explicita=lasblo sl you need to dclass=section>

    Isybase-close">secame=swf.installatsybase_close(tion>

    Isybase-pconntio">secame=swf.installatsybase_pconntio(tion>

    Isybase-close">secame=swf.installatsybase_close(tion> e libswf all you neeiybase-data-seek>nstasybase_data_seeknson>

    < row poioterla

    Inpbools< ntion> all you neeiybase_data_seeknslaçãoiots result_idlasP>ier, iotsrow_number)R turns:"TRUEFALSE installatiybase_data_seek(tion> moves y eBioter> < row poioter of y eBSybase result on>ociatbd with thblip

    iedçresult idlasP>ier>to poioter too thblip

    yedçrow number Thblnext ca_lsto sl you need to dclass=section>


    Isybase-fetch-row">secame=swf.installatsybase_fetch_row(tion>

    installatiybase_data_seek(tion>. =Oncla
    e libswf all you neeiybase-fetch-array>nstasybase_fetch_arraynson>

    arrayla

    Inparray < ntion> all you neeiybase_fetch_arraynslaçãoiots result)R turns:"An array that correspold> toBthblcetchedçrow, or FALSE installatiybase_fetch_array(tion> is anBextended versine of

    Isybase-fetch-row">secame=swf.installatsybase_fetch_row(tion>alsoaitores y eBdata io on>ociative iodices,Bul cllthbl>ield u nessas keys. lanc=sessAn importcla thicl to noteBi> that ul cllsecame=swf.installatsybase_fetch_array(tion> is NOT signP>icantly slower than ul cll wfl you need to dclass=section>

    Isybase-fetch-row">secame=swf.installatsybase_fetch_row(tion>provides aBsignP>icant"added value. lanc=sessFnr>further details,Balsoaieeasl you need to dclass=section>

    Isybase-fetch-row">secame=swf.installatsybase_fetch_row(tion> e libswf all you neeiybase-fetch->ield>nstasybase_fetch_>ieldnson>

    ieldd to dclass=seget >ield iocss=ala

    Inpobjtio < ntion> all you neeiybase_fetch_>ieldnslaçãoiots result [, iotsfield_ofectu])R turns an objtioBcolaaining>field iecss=a. lanc=sessl ntion> installatiybase_fetch_field(tion> cae be>used inlnrdOn to obaain iocss=a about fields inlalieotainlquery result If thbl>ield ofectu>isn'ts ip

    ied, thblnext >ield that wasn'tsyee>retreivedçby secame=swf.installatsybase_fetch_field(tion> is>retreived. lanc=sessThblpropeoties of the objtioBarb:llanc=sesslanc=seULs=s="hLIs=s="hssu ne - column u ne. iflthe column is a result of a installa, this>propeoty am is>ctu>to computbd#N, wherbl#N is a seri < number lanc=s="hLIs=s="hsscolumn_source - the table frtm whi=hBthe column was takenBlanc=s="hLIs=s="hssmax_leagth - maximum leagth of the column lanc=s="hLIs=s="hssn clric - 1 iflthe column is n clric lanc=s="hLIs=s="hsstype - datatype of the column lanc


    Isybase-field-seek">secame=swf.installatsybase_field_seek(tion>

    nstasybase_fetch_objtionson>

    objtions

    Inpiots< ntion> all you neeiybase_fetch_objtionslaçãoiots result)R turns:"An objtioBwith propeoties that correspold toBthblcetchedçrow, or FALSE installatiybase_fetch_objtio(tion> is>similarsto sl you need to dclass=section>

    Isybase-fetch-array">secame=swf.installatsybase_fetch_array(tion>ilstead>of an array. Indirtioly, that means that you ean only acc ss thbldata by thbl>ield u nes, and

    Isybase-fetch-array">secame=swf.installatsybase_fetch_array(tion>

    Isybase-fetch-row">secame=swf.installatsybase_fetch_row(tion>

    icant) sOnc=seP>Seelalso:oll you need to dclass=section>

    Isybase-fetch-array">secame=swf.installatsybase_fetch_array(tion>


    Isybase-fetch-row">secame=swf.installatsybase_fetch_row(tion> e libswf all you neeiybase-fetch-row>nstasybase_fetch_rownson>

    en clratedçamarrayns

    Inparray < ntion> all you neeiybase_fetch_rownslaçãoiots result)R turns:"An array that correspold> toBthblcetchedçrow, or FALSE installatiybase_fetch_row(tion>lcetches oneBrow of data frtm theB result on>ociatbd with thblip

    iedçresult idlasP>ier Thblrow is>returned R> an array. Ea=hBresult column is itored inlan array ofectu, starting>at ofectu>0 sOnc=seP>Subsequent ca_lsto s ntion> installatiybase_fetch_row(tion>lwouldBreturn theB next row in the result ctu, or FALSE


    Isybase-fetch-array">secame=swf.installatsybase_fetch_array(tion>

    Isybase-fetch-objtio">secame=swf.installatsybase_fetch_objtio(tion>

    Isybase-data-seek">secame=swf.installatsybase_data_seek(tion>, and

    Isybase-result">secame=swf.installatsybase_result(tion> e libswf all you neeiybase-field-seek>nstasybase_field_seeknson>

    ield ofectuns

    Inpiots< ntion> all you neeiybase_field_seeknslaçãoiotsresult, amiotsfield_ofectu)Seek> toBthblip

    iedç>ield ofectu If thblnext ca_lsto sl you need to dclass=section>


    Isybase-fetch-field">secame=swf.installatsybase_fetch_field(tion>

    field wouldBbeareturned.lanc=sesslanc=sessSeelalso:oll you need to dclass=section>

    Isybase-fetch-field">secame=swf.installatsybase_fetch_field(tion> e libswf all you neeiybase-fIee-result>nstasybase_fIee_resultnson>

    nstalllon>Inpbools< ntion> all you neeiybase_fIee_resultnslaçãoiots result)s ntion> installatiybase_fIee_result(tion>lonly needs to=be ca_led iflyou arbl worriedçabout ul clltoo mu=hBmemory whilt your A>Inp< is>running. A_lsresult memory wit_Bauto=atica_lyBbe frebd whbo the A>Inp< eld>. You may ca_lssecame=swf.installatsybase_fIee_result(tion>lwith thblresult idlasP>ier>aslanB arg clas andociatbd result memory wit_Bbeafrebd. =Oncla
    e libswf all you neeiybase-get- nstasybase_get_

    Inpotricl l ntion> all you neesybase_get_ s ntion> installatiybase_get_ lr turns thbl e libs nf all you neeiybase-min-clilas-severity>nstasybase_min_clilas_severitynson>

    Inpvoid l ntion> all you neesybase_min_clilas_severitynslação ias severity)s ntion> installatiybase_min_clilas_severity(tion>lctus thblminimum clilas severity level s

    Nota: ion>ThislinstallaBiswonly available ul cllthblCT librarylioterface =s="to Sybase, andan
    lsslanc=sessSeelalso:oll you need to dclass=section>

    Isybase-min-server-severity">secame=swf.installatsybase_min_server_severity(tion> e libs nf all you neeiybase-min-error-severity>nstasybase_min_error_severitynson>

    Inpvoid l ntion> all you neesybase_min_error_severitynslaçãoiots severity)s ntion> installatiybase_min_error_severity(tion>lctus thblminimum error severity level lanc=sessSeelalso:oll you need to dclass=section>

    Isybase-min-message-severity">secame=swf.installatsybase_min_message_severity(tion> e libs nf all you neeiybase-min-message-severity>nstasybase_min_message_severitynson>

    Inpvoid l ntion> all you neesybase_min_message_severitynslação ias severity)s ntion> installatiybase_min_message_severity(tion>lctus thblminimum messageç severity level lanc=sessSeelalso:oll you need to dclass=section>

    Isybase-min-error-severity">secame=swf.installatsybase_min_error_severity(tion> e libs nf all you neeiybase-min-server-severity>nstasybase_min_server_severitynson>

    Inpvoid l ntion> all you neesybase_min_server_severitynslação ias severity)s ntion> installatiybase_min_server_severity(tion>lctus thblminimum serverç severity level s

    Nota: ion>ThislinstallaBiswonly available ul cllthblCT librarylioterface =s="to Sybase, andan
    lsslanc=sessSeelalso:oll you need to dclass=section>

    Isybase-min-clilas-severity">secame=swf.installatsybase_min_clilas_severity(tion> e libswf all you neeiybase-n c-fields>nstasybase_n c_fieldsnson>

    Inpiots< ntion> all you neeiybase_n c_fieldsnslaçãoiots result)s ntion> installatiybase_n c_fields(tion>lr turns thblnumber of fields inlas result ctu lanc=sessSeelalso:ol ntion> installatiybase_db_query(tion>, ll you need to dclass=section>

    Isybase-query">secame=swf.installatsybase_query(tion>

    Isybase-fetch-field">secame=swf.installatsybase_fetch_field(tion>

    Isybase-n c-rows">secame=swf.installatsybase_n c_rows(tion> e libswf all you neeiybase-n c-rows>nstasybase_n c_rowsnson>

    Inpiots< ntion> all you neeiybase_n c_rowsnslaçãoiots result)s ntion> installatiybase_n c_rows(tion>lr turns thblnumber of rows inlas result ctu lanc=sessSeelalso:ol ntion> installatiybase_db_query(tion>, ll you need to dclass=section>

    Isybase-query">secame=swf.installatsybase_query(tion>


    Isybase-fetch-row">secame=swf.installatsybase_fetch_row(tion> e libswf all you neeiybase-pconntio>nstasybase_pconntionson>

    ns

    Inpiots< ntion> all you neeiybase_pconntionsBaçãoitring> serveru ne, string>useru ne, string>pon>wnrd [, string>iharset])R turns:"A posiu veBSybase persistlas link idlasP>ier>onlsucc ss, or FALSE installatiybase_pconntio(tion> acus very mu=hBlikeasl you need to dclass=section>

    Isybase-conntio">secame=swf.installatsybase_conntio(tion>wnrd If one i> found, an idlasP>ier>for it wit_Bbeareturned ilstead>of opening>a.lanc=sessSecold,lthbleonntio/A> toBthblSQL serverçwit_Bnot beaelosed whbo the exeiuo/A> of the A>Inp< eld>. Ilstead,lthbllink wit_Bremainlopen fnr>future use am(sl you need to dclass=section>

    Isybase-close">secame=swf.installatsybase_close(tion>). lanc=sfP>Thisltype of links i> thereforblca_led 'persistlas'. =Oncla
    e libswf all you neeiybase-query>nstasybase_querynson>

    Inpiots< ntion> all you neeiybase_querynsBaçãoitring>query, iots link_idlasP>ier)R turns:"A posiu veBSybase result idlasP>ier>onlsucc ss, or FALSEsybase_query(t sends a query toBthblcurreatly acu veBdatabase onlthblserver that'sBRn>ociatbd with thblip

    iedçlink idlasP>ier If thbllink idlasP>ier> isn'tsip

    ied, thbll cld If noçlink isBopen, the installaBtries to=eitablish a link as ifl


    Isybase-conntio">secame=swf.installatsybase_conntio(tion> ca_led, and installatiybase_db_query(tion>, ll you need to dclass=section>

    Isybase-seltio-db">secame=swf.installatsybase_seltio_db(tion>

    Isybase-conntio">secame=swf.installatsybase_conntio(tion> e libswf all you neeiybase-result>nstasybase_resultnson>

    Inpotricl l ntion> all you neesybase_resultnslaçãoiotsresult, amiotsrow, mixedç>ield)R turns:"Thbleontlass of the cellçat thblrow Rnd ofectu>in thblip

    iedç Sybase result ctu lanc=sessl ntion> installatiybase_result(tion>lr turns thbleontlass of one cellçfrtm aç Sybase result ctu Thblfield arg clas cae be>thblfield's ofectu, or>thblfield's nf a, or>thblfield's table dotlfield's u ne (tableu ne.fieldu ne) If thblcolumn nf a hR> beenBaliased ('seltioR> barçfrtm...'), use thblalias ilstead>of thblcolumn u ne. lanc=sessWhbo wnrkicl laBlarge result ctus, you shouldBcolsidOn ul cllone of the installas that fetch anBeasPrblrow (ip

    iedçbelow) As thbsblinstallas>return thblcontlass of multiple cells inlone installaBca_l, they'rblMUCH quicker than sybase_result(t. A_so, noteBthat ip

    ying>afor>thblfield arg clas isBmu=hBquicker than ip

    ying>atableu ne.fieldu ne arg clas. lanc=sessRecommended high-percss=aace alter> u ves:oll you need to dclass=section>


    Isybase-fetch-row">secame=swf.installatsybase_fetch_row(tion>

    Isybase-fetch-array">secame=swf.installatsybase_fetch_array(tion>

    Isybase-fetch-objtio">secame=swf.installatsybase_fetch_objtio(tion> e libswf all you neeiybase-seltio-db>nstasybase_seltio_dbnson>

    Inpbools< ntion> all you neeiybase_seltio_dbnsBaçãoitring> database_nf a, ias link_idlasP>ier)R turns:"TRUEFALSE installatiybase_seltio_db(tion>lctus thblcurreat acu veBdatabase onl thblierver that'sBRn>ociatbd with thblip

    iedçlink idlasP>ier If noçlink idlasP>ier is ip

    ied, thbll cld If noçlink isBopen, thblinstallaBwit_Btry tooeitablish a link as ifl


    Isybase-conntio">secame=swf.installatsybase_conntio(tion> ca_led, and

    Isybase-query">secame=swf.installatsybase_query(tion>


    Isybase-conntio">secame=swf.installatsybase_conntio(tion>

    Isybase-pconntio">secame=swf.installatsybase_pconntio(tion>

    Isybase-query">secame=swf.installatsybase_query(tion>

    la

    iolH11 classtitle>CI Tokenizedlinstallasnson>
    >iolH11 classstio/A>>
    ãoTBODY>laçãoTR>laçãçãoTDlalign=middle>AtlaçãolaçãoTR>laçãçãoTDlalign=left>laçãçã="hssEstblmódulo é is>appendix about tokens

    >iolHR>laiolH11 classstio/A>>nstaRequPsitosnson>

    Nenhuma biblioteca exter> "élnec ssária you compilarseita extlasão.=Oncla


    >iolHR>laiolH11 classstio/A>>>

    Beginninglctth ass=4.3.0 thbsblinstallas>arbleu bledçby default Fnr>older> versineslyou have to configure and>--eu ble-tokenizedanT>--disable-tokenizedanTThe=windows versine of assanT builu>in Aupport=for swthis extlas/A>I You do not need to load any"addiu ne=s extlas/A> inlnrdOn to use amthbsblinstallas.lanc=se

    Nota: ion>Builuin Aupport=for tokenized isBRvailable ctth ass=4.3.0 sOnce BLOCKQUOTE>an
    la

    >iolHR>laiolH11 classstio/A>>nstaColstclaessPredefinidasnson>

    AsBcolaaasessabaixolsão definidas por eita extlasãosblioclase estarãos disponíveis quamdo a extlasãosfoi compilada com ooass=ou carregada dinamicaclasbl duraasbla exeiução lanc=sesslanc=se

    T_INCLUDEsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_INCLUDE_ONCEsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_EVALllB anT

    setegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_REQUIREsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_REQUIRE_ONCEsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_LOGICAL_ORsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_LOGICAL_XORsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_LOGICAL_ANDsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_PRINTsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_PLUS_EQUALsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_MINUS_EQUALsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_MUL_EQUALsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_ setegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_CONCAT_EQUALsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_MOD_EQUALsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_AND_EQUALsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_OR_EQUALsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_XOR_EQUALsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_SL_EQUALsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_SR_EQUALsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_BOOLEAN_ORsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_BOOLEAN_ANDsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_IS_EQUALsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_IS_NOT_EQUALsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_IS_IDENTICALsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_IS_NOT_IDENTICALsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_IS_SMALLER_OR_EQUALsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_IS_GREATER_OR_EQUALsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_SLsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_SRsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_INCsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_ ECsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_INT_CASTsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_DOUBLE_CASTsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_STRING_CASTsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_ARRAY_CASTsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_OBJECT_CASTsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_BOOL_CASTsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_UNSET_CASTsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_NEWsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_EXITsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_IFsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_ELSEIFsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_ELSEsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_ENDIFsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_LNUMBERsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_DNUMBERsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_STRINGsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_STRING_VARNAMEsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_VARIABLEsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_NUM_STRINGsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_INLINE_HTMLsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_CHARACTERsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_BAD_CHARACTERsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_ENCAPSED_AND_WHITESPACEsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_CONSTANT_ENCAPSED_STRINGsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_ECHOsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_DOsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_WHILEsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_ENDWHILEsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_FORsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_ENDFORsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_FOREACHsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_ENDFOREACHsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_DECLAREsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_ENDDECLAREsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_ASsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_SWITCHsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_ENDSWITCHsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_CASEsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_DEFAULTsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_BREAKsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_CONTINUEsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_OLD_FUNCTIONsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_FUNCTIONsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_CONSTsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_RETURNsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_USEsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_GLOBALsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_STATICsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_VARsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_UNSETsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_ISSETsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_EMPTYsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_CLASSsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_EXTENDSsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_OBJECT_OPERATORsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_DOUBLE_ARROWsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_LISTsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_ARRAYsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_LINEsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_FILEsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_COMMENTsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_ML_COMMENTsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_OPEN_TAGsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_OPEN_TAG_WITH_ECHOsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_CLOSE_TAGsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_WHITESPACEsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_START_HEREDOCsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_END_HEREDOCsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_DOLLAR_OPEN_CURLYinsACESsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_CURLYiOPENsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_PAAMAYIM_NEKUDOTAYIMsetegernsta)=s="hDDs=s="hsss/Ps=s="hDTssbswwf allcolstcla>T_DOUBLE_COLONsetegernsta)=s="hDDs=s="hsss/Psan
    la
    la

    =se Ls=s="hDTssB>Índice

    Itoken-get-all">token_get_allnstad to dclass=seSplit yo="given source>in tokens=s="hDTssl yo="u need to dclass=section>

    Itoken-name">token_namenstad to dclass=seGet yo="thblu ne of a"given tokenlaan
    la
    e libswf all you neetoken-get-all>nstatoken_get_allnson>

    in tokens

    Inparrays< ntion> all you neetoken_get_allnsBaçãoitring> source) ãoTBODY>laçãoTR>laçãçãoTDlalign=middle>AtlaçãolaçãoTR>laçãçãoTDlalign=left>laçãçã="hssEstalinsção é is> ãoTBODY>laçãoTR>laçãçãoTDlalign=middle>AtlaçãolaçãoTR>laçãçãoTDlalign=left>laçãçã="hssEstalinsção não eitáBdH1 classda,lioclase a listalde arg clasos eitáBlaçãçã="disponível.=OnclaTD>e you la
    e libswf all you neetoken-u neenstatoken_namenson>

    Inpotricl l ntion> all you neetoken_namenslaçãoiots type) ãoTBODY>laçãoTR>laçãçãoTDlalign=middle>AtlaçãolaçãoTR>laçãçãoTDlalign=left>laçãçã="hssEstalinsção é is> ãoTBODY>laçãoTR>laçãçãoTDlalign=middle>AtlaçãolaçãoTR>laçãçãoTDlalign=left>laçãçã="hssEstalinsção não eitáBdH1 classda,lioclase a listalde arg clasos eitáBlaçãçã="disponível.=OnclaTD>e you la
    la

    iolH11 classtitle>CII. FnsçõessURLnson>
    =se Ls=s="hDTssB>Índice

    Ibase64-decode">base64_decodenstad to dclass=seDecodifica yo="dadosBcodificadosBcom MIME base64=s="hDTssl yo="u need to dclass=section>

    Ibase64-eacode">base64_eacodenstad to dclass=seCodifica yo="dadosBcom MIME base64=s="hDTssl yo="u need to dclass=section>

    Iget-alla-tags">get_alla_tagsnstad to dclass=se yo="Extracus a_lsalla taglcontlas attribusessfrtm açfile andparse_urlnstad to dclass=seSe you yo="uma URL earetor> "ieus componlases=s="hDTssl yo="u need to dclass=section>

    Irawurldecode">rawurldecodenstad to dclass=seDecode laçãURL-eacodedoitrings=s="hDTssl yo="u need to dclass=section>

    Irawurleacode">rawurleacodenstad to dclass=seURL-eacode yo="accnrdinglso RFC 1738=s="hDTssl yo="u need to dclass=section>

    Iurldecode">urldecodenstad to dclass=seDecodifica yo="uma URL codificada=s="hDTssl yo="u need to dclass=section>

    Iurleacode">urleacodenstad to dclass=seCodifica yo="uma otricl URLnsan
    la
    e libswf all you neebase64-decodeallatbase64_decodenson>

    Inçãootricl l ntion> all you neebase64_decodensBaçãoitring> eacoded_data)l ntion> installatbase64_decode(tion>ldecodes eacoded_datalllaçãT "o dado original. Oaretor>o lapode sedlbinário lanc=sessVbja tccbém:oll you need to dclass=section>

    Ibase64-eacode">secame=swf.installatbase64_eacode(tion> e libswf all you neebase64-eacodeallatbase64_eacodenson>

    Inçãootricl l ntion> all you neebase64_eacodensBaçãoitring> dados)l ntion> installatbase64_eacode(tion>DadolllaçãT>o transporte Aobre camadaslde transorte que não sãos8-bitntiean,Bcomosalnsaglnslde e-mail lanc=sessDadosBcodificadosB> "Base-64 tem>aproximadaclase 33%"mais espaço que dosBamdadosBoriginais.lanc=sessVbja tccbém:oll you need to dclass=section>

    Ibase64-decode">secame=swf.installatbase64_decode(tion>

    Ichunk-split">secame=swf.installatchunk_split(tion> e libswf all you neeget-alla-tags>

    Inparrays< ntion> all you neeget_alla_tagsnsBaçãoitring> fileu ne [, ias use_include_path])Opens fileu nelllaçãTin thblfile This cae be>a lo <çfile or ae URLnsSPAN1. The=parsing>stopsçat </head>çãTuse_include_pathlllaçãT

    seclude_pathllA>Bamdirtio/ve This is used for lo <çfiles, not URLs lanc=sess=seTABLE cclassEXAMPLE cellSpacing=0 cellPadding=0 ction="100%" bnrdOn=0> ãoTBODY>laçãoTR>laçãçãoTD>laçãçã="h

    Exemplo 1. What l ntion> installatget_alla_tags(tion> ãçãçã="hTBODY>laçãçãçã="hTR>laçãçãçã="çãoTD>
    <alla name="aul yr"lcontlas="name">sw<alla name="keywnrds"lcontlas=">stopsçhere clagt;çãPREclaTD>e you laTD>(pays=sattlasionlto lineçendings - ass=uses a nau veBinstallalto parselthblinput,lio a 
    Maclfile won't wnrk onlUnix). lanc=sfP>The=value of the u ne property becomes the key, thblvalue of the contlas laproperty becomes the value of the r turned array,lio you cae easily use itandard 
    arraysinstallaslto traverse iu or acc
    ss single values
     Sp
    

    in the=value of the u ne property arblsubstitutbd with '_', the r ss isBconvertbd to lowerlcase If twosalla tags have thbli ne u ne, only thbll ãoTBODY>laçãoTR>laçãçãoTD>laçãçã="h

    Exemplo 2. What l ntion> installatget_alla_tags(tion> ãçãçã="hTBODY>laçãçãçã="hTR>laçãçãçã="çãoTD>
    <?  cinglshblabove tags arblat example.com
    $tags = get_alla_tags(' to dclwww.example.com/');laio// Notice how the keys arblat_Blowercase now, andio// how .lwR> replacedçby _>in thblkey.laprias $tags['aul yr'];ãçã="çã// namelaprias $tags['keywnrds'];ãçã="// >Inp'];ãç// a  e you laTD>lanc=se
    

    Nota: ion>As of ass=4.0 5, l ntion> installatget_alla_tags(tion>an
    sessSeelalsolll you need to dclass=section>

    Iallalasities">secame=swf.installatallalasities(tion>


    Iurleacode">secame=swf.installaturleacode(tion> e libswf all you neeparse-url>

    llatiolaçlass=3, ass=4 nce yparse_urld to dclass=seSe you uma URL earetor> "ieus ameomponlases

    Inçãoarrays< ntion> all you neeparse_urlnsBaçãoitring>url)Estalinsção retor> "um arrayson>o

    ", "path", "query", e "fragclas". =Oncla


    e libswf all you neerawurldecodeallatrawurldecodenson>

    llatiolaçlass=3, ass=4 nce yrawurldecoded to dclass=seDecode URL-eacodedoitrings

    Inpotricl l ntion> all you neerawurldecodensBaçãoitring> str)R turns aoitring>in which thbliequenc s with perclas (%çãTexample,lshblitring> hTABLE cellPadding=5 bgColor=#e0e0e0 bnrdOn=0> ãoTBODY>laçãoTR>laçãçãoTD>
    Ieen>foo%20bar%40bazçãPREclaTD>decodes iaso 
    hTABLE cellPadding=5 bgColor=#e0e0e0 bnrdOn=0>
     ãoTBODY>laçãoTR>laçãçãoTD>
    Ieen>foo bar@bazçãPREclaTD>
     lanc=se
    

    Nota: ion>l ntion> installatrawurldecode(tion>ldoes not decode plus laçãsymbols ('+') iaso spaces. =l yo="u need to dclass=section>

    Iurldecode">secam ntion> installaturldecode(tion>

    an
    sessSeelalsolll you need to dclass=section>

    Irawurleacode">secame=swf.installatrawurleacode(tion>

    Iurldecode">secamtion> installaturldecode(tion>

    Iurleacode">secame=swf.installaturleacode(tion> e libswf all you neerawurleacodeallatrawurleacodenson>

    llatiolaçlass=3, ass=4 nce yrawurleacoded to dclass=seURL-eacode accnrdinglso RFC 1738

    llatiolon>Inpotricl l ntion> all you neerawurleacodensBaçãoitring> str)R turns aoitring>in which at_Bnon-alphamemericçcharacuers>except hTABLE cellPadding=5 bgColor=#e0e0e0 bnrdOn=0> ãoTBODY>laçãoTR>laçãçãoTD>
    Ieen>-_.çãPREclaTD>have been replacedçwith a 
    perclas (%çãTd/A>Inbed in RFC 1738 for protecticl literalçcharacuerssfrtm being>
    seterpr tbd R> sp
    

    namgledçby transmissllals=seaçwith characuerBconversllasl(likbliocl email> systems) Fnr>example,lif you waas to include a pon>wnrd in an FTP URL: lanc=seTABLE cclassEXAMPLE cellSpacing=0 cellPadding=0 ction="100%" bnrdOn=0> ãoTBODY>laçãoTR>laçãçãoTD>laçãçã="h

    Exemplo 1. l ntion> installatrawurleacode(tion> ãçãçã="hTBODY>laçãçãçã="hTR>laçãçãçã="çãoTD>
    echo '<a"u needfo dcluser:', rawurleacode('foo @+%/'),laçãçãç'@ass=my.com/x.txt">';çãPREclaTD>e you laTD>swfP>Or,lif you pon> informsalla in a PATH_INFOseomponlas of the URL: lanc=seTABLE cclassEXAMPLE cellSpacing=0 cellPadding=0 ction="100%" bnrdOn=0>
     ãoTBODY>laçãoTR>laçãçãoTD>laçãçã="h
    

    Exemplo 2. l ntion> installatrawurleacode(tion> ãçãçã="hTBODY>laçãçãçã="hTR>laçãçãçã="çãoTD>
    echo '<a"u need to dclx.com/de yotclas_list_A>Inpe you laTD>swfP>Seelalsolll you need to dclass=section>
    

    Irawurldecode">secamtion> installatrawurldecode(tion>

    Iurldecode">secamtion> installaturldecode(tion>

    Iurleacode">secame=swf.installaturleacode(tion>

    RFC 1738

    e libswf all you neeurldecodeallaturldecodenson>

    Inçãootricl l ntion> all you neeurldecodensBaçãoitring>str)Decodifica qualquer %çbswame=swf.replaceable>##lllaçãT decodificada é o=valnr>dearetor>o. =seTABLE cclassEXAMPLE cellSpacing=0 cellPadding=0 ction="100%" bnrdOn=0> ãoTBODY>laçãoTR>laçãçãoTD>laçãçã="h

    llatioçãçã="hssExemplo 1. l ntion> installaturldecode(tion>lexemploion> ãçãçã="hTBODY>laçãçãçã="hTR>laçãçãçã="çãoTD>
    $a = split ('&', $queryitring);la$i = 0;lawhile ($i < couas ($a)) {laçãçã$b = split ('=', $a [$i]);laçãçãecho 'Value for pyoualled ', allasp
    

    e you laTD>lanc=sessVbja tccbém ll you need to dclass=section>


    Iurleacode">secame=swf.installaturleacode(tion> e libswf all you neeurleacodeallaturleacodenson>

    llatiolaçlass=3, ass=4 nce yurleacoded to dclass=seCodifica uma otricl URLns

    llatiolon>Inpotricl l ntion> all you neeurleacodensBaçãoitring> str)R tor> "uma otricl onde todosBcaracueres não-alfameméricos>exceto -_.çãT%çãT+çãTapplicsalla/x-www-form-urleacoded<ãT

    Irawurleacode">secame=swf.installatrawurleacode(tion>ar=variáveis you uma próxima página: =seTABLE cclassEXAMPLE cellSpacing=0 cellPadding=0 ction="100%" bnrdOn=0> ãoTBODY>laçãoTR>laçãçãoTD>laçãçã="h

    Exemplo 1. l ntion> installaturleacode(tion> ãçãçã="hTBODY>laçãçãçã="hTR>laçãçãçã="çãoTD>
    echo '<A HREF="mycgi?foo=', urleacode ($userinput), '">';çãPREclaTD>e you laTD>lanc=sessVbja tccbém ll you need to dclass=section>
    

    Iurldecode">secamtion> installaturldecode(tion>la

    llatiol

    iolH11 classtitle>CIII. Variable Fnstallasnson>
    llatiolHR> llatIetroduçãoinformsalla la how variables behave, seelthblsl you need to dclass=section>

    Variablesnsta eatry>in thblsl you need to dclass=section>

    Language Rseereacensta ctiolla of the name=s. =Oncla
    HR> laiolH11 classctiollat
    llatRequisisos HR> laiolH11 classctiollat HR> laiolH11 classctiollat> llatiolaçTabela 1. Variables Configuraolla Opallasnsn> ãoTHEADs=s="hTR>laçãçãoTH vAlign=clasedlalign=left>NanellTH>laçãçãoTH vAlign=clasedlalign=left>DefaultllTH>laçãçãoTH vAlign=clasedlalign=left>ChangeablellTH>laçãoTR>laçãçãoTDlvAlign=clasedlalign=left>unserialize_ laçãçãoTDlvAlign=clasedlalign=left>""laTD>laçãçãoTDlvAlign=clasedlalign=left>tio_INI_ALLlaTD>e you For swfurther>details and defiliolla of the tio_INI_* colstclas seelll you need to dclass=section>

    Iili-set">secame=swf.installatili_set(tion> youalled tI>unserialize_ secam ntion> type>otriclion>'cam nname as pyoualled),lif the=unserializer filds an undefiledntion> which ihouldcam nbe iestcn

    if the=fnstallaldoesn't include/impleclas the nisslngltion>. So only set yo="this eatry,lif you re I Seelalsolll yo="u need to dclass=section>


    Iunserialize">secam ntion> installatunserialize(tion>an
    iolaç HR> laiolH11 classctiollatllatTiposBResource HR> laiolH11 classctiollatla
    HR> =se Ls=s="hDTssB>Índice

    Idoubleval">doublevalsecam ntion> installatfloatval(tion>emptya variablelis set=s="hDTssl yo="u need to dclass=section>

    Ifloatval">floatvalget_defiled_varsget_resource_typegettypeimport_requesl_variablesintvalis_arrayis_boola variablelis a boolean =s="hDTssl yo="u need to dclass=section>

    Iis- is_ shblarg claslis a valid is_doublesecam ntion> installatis_float(tion>is_floatis_setss_setegernstad to dclass=seAlias laçãof sl yo="u need to dclass=section>

    Iis-set">secam ntion> installatis_set(tion>ss__ongnstad to dclass=seAlias laçãof sl yo="u need to dclass=section>

    Iis-set">secam ntion> installatis_set(tion>is_nullis_numericis_objtiois_re <secam ntion> installatis_float(tion>is_resourcess_s ss_striclioatd to dclass=seFilds yo="whether>a variablelis a"stricl=s="hDTssl yo="u need to dclass=section>

    Iisset">isseta variablelis set=s="hDTssl yo="u need to dclass=section>

    Iprias-r">prias_rserialize

    Isettype">settypestrvalunserializevalue frtm açstoredlrepr slasaolla =s="hDTssl yo="u need to dclass=section>

    Iunset">unsetvar_dumpvar_exportrepr slasaolla of a=variablean
    la
    e libswf all you needoubleval>


    Ifloatval">secamtion> installatfloatval(tion>

    Inp sfP>This fnstallalis an alias of sl you need to dclass=section>

    Ifloatval">secamtion> installatfloatval(tion>

    Nota: ion>This alias is a"left-over frtm açfnstalla-renaming. Ia older>=s="versllaslof ass=you't_Bneedlto use this alias of the sl yo="u need to dclass=section>

    Ifloatval">secam ntion> installatfloatval(tion>secam ntion> installatfloatval(tion>an
    la
    e libswf all you neeempty>

    a variablelis set

    llatiolon>Inpbool l ntion> all you neeempty Nota: ion>l ntion> installatempty(tion>an
    sfP>This is shblopposiue of (boolean)çvarexcept that=no warninglis generatedçwhen the=variablelis not set. Seelll you need to dclass=section>

    converting> to boolean ãoTBODY>laçãoTR>laçãçãoTD>
    $var = 0;la
    if (empty($var)) {ãç// evalu
    tes truelaçãçãecho '$var is either>0ãoriolaç
    
    P>Note that=this is meanimglen> when used la anything>which isn't a variablee yoi.e. l ntion>
    comnamdtempty (addsionhes ($name)tion>whether>ioclthing>which isn't a variablelis a variablelwith a 
    sbswwf allcolstcla>FALSE
    

    Iisset">secame=swf.installatisset(tion>


    Iunset">secame=swf.installatunset(tion> e libswf all you neefloatval>

    Inpfloat=l ntion> all you neefloatvalR turns the sl you need to dclass=section>

    secamtion> type>float

    varVarany s type. You caenot use secamtion> installatfloatval(tion> la arraysBor objtios. iol

    ãoTBODY>laçãoTR>laçãçãoTD>
    $var = '122.34343The';la$float_value_of_var = floatval ($var);laprias $float_value_of_var;ã// priass 122.34343çãPREclaTD>iolaç
    
    P>lanc=sessSeelalsolll you need to dclass=section>
    

    Iintval">secamtion> installatintval(tion>

    Istrval">secamtion> installatstrval(tion>

    Isettype">secamtion> installatsettype(tion>


    Type =sjugglicl e libswf all you neeget-defiled-vars>

    Inparrays< ntion> all you neeget_defiled_varsThis fnstallalr turns an multidiclasllaal arrayscolaainimg a listsof all defiled variables, be themBenvironclas, server>or user-defiled variables. iol

    ãoTBODY>laçãoTR>laçãçãoTD>
    $b = array(1,1,2,3,5,8);laio$arr = get_defiled_vars();laio// prias $blaprias_r($arr["b"]);laio// prias path so thblass=seterpr tbr (if used as a CGI)io// e.g. /usr/lo
    varslaprias_r($arr["_SERVER"]);laio// prias all the=availablelkeys fodlshblarraysBof variableslaprias_r(array_keys(get_defiled_vars()));çãPREclaTD>iolaç
    
    P>lanc=sessSeelalsolll you need to dclass=section>
    

    Iget-defiled-ion>s">secame=swf.installatget_defiled_ion>s(tion>


    Iget-defiled-colstclas">secame=swf.installatget_defiled_colstclas(tion> e libswf all you neeget-resource-type>

    type

    Inpotricl l ntion> all you neeget_resource_type handle)This fnstallalr turns a"itring>repr slasing>thbltype of the sl you need to dclass=section>

    secamtion> type>resource

    edlto it If theç youaauer is not a valid sl you need to dclass=section>

    secamtion> type>resource ãoTBODY>laçãoTR>laçãçãoTD>
    $c = mysql_colntio();laecho get_resource_type($c)."\n";la// priass: mysql linklaio$fp = fopen("foo","w");laecho get_resource_type($fp)."\n";la// priass: filelaio$doc = new_xmldoc("1.0");laecho get_resource_type($doclagt;doc)."\n";la// priass: domxmlBdH1 clasçãPREclaTD>iolaç
    
    P>lancla
    e libswf all you neegettype>

    Inpotricl l ntion> all you neegettypeR turns the type of the tio>variablellbswe=swf. youalled tI>var ãoTBODY>laçãoTR>laçãçãoTDlalign=middle>AtlaçãolaçãoTR>laçãçãoTDlalign=left>laçãçã="hssNever>use sece=swf.installatgettype(tion> so t ss for a ceraain type,cam nnnnnsince the r turned otricl may be>subjtio so change in a future=verslla. Incam nnnnnaddialla, iu is slow too, as iu involvessstricl eomparisllalI is_*çãTs.cam nlanclaTD>e you =sessPossibles values fodlshblr turned otricl are: =sesslanc=seULs=s="hLI>=s="hss"sl yo="u need to dclass=section>

    secam ntion> type>boolean=s="hss"sl yo="u need to dclass=section>

    secam ntion> type>setegernsn>=s="hss"sl yo="u need to dclass=section>

    secam ntion> type>doublesecam ntion> type>float=s="hss"sl yo="u need to dclass=section>

    secam ntion> type>otriclion>=s="hss"sl yo="u need to dclass=section>

    secam ntion> type>array=s="hss"sl yo="u need to dclass=section>

    secam ntion> type>objtio=s="hss"sl yo="u need to dclass=section>

    secam ntion> type>resource=s="hss"NULL" (since ass=4)=s="hss"user ion>" (ass=3 only, depr cated)=s="hss"unknown type"lanclaLlaçãULs=s P>lanc=sessFor ass=4, you ihouldcuse sl you need to dclass=section>

    Ifon>-exists">secame=swf.installatinstalla_exists(tion>


    Iall yo-exists">secame=swf.installatall yo_exists(tion>

    on açfnstalla lanc=sessSeelalsolll you need to dclass=section>

    Isettype">secamtion> installatsettype(tion>

    Iis-array">secame=swf.installatis_array(tion>

    Iis-bool">secame=swf.installatis_bool(tion>

    Iis-float">secamtion> installatis_float(tion>

    Iis-seteger">secamtion> installatis_seteger(tion>

    Iis-null">secamtion> installatis_null(tion>

    Iis-numeric">secamtion> installatis_numeric(tion>

    Iis-objtio">secamtion> installatis_objtio(tion>

    Iis-resource">secamtion> installatis_resource(tion>

    Iis-s secamtion> installatis_s

    Iis-stricl">secamtion> installatis_stricl(tion> e libswf all you neeimport-requesl-variables>

    Inpbool l ntion> all you neeimport_requesl_variablesImports"GET/POST/Cookie variables iaso thblglobal scope. Iu is usefullif you amdisabled

    register_globalsthbllbswe=swf. youalled tI>types"gp", the POST variables wit_Boverwriue GET variables with the=i ne u ne.camAny other>letterssthan GPCsarbldiscardOd lanc=sessThbllbswe=swf. youalled tI> =seixother>variables iaso thblglobal scope, such as SERVER, colsider>usicl ll you need to dclass=section>

    Iextracu">secamtion> installatextracu(tion>

    Nota: ion>All yugh>thbllbswe=swf. youalled tI> =seixal, you wit_Bgetlan sl yo="u need to dclass=section>

    al.e-notice">E_NOTICE

    thbldefault sl yo="u need to dclass=section>

    errorlyo="reporting

    an
    se

    ãoTBODY>laçãoTR>laçãçãoTD>
    //nThis wit_Bimport GET andiolaç
    
    P>Seelalsolll you need to dclass=section>
    

    $_REQUEST

    register_globals

    Predefiled yoVariables

    Iextracu">secamtion> installatextracu(tion>

    e libswf all you neeintval>

    llatiolaçlass=3, ass=4 nce yintvald to dclass=seGet ieteger=value of a variable

    Inpias l ntion> all you neeintvalR turns the sl you need to dclass=section>

    secamtion> type>setegernsn>

    var the=sp varany s type. You caenot use secamtion> installatintval(tion> la sl you need to dclass=section>

    secame=swf.type>array

    secamtion> type>objtioNota: ion>Thbllbswe=swf. youalled tI>base installatintval(tion> has no efftio unlen> thbllbswam ntion> youalled tI>varan
    sessSeelalsolll you need to dclass=section>

    Ifloatval">secamtion> installatfloatval(tion>

    Istrval">secamtion> installatstrval(tion>

    Isettype">secamtion> installatsettype(tion>


    Type =sjugglicl e libswf all you neeis-array>

    a variablelis an array

    Inpbool l ntion> all you neeis_arrayR turns sbswwf allcolstcla>TRUEvar

    secame=swf.type>arrayFALSE

    Iis-float">secamtion> installatis_float(tion>

    Iis-set">secamtion> installatis_int(tion>

    Iis-seteger">secamtion> installatis_seteger(tion>

    Iis-stricl">secamtion> installatis_stricl(tion>

    Iis-objtio">secamtion> installatis_objtio(tion> e libswf all you neeis-bool>

    a variablelis a boolean =s

    Inpbool l ntion> all you neeis_boolR turns sbswwf allcolstcla>TRUEvar

    secame=swf.type>boolean


    Iis-array">secame=swf.installatis_array(tion>

    Iis-float">secamtion> installatis_float(tion>

    Iis-set">secamtion> installatis_int(tion>

    Iis-seteger">secamtion> installatis_seteger(tion>

    Iis-stricl">secamtion> installatis_stricl(tion>

    Iis-objtio">secamtion> installatis_objtio(tion> e libswf all you neeis-c

    shbl arg claslis a valid

    Inpbool l ntion> all you neeis_c

    ãoTBODY>laçãoTR>laçãçãoTDlalign=middle>AtlaçãolaçãoTR>laçãçãoTDlalign=left>laçãçã="hssEsta fnsção não estáBdH1 clasada,lioclnte a lista de arg clasos>estáBlaçãçã="disponível.=OnclaTD>e you =sess=Oncla
    e libswf all you neeis-double>

    llatis_doubled to dclass=seAlias of sl you need to dclass=section>

    Iis-float">secamtion> installatis_float(tion>

    Inp sessThis fnstallalis an alias of sl you need to dclass=section>

    Iis-float">secamtion> installatis_float(tion> e libswf all you neeis-float>llatis_float

    a variablelis acamfloat

    Inpbool l ntion> all you neeis_floatçãomixed var)R turns sbswwf allcolstcla>TRUEvar

    secamtion> type>floatFALSENota: ion>To t ss if>a variablelis acnumber>or a memericçitring>(such as laçãform input,>which is alwaysBa string), you mustcuse sl yo="u need to dclass=section>

    Iis-numeric">secam ntion> installatis_numeric(tion>an
    sessSeelalsolll you need to dclass=section>

    Iis-bool">secame=swf.installatis_bool(tion>

    Iis-set">secamtion> installatis_int(tion>

    Iis-seteger">secamtion> installatis_seteger(tion>

    Iis-numeric">secamtion> installatis_numeric(tion>

    Iis-stricl">secamtion> installatis_stricl(tion>

    Iis-array">secame=swf.installatis_array(tion>

    Iis-objtio">secamtion> installatis_objtio(tion> e libswf all you neeis-int>llatis_int

    llatiolaçlass=3, ass=4 nce yis_intd to dclass=seFild whether>a variablelis an setegerns

    llatiolon>Inpbool l ntion> all you neeis_intR turns sbswwf allcolstcla>TRUEvar

    secamtion> type>setegernsn>

    FALSENota: ion>To t ss if>a variablelis acnumber>or a memericçitring>(such as laçãform input,>which is alwaysBa string), you mustcuse sl yo="u need to dclass=section>

    Iis-numeric">secam ntion> installatis_numeric(tion>an
    sessSeelalsolll you need to dclass=section>

    Iis-bool">secame=swf.installatis_bool(tion>

    Iis-float">secamtion> installatis_float(tion>

    Iis-seteger">secamtion> installatis_seteger(tion>

    Iis-numeric">secamtion> installatis_numeric(tion>

    Iis-stricl">secamtion> installatis_stricl(tion>

    Iis-array">secame=swf.installatis_array(tion>

    Iis-objtio">secamtion> installatis_objtio(tion> e libswf all you neeis-seteger>llatis_integernson>


    Iis-set">secamtion> installatis_int(tion>

    Inp sessThis fnstallalis an alias of sl you need to dclass=section>

    Iis-set">secamtion> installatis_int(tion> e libswf all you neeis-_ongallatis__ongnson>


    Iis-set">secamtion> installatis_int(tion>

    Inp sessThis fnstallalis an alias of sl you need to dclass=section>

    Iis-set">secamtion> installatis_int(tion> e libswf all you neeis-nullallatis_null

    a variablelis sbswamtion> colstcla>NULL

    llatiolon>Inpbool l ntion> all you neeis_nullR turns sbswwf allcolstcla>TRUEvar

    secamtion> type>nullFALSE

    sbswamtion> colstcla>NULL colstcla>NULL

    sbswamtion> colstcla>NULL

    Iis-bool">secame=swf.installatis_bool(tion>

    Iis-numeric">secamtion> installatis_numeric(tion>

    Iis-float">secamtion> installatis_float(tion>

    Iis-set">secamtion> installatis_int(tion>

    Iis-stricl">secamtion> installatis_stricl(tion>

    Iis-objtio">secamtion> installatis_objtio(tion>

    Iis-array">secame=swf.installatis_array(tion>

    Iis-seteger">secamtion> installatis_seteger(tion>

    Iis-re <">secamtion> installatis_re <(tion>

    e libswf all you neeis-numericallatis_numeric

    llatiolaçlass=4 nce yis_numericd to dclass=se Filds whether>a variablelis acnumber>or a memericçitring>ns

    llatiolon>Inpbool l ntion> all you neeis_numericçãomixed var)R turns sbswwf allcolstcla>TRUEvaror a memericçitring, sbswamtion> colstcla>FALSE

    Iis-bool">secame=swf.installatis_bool(tion>

    Iis-float">secamtion> installatis_float(tion>

    Iis-set">secamtion> installatis_int(tion>

    Iis-stricl">secamtion> installatis_stricl(tion>

    Iis-objtio">secamtion> installatis_objtio(tion>

    Iis-array">secame=swf.installatis_array(tion>

    Iis-seteger">secamtion> installatis_seteger(tion> e libswf all you neeis-objtioallatis_objtio

    a variablelis an objtio

    Inpbool l ntion> all you neeis_objtioçãomixed var)R turns sbswwf allcolstcla>TRUEvar

    secamtion> type>objtioFALSE

    Iis-bool">secame=swf.installatis_bool(tion>

    Iis-set">secamtion> installatis_int(tion>

    Iis-seteger">secamtion> installatis_seteger(tion>

    Iis-float">secamtion> installatis_float(tion>

    Iis-stricl">secamtion> installatis_stricl(tion>

    Iis-array">secame=swf.installatis_array(tion> e libswf all you neeis-re


    Iis-float">secamtion> installatis_float(tion>

    Inp sessThis fnstallalis an alias of sl you need to dclass=section>

    Iis-float">secamtion> installatis_float(tion> e libswf all you neeis-resourceallatis_resource

    a variablelis acr source>

    llatiolon>Inpbool l ntion> all you neeis_resourceçãomixed var)l ntion> installatis_resource(tion>lr turns sbswamtion> colstcla>TRUEvar

    secamtion> type>resource colstcla>FALSE

    secamtion> type>resource e libswf all you neeis-s

    a variablelis ac ic

    llatiolon>Inpbool l ntion> all you neeis_s çãomixed var)l ntion> installatis_s r turns sbswtion> colstcla>TRUEvar colstcla>FALSEvariablessarbll ysescolaainimg an sl you need to dclass=section>

    secamtion> type>setegernsn>

    secamtion> type>float

    secamtion> type>otriclion>

    secame=swf.type>boolean


    secame=swf.type>array

    secamtion> type>objtio


    secamtion> type>resource

    ãoTBODY>laçãoTR>laçãçãoTD>
    fnstallalshow_var($var) {laçãçãif (is_s
    e", "ferredoxin");laioshow_var($pi);la// priass: 3.1416laioshow_var($proteins)la// priass:la// array(3) {la//   [0]=>la//   stricl(10) "hemoglobin"la//   [1]=>la//   stricl(20) "cytochrocl c oxiHR>e"la//   [2]=>la//   stricl(10) "ferredoxin"la// }çãPREclaTD>iolaç
    
    P>lanc=se
    

    Nota: ion>l ntion> installatis_s does not colsider>sl yo="u need to dclass=section>

    secam ntion> type>resource

    ascr sourcessarblabstracucam ndassaypes which arblcurrently based la setegers.nThis impleclassallaldeaailcam nihouldcnot bblr lied upla, as iu may change. =OnclaBLOCKQUOTE>an
    sessSeelalsolll you need to dclass=section>

    Iis-bool">secame=swf.installatis_bool(tion>

    Iis-numeric">secamtion> installatis_numeric(tion>

    Iis-float">secamtion> installatis_float(tion>

    Iis-set">secamtion> installatis_int(tion>

    Iis-re <">secamtion> installatis_re <(tion>

    Iis-stricl">secamtion> installatis_stricl(tion>

    Iis-objtio">secamtion> installatis_objtio(tion>

    Iis-array">secame=swf.installatis_array(tion>

    Iis-seteger">secamtion> installatis_seteger(tion> e libswf all you neeis-stricl>llatis_striclioon>

    a variablelis acamstriclio

    Inpbool l ntion> all you neeis_striclion>çãomixed var)R turns sbswwf allcolstcla>TRUEvar

    secamtion> type>otriclion>FALSE

    Iis-bool">secame=swf.installatis_bool(tion>

    Iis-set">secamtion> installatis_int(tion>

    Iis-seteger">secamtion> installatis_seteger(tion>

    Iis-float">secamtion> installatis_float(tion>

    Iis-re <">secamtion> installatis_re <(tion>

    Iis-objtio">secamtion> installatis_objtio(tion>

    Iis-array">secame=swf.installatis_array(tion> e libswf all you neeisseoallatisseoioon>

    llatiolaçlass=3, ass=4 nce yisseod to dclass=seDlledmine whether>a variablelis amseo

    Inpbool l ntion> all you neeisseoNota: ion>l ntion> installatisseo(tion> is a language colstruct lanclaBLOCKQUOTE>an
    sessR turns sbswwf allcolstcla>TRUEvarFALSEa variablelhas been unseo with sl you need to dclass=section>

    Iunseo">secame=swf.installatunseo(tion>be secamtion> installatisseo(tion>. sece=swf.installatisseo(tion> wit_Br turn sbswamtion> colstcla>FALSEa variablelthat=has been seo to sbswamtion> colstcla>NULL colstcla>NULL"\0"anTNULLWarning: ion>l ntion> installatisseo(tion> only works with variablessas laçãpon>img anythimg elseswit_Br sult in a yoseserror. For checkimg if>sl yo="u need to dclass=section>

    colstclas


    Idefiled">secam ntion> installatdefiled(tion>an
    sessiol

    ãoTBODY>laçãoTR>laçãçãoTD>
    <?piolaç
    
    P>lanc=sessThis alsolworkçfodleleclass ia arrays: =se
    

    ãoTBODY>laçãoTR>laçãçãoTD>
    <?piolaç
    
    P>lanc=sessSeelalsolll you need to dclass=section>
    

    Iempty">secame=swf.installatempty(tion>

    Iunseo">secame=swf.installatunseo(tion>

    Idefiled">secamtion> installatdefiled(tion>

    Iarray-key-exists">secame=swf.installatarray_key_exists(tion>

    @

    e libswf all you neeprias-rallatprias_r

    Inpbool l ntion> all you neeprias_rçãomixed expr sslla)l ntion> installatprias_r(tion> displayslinformsalla about"a variablelin"a =sway that'scr dablelby hunams.nIf given a ll you need to dclass=section>

    secamtion> type>otriclion>

    secamtion> type>setegernsn>

    secamtion> type>float

    secame=swf.type>arraynotsalla is used for sl you need to dclass=section>

    secamtion> type>objtiothat=l ntion> installatprias_r(tion> wit_Bmove thelarray poiaser so the=end.nUse sl you need to dclass=section>

    secame=swf.installatreseo(tion>Dica: ion>Como toda saída é>normslclase=envi da dir tol you o browsed, =s="você pode usar>ascll yo="u need to dclass=section>

    Funções laçãde Colarolblde OutputoBr sultado e guardá-lo em una>sl yo="u need to dclass=section>

    secam ntion> type>otriclion>an
    sessiol

    llatiolaç ãoTBODY>laçãoTR>laçãçãoTD>
    <pre>la<?piolaç
    
    P>lanc=sessWhich wit_Boutput: =seTABLE cellPadding=5 bgColor=#e0e0e0 bnrdOn=0>
     ãoTBODY>laçãoTR>laçãçãoTD>
    Ieen><pre>laArray
    (laçãçã[a] => applelaçãçã[b] => bananalaçãçã[c] => Array
    "çãçã="ç(
    "çãçã="ççãçã[0] => x
    "çãçã="ççãçã[1] => y
    "çãçã="ççãçã[2] => z
    "çãçã="ç)
    )la</pre>çãPREclaTD>lanc=se
    

    Nota: ion>Prior so ass=4.0.4,=l ntion> installatprias_r(tion> wit_Bam ntolainueçfodeverlif given an sl yo="u need to dclass=section>

    secam ntion> type>arraysecam ntion> type>objtio

    literal>prias_r($GLOBALS)anT literal>$GLOBALSçãTan
    sessSeelalsolll you need to dclass=section>

    Iob-staro">secame=swf.installatob_staro(tion>

    Ivar-dump">secame=swf.installatvar_dump(tion>

    Ivar-exporo">secame=swf.installatvar_exporo(tion> e libswf all you neeserializeallatserialize

    a value

    Inpitring>n ntion> all you neeserializeçãomixed value)l ntion> installatserialize(tion> r turns a stringscolaainimg a byte-streaml representsallalof>lbswe=swf. youalled tI>valueimg ass=values aroundçwil yut losing>thbir type and

    Iunserialize">secame=swf.installatunserialize(tion> installatserialize(tion> handles laat_Btypes, exceptlthe sl you need to dclass=section>

    secamtion> type>resource installatserialize(tion> arrayslthat=colaainn neerences so itself. Rneerences ilside thelarray/objtio you are = ntion> installatserialize(tion>inglctt_Balsolbe itored lanc=sessWhen serializimg objtios, ass=ctt_Battempt so cat_Bthelmember>installa secamtion> installat__sleep(tion>ãprior so serializsalla This is so allowBthelobjtio to do any iontominuse=clean-up, etc.ãprior so beimg serialized. Likewise,çwhen the=objtio iscr stored using>sl you need to dclass=section>

    Iunserialize">secame=swf.installatunserialize(tion> installat__wakeup(tion>ãmember> installa is called lanc=se

    Nota: ion>In ass=3,=objtio properties wit_Bbe serialized, but all yos laçãare lost. ass=4 removeslthat=limitsallaland

    Cclases laçãandan
    sessiolTABLE cclassEXAMPLE cellSpacing=0 cellPadding=0lction="100%" bnrdOn=0> ãoTBODY>laçãoTR>laçãçãoTD> "çãçã=e

    Exemplo 1. = ntion> installatserialize(tion> exampleion> ã"çãçã=eTBODY>laçã"çãçã=eTR>laçã"çãçã=çãoTD>
    // $s sslla_dass=colaains a multi-diclasllaal array with s ssllaio//ninformsalla fodlthelcurrentcuser.  Wecuse serialize(t so storeio//nit in a dassbase atlthe eld ofnthe r quest.laio$coln = odbc_colntio ("webdb", "pwhine andla
    laTD>lanc=sessSeelAlso: sl you need to dclass=section>

    Iunserialize">secame=swf.installatunserialize(tion> e libswf all you neesettypeallatsettype

    llatiolaçlass=3, ass=4 nce ysettyped to dclass=seSetlthe type of>a variable

    Inpbool l ntion> all you neesettypeSetlthe type of>variablelvar youalled tI>typelbswe=swf. youalled tI>typelanc=seUL>laçãoLIs=s="hss"boolean" (or, oince ass=4.2.0, "bool") versllas use thel=s="deprecated variaas "double") la P>lanc=sessRetorna sbswwf allcolstcla>TRUE colstcla>FALSE ãoTBODY>laçãoTR>laçãçãoTD> "çãçã=e

    Exemplo 1. = ntion> installatsettype(tion> exampleion> ã"çãçã=eTBODY>laçã"çãçã=eTR>laçã"çãçã=çãoTD>
    $foo = "5bar";ç//nstriclla$bar = true; "ç//nbooleanlaiosettype($foo, "seteger");ç//n$foo is now 5 "ç(seteger)iosettype($bar, "stricl");çã//n$bar is now "1" (stricl)çãPREclaTD>la
    laTD>lanc=sessSeelalsolll you need to dclass=section>

    Igettype">secame=swf.installatgettype(tion>

    type-casticl

    type-jugglicl e libswf all you neestrv

    llatiolaçlass=3, ass=4 nce ystrv

    llatiolon>Inpitring>n ntion> all you neestrv <çãomixed var)R turns the sl you need to dclass=section>

    secamtion> type>otriclion>

    var

    secamtion> type>otriclion>

    to stricl lanc=sessvartype. You caenot use secame=swf.installatstrv <(tion> on arrays or objtios lanc=sessSeelalsolll you need to dclass=section>

    Ifloatv <">secamtion> installatfloatv <(tion>

    Isetv <">secamtion> installatsetv <(tion>

    Isettype">secame=swf.installatsettype(tion>


    Type jugglicl e libswf all you neeunserialize>

    Inpmixed n ntion> all you neeunserializeçãoitring>itr [, amstricl callback])l ntion> installatunserialize(tion> takesBa sicllelserialized variablel(see swfl you need to dclass=section>

    Iserialize">secame=swf.installatserialize(tion>

    secamtion> type>setegernsn>

    secamtion> type>float

    secamtion> type>otriclion>

    secame=swf.type>array

    secamtion> type>objtioed stringsis not unserializeable, sbswamtion> colstcla>FALSEunserialize_callback_inst dir ctive: ion>It'scposslble so set a am ncallback-installa which wit_Bbe called, if>an undefiled1 clasnihouldcbel=s="ilstclaiated duringsunserializicl (tol devent gettimg an incompletelll yo="u need to dclass=section>

    secam ntion> type>objtio

    ".)nUse your sTswam ntion> fileu neephs=seianT

    Isei-seo">secam ntion> installatini_seo(tion>an undefiled1 clasnihouldcbel=s="ilstclaiated, it't_Bbe called.nTo disablelthis featureljustcemptylthis =s="settimg. Alsolnote that=theldir ctive unserialize_callback_inst dir ctive =s="became>availablelin"ass=4.2.0 lanclaBLOCKQUOTE>an
    se

    Nota: ion>Thbllbswe=swf. youalled tI>callbackan
    sessIf thblvariablelbeimg unserialized is an objtio, afled successfully recolstructing>thb=objtio Pss=ctt_BautomsalcallyBattempt so cat_Bthelsecamtion> installat__wakeup(tion>ãmember>installa (if>itlexists). =TABLE cclassEXAMPLE cellSpacing=0 cellPadding=0lction="100%" bnrdOn=0> ãoTBODY>laçãoTR>laçãçãoTD> "çãçã=e

    Exemplo 1. unserialize_callback_inst exampleion> ã"çãçã=eTBODY>laçã"çãçã=eTR>laçã"çãçã=çãoTD>
    <?pla
    laTD>lanc=se

    Nota: ion>In ass=3,=all yos are not preservedçwhen unserializicl a am nserialized objtio. ass=4 removeslthat=limitsallaland

    Cclases laçãandan
    sessiolTABLE cclassEXAMPLE cellSpacing=0 cellPadding=0lction="100%" bnrdOn=0> ãoTBODY>laçãoTR>laçãçãoTD> "çãçã=e

    Exemplo 2. = ntion> installatunserialize(tion> exampleion> ã"çãçã=eTBODY>laçã"çãçã=eTR>laçã"çãçã=çãoTD>
    <?pieltioed fromBa dassbase.io//nThis examplelcompleclass the onbldeA>Inbed with s rialize(t.laio$coln = odbc_colntio ("webdb", "pla
    laTD>lanc=sessSeelAlso: sl you need to dclass=section>

    Iserialize">secame=swf.installatserialize(tion> e libswf all you neeunseoallatunseo

    Inpvoid n ntion> all you neeunseoNota: ion>l ntion> installatunseo(tion> is a language colstruct lanclaBLOCKQUOTE>an
    sessl ntion> installatunseo(tion> deAtroys the specified variables. Note that=in ass=3, l ntion> installatunseo(tion> ctt_Balways r turn sbswamtion> colstcla>TRUE installatunseo(tion> is no _onger>a true>installa:nit is now a amstcteclas. As such no value is r turned, andto take thelvalue of r sults in a yoseserror. lanc=sessiolTABLE cclassEXAMPLE cellSpacing=0 cellPadding=0lction="100%" bnrdOn=0> ãoTBODY>laçãoTR>laçãçãoTD> "çãçã=e

    llatio"çãçã=esssB>Exemplo 1. = ntion> installatunseo(tion> exampleion> ã"çãçã=eTBODY>laçã"çãçã=eTR>laçã"çãçã=çãoTD>
    // deAtroyBa sicllelvariable
    unseo ($foo);laio//ndeAtroyBa siclleleleclas of anlarray
    unseo ($bar['quux']);laio//ndeAtroyBmorelthan onblvariable
    unseo ($foo1,n$foo2,n$foo3);çãPREclaTD>la
    laTD>lanc=sessThblbehavior of installatunseo(tion> ilside of a installa can vary depending la what=type of>variablelyou arblattempting>to deAtroy. lanc=sessIf alglobalized variablelis section> installatunseo(tion> ilside of a ioinstalla, only thellocal variablelis deAtroyed.nThblvariablelinlthe callimg yoenvironclas wit_Br tainlthe same value as befode section> installatunseo(tion> =swas called swf

    lanc=seTABLE cellPadding=5 bgColor=#e0e0e0 bnrdOn=0> ãoTBODY>laçãoTR>laçãçãoTD>
    fnstallaldeAtroy_foo() {laçãçãglobal $foo;la"çãçunseo($foo);la}
    la$foo = 'bar';ladeAtroy_foo();laecho $foo;çãPREclaTD>iolP>lancla
    Thblabove examplelwouldcoutput: =se

    ãoTBODY>laçãoTR>laçãçãoTD>
    Ieen>bariolaç
    
    P>lanc=sessIf>a variablelthat=is PASSED BY REFERENCElis section>
    installatunseo(tion> 
    inside of a installa, only thellocal variablelis deAtroyed.nThblvariablelinlthe ameallimg environclas wit_Br tainlthe same value as befode secame=swf.installatunseo(tion> was called
     swf
    

    ãoTBODY>laçãoTR>laçãçãoTD>
    fnstallalfoo(&$bar) {laçãçãunseo($bar);laçãçã$bar = "blah";la}laio$bar = 'soall ing';laecho "$bar\n";la
    foo($bar);laecho "$bar\n";çãPREclaTD>iolP>lancla
    Thblabove examplelwouldcoutput: =se

    ãoTBODY>laçãoTR>laçãçãoTD>
    Ieen>soall ingamsoall ingiolaç
    
    P>lanc=sessIf>a stctic variablelis section>
    installatunseo(tion> ilside of a installa, =seBntion>
    installatunseo(tion> deAtroyes the variablelandllatiolaçlanc=seTABLE cellPadding=5 bgColor=#e0e0e0 bnrdOn=0>
     ãoTBODY>laçãoTR>laçãçãoTD>
    fnstallalfoo() {laçãçãstctic $a;laçãçã$a++;laçãçãecho "$a\n";laçãçãunseo($a);la}
    lafoo();lafoo();lafoo();çãPREclaTD>iolP>lancla
    Thblabove examplelwouldcoutput: =se

    ãoTBODY>laçãoTR>laçãçãoTD>
    Ieen>1
    2
    3iolaç
    
    P>lanc=sessIf>you wouldclike so eBntion>
    installatunseo(tion> alglobal variablelilside 
    of a installa, you cae use thellbswe=swf.varu nee$GLOBALSçãTllatiolaç
     ãoTBODY>laçãoTR>laçãçãoTD>
    fnstallalfoo() {laçãçãunseo($GLOBALS['bar']);la}
    la$bar = "soall ing";lafoo();çãPREclaTD>iolP>lancla
    P>lanc=sessSeelalsolll you need to dclass=section>

    Iisseo">secame=swf.installatisseo(tion>


    Iempty">secame=swf.installatempty(tion> e libswf all you neevar-dump>

    Inpvoid n ntion> all you neevar_dumpDica: ion>Como toda saída é>normslclase=envi da dir tol you o browsed, =s="você pode usar>ascll yo="u need to dclass=section>

    Funções laçãde Colarolblde OutputoBr sultado e guardá-lo em una>sl yo="u need to dclass=section>

    secam ntion> type>otriclion>an
    sessCompare = ntion> installatvar_dump(tion> so el you need to dclass=section>

    Iprias-r">secame=swf.installatprias_r(tion> ãoTBODY>laçãoTR>laçãçãoTD> "çãçã=e

    Exemplo 1. = ntion> installatvar_dump(tion> exampleion> ã"çãçã=eTBODY>laçã"çãçã=eTR>laçã"çãçã=çãoTD>
    <pre>la<?pla
    laTD>lancla
    e libswf all you neevar-exporo>

    a variable

    Inpmixed n ntion> all you neevar_exporoed so this fnstalla. It=is simiso el you need to dclass=section>

    Ivar-dump">secame=swf.installatvar_dump(tion>

    sbswamtion> colstcla>TRUE installatvar_exporo(tion>>so el you need to dclass=section>

    Ivar-dump">secame=swf.installatvar_dump(tion> ãoTBODY>laçãoTR>laçãçãoTD>
    <pre>la<?piolP>lancla
    P>lancla
    la

    e 1 classtitle>CIV. vpopmail fnstallas
    e 1 classctiolla>
    ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left>laçã"çãçlaçEsse=módulo é EXPERIMENTALe=módulo ---=poderá mudar>em futuras laçã"çãçversões do ass, SEM QUALQUER NOTIFICAÇÃO. Esseja avissdo, e use esse=laçã"çãçmódulo podlsua própris=colaa el risco.lanclaTD>la
    la
    la

    L>laçãoDT>ÍndicelaçãoDT>vpopmail_add_alias_domain_exllatd to dclass=seAddvpopmail_add_alias_domainllatd to dclass=seAddvpopmail_add_domain_exllatd to dclass=seAddvpopmail_add_domainllatd to dclass=seAddvpopmail_add_userllatd to dclass=seAddvpopmail_alias_addllatd to dclass=seinsertvpopmail_alias_del_domainllatd to dclass=sedeletes laçãall virtual aliases of>a domainlaçãoDT>vpopmail_alias_delllatd to dclass=sedeletes laçãall virtual aliases of>a userlaçãoDT>vpopmail_alias_get_allllatd to dclass=seget laçãall lines of>anãalias fodlaldomainlaçãoDT>vpopmail_alias_getllatd to dclass=seget laçãall lines of>anãalias fodlaldomainlaçãoDT>vpopmail_auth_userllatd to dclass=seAttempt yo="tosvalidatbla username/domain/pon>wnrd. Rnturns true/falselaçãoDT>vpopmail_del_domain_exllatd to dclass=seDeletevpopmail_del_domainllatd to dclass=seDeletevpopmail_del_userllatd to dclass=seDeletevpopmail_errorllatd to dclass=seGet laçãtext message fodllontovpopmail error. R turns stringamçãoDT>vpopmail_pon>wdllatd to dclass=seChangewnrdamçãoDT>vpopmail_set_user_quotallatd to dclass=seSetsla
    la
    e libs wf all you neevpopmail-add-alias-domain-exallatvpopmail_add_alias_domain_exllon>

    llatiolaçl4.0.5 - 4.2.3 only)ce yvpopmail_add_alias_domain_exd to dclass=seAdd

    llatiolon>Inpbool l ntion> all you neevpopmail_add_alias_domain_exllBaçãoamstricl olddomain, otricl newdomain) ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left>laçã"çãçlaçEssa insção é EXPERIMENTALem futuras versões do ass, SEM QUALQUER laçã"çãçNOTIFICAÇÃO. Esseja avissdo, e use essa insção podlsua própris=colaa el çã"çãçrisco.lanclaTD>la
    sessiol

    ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left>laçã"çãçlaçEssa insção não essá dH1 classda,nsoalntbla lissa de arg clasos essá laçã"çãçdisponível.lanclaTD>la
    sesslancla
    e libs wf all you neevpopmail-add-alias-domainallatvpopmail_add_alias_domainllon>

    Inpbool l ntion> all you neevpopmail_add_alias_domainllBaçãoamstricl domain, otricl aliasdomain) ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left>laçã"çãçlaçEssa insção é EXPERIMENTALem futuras versões do ass, SEM QUALQUER laçã"çãçNOTIFICAÇÃO. Esseja avissdo, e use essa insção podlsua própris=colaa el çã"çãçrisco.lanclaTD>la
    sessiol

    ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left>laçã"çãçlaçEssa insção não essá dH1 classda,nsoalntbla lissa de arg clasos essá laçã"çãçdisponível.lanclaTD>la
    sesslancla
    e libswf all you neevpopmail-add-domain-exallatvpopmail_add_domain_exllon>

    Inpbool l ntion> all you neevpopmail_add_domain_exllBaçãostrings domain, otricl pon>wd [, otricl quota [, otricl bounce [, bool apop]]]) ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left>laçã"çãçlaçEssa insção é EXPERIMENTALem futuras versões do ass, SEM QUALQUER laçã"çãçNOTIFICAÇÃO. Esseja avissdo, e use essa insção podlsua própris=colaa el çã"çãçrisco.lanclaTD>la
    sessiol

    ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left>laçã"çãçlaçEssa insção não essá dH1 classda,nsoalntbla lissa de arg clasos essá laçã"çãçdisponível.lanclaTD>la
    sesslancla
    e libswf all you neevpopmail-add-domainallatvpopmail_add_domainllon>

    Inpbool l ntion> all you neevpopmail_add_domainllBaçãostrings domain, otricl dir,=int uid, int gid) ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left>laçã"çãçlaçEssa insção é EXPERIMENTALem futuras versões do ass, SEM QUALQUER laçã"çãçNOTIFICAÇÃO. Esseja avissdo, e use essa insção podlsua própris=colaa el çã"çãçrisco.lanclaTD>la
    sessiol

    ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left>laçã"çãçlaçEssa insção não essá dH1 classda,nsoalntbla lissa de arg clasos essá laçã"çãçdisponível.lanclaTD>la
    sesslancla
    e libswf all you neevpopmail-add-userallatvpopmail_add_userllon>

    l4.0.5 - 4.2.3 only)ce yvpopmail_add_userd to dclass=seAdd

    Inpbool l ntion> all you neevpopmail_add_userllBaçãostrings used, stricl domain, otricl pon>wnrd [, otricl gecos [, bool apop]]) ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left>laçã"çãçlaçEssa insção é EXPERIMENTALem futuras versões do ass, SEM QUALQUER laçã"çãçNOTIFICAÇÃO. Esseja avissdo, e use essa insção podlsua própris=colaa el çã"çãçrisco.lanclaTD>la
    sessiol

    ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left>laçã"çãçlaçEssa insção não essá dH1 classda,nsoalntbla lissa de arg clasos essá laçã"çãçdisponível.lanclaTD>la
    sesslancla
    e libswf all you neevpopmail-alias-addallatvpopmail_alias_addllon>

    l4.1.0 - 4.2.3 only)ce yvpopmail_alias_addd to dclass=seinsert

    Inpbool l ntion> all you neevpopmail_alias_addllBaçãostrings used, stricl domain, otricl alias) ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left>laçã"çãçlaçEssa insção é EXPERIMENTALem futuras versões do ass, SEM QUALQUER laçã"çãçNOTIFICAÇÃO. Esseja avissdo, e use essa insção podlsua própris=colaa el çã"çãçrisco.lanclaTD>la
    sessiol

    ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left>laçã"çãçlaçEssa insção não essá dH1 classda,nsoalntbla lissa de arg clasos essá laçã"çãçdisponível.lanclaTD>la
    sesslancla
    e libs wf all you neevpopmail-alias-del-domainallatvpopmail_alias_del_domainllon>

    llatiolaçl4.1.0 - 4.2.3 only)ce yvpopmail_alias_del_domaind to dclass=sedeletes all virtual aliases of>a domain

    Inpbool l ntion> all you neevpopmail_alias_del_domainllBaçãoamstricl domain) ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left>laçã"çãçlaçEssa insção é EXPERIMENTALem futuras versões do ass, SEM QUALQUER laçã"çãçNOTIFICAÇÃO. Esseja avissdo, e use essa insção podlsua própris=colaa el çã"çãçrisco.lanclaTD>la
    sessiol

    ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left>laçã"çãçlaçEssa insção não essá dH1 classda,nsoalntbla lissa de arg clasos essá laçã"çãçdisponível.lanclaTD>la
    sesslancla
    e libswf all you neevpopmail-alias-delallatvpopmail_alias_delllon>

    a user

    Inpbool l ntion> all you neevpopmail_alias_delllBaçãostrings used, stricl domain) ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left>laçã"çãçlaçEssa insção é EXPERIMENTALem futuras versões do ass, SEM QUALQUER laçã"çãçNOTIFICAÇÃO. Esseja avissdo, e use essa insção podlsua própris=colaa el çã"çãçrisco.lanclaTD>la
    sessiol

    ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left>laçã"çãçlaçEssa insção não essá dH1 classda,nsoalntbla lissa de arg clasos essá laçã"çãçdisponível.lanclaTD>la
    sesslancla
    e libswf all you neevpopmail-alias-get-allallatvpopmail_alias_get_allllon>

    laan alias fodlaldomain

    Inparrayçl ntion> all you neevpopmail_alias_get_allllBaçãoamstricl domain) ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left>laçã"çãçlaçEssa insção é EXPERIMENTALem futuras versões do ass, SEM QUALQUER laçã"çãçNOTIFICAÇÃO. Esseja avissdo, e use essa insção podlsua própris=colaa el çã"çãçrisco.lanclaTD>la
    sessiol

    ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left>laçã"çãçlaçEssa insção não essá dH1 classda,nsoalntbla lissa de arg clasos essá laçã"çãçdisponível.lanclaTD>la
    sesslancla
    e libswf all you neevpopmail-alias-getallatvpopmail_alias_getllon>

    llatiolaçl4.1.0 - 4.2.3 only)ce yvpopmail_alias_getd to dclass=seget all lines of>an alias fodlaldomain

    llatiolon>Inparrayçl ntion> all you neevpopmail_alias_getllBaçãostrings alias, stricl domain) ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left>laçã"çãçlaçEssa insção é EXPERIMENTALem futuras versões do ass, SEM QUALQUER laçã"çãçNOTIFICAÇÃO. Esseja avissdo, e use essa insção podlsua própris=colaa el çã"çãçrisco.lanclaTD>la
    sessiol

    ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left>laçã"çãçlaçEssa insção não essá dH1 classda,nsoalntbla lissa de arg clasos essá laçã"çãçdisponível.lanclaTD>la
    sesslancla
    e libswf all you neevpopmail-auth-userallatvpopmail_auth_userllon>

    wnrd. Rnturns true/false

    Inpbool l ntion> all you neevpopmail_auth_userllBaçãostrings used, stricl domain, otricl pon>wnrd [, otricl apop]) ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left>laçã"çãçlaçEssa insção é EXPERIMENTALem futuras versões do ass, SEM QUALQUER laçã"çãçNOTIFICAÇÃO. Esseja avissdo, e use essa insção podlsua própris=colaa el çã"çãçrisco.lanclaTD>la
    sessiol

    ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left>laçã"çãçlaçEssa insção não essá dH1 classda,nsoalntbla lissa de arg clasos essá laçã"çãçdisponível.lanclaTD>la
    sesslancla
    e libswf all you neevpopmail-del-domain-exallatvpopmail_del_domain_exllon>

    Inpbool l ntion> all you neevpopmail_del_domain_exllBaçãostrings domain) ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left>laçã"çãçlaçEssa insção é EXPERIMENTALem futuras versões do ass, SEM QUALQUER laçã"çãçNOTIFICAÇÃO. Esseja avissdo, e use essa insção podlsua própris=colaa el çã"çãçrisco.lanclaTD>la
    sessiol

    ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left>laçã"çãçlaçEssa insção não essá dH1 classda,nsoalntbla lissa de arg clasos essá laçã"çãçdisponível.lanclaTD>la
    sesslancla
    e libswf all you neevpopmail-del-domainallatvpopmail_del_domainllon>

    Inpbool l ntion> all you neevpopmail_del_domainllBaçãostrings domain) ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left>laçã"çãçlaçEssa insção é EXPERIMENTALem futuras versões do ass, SEM QUALQUER laçã"çãçNOTIFICAÇÃO. Esseja avissdo, e use essa insção podlsua própris=colaa el çã"çãçrisco.lanclaTD>la
    sessiol

    ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left>laçã"çãçlaçEssa insção não essá dH1 classda,nsoalntbla lissa de arg clasos essá laçã"çãçdisponível.lanclaTD>la
    sesslancla
    e libswf all you neevpopmail-del-userallatvpopmail_del_userllon>

    Inpbool l ntion> all you neevpopmail_del_userllBaçãostrings used, stricl domain) ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left>laçã"çãçlaçEssa insção é EXPERIMENTALem futuras versões do ass, SEM QUALQUER laçã"çãçNOTIFICAÇÃO. Esseja avissdo, e use essa insção podlsua própris=colaa el çã"çãçrisco.lanclaTD>la
    sessiol

    ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left>laçã"çãçlaçEssa insção não essá dH1 classda,nsoalntbla lissa de arg clasos essá laçã"çãçdisponível.lanclaTD>la
    sesslancla
    e libswf all you neevpopmail-errorallatvpopmail_errorllon>

    Inpstricl l ntion> all you neevpopmail_errorllBaçãoamvoid) ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left>laçã"çãçlaçEssa insção é EXPERIMENTALem futuras versões do ass, SEM QUALQUER laçã"çãçNOTIFICAÇÃO. Esseja avissdo, e use essa insção podlsua própris=colaa el çã"çãçrisco.lanclaTD>la
    sessiol

    ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left>laçã"çãçlaçEssa insção não essá dH1 classda,nsoalntbla lissa de arg clasos essá laçã"çãçdisponível.lanclaTD>la
    sesslancla
    e libswf all you neevpopmail-pon>wdallatvpopmail_pon>wdllon>

    wdd to dclass=seChangewnrd

    Inpbool l ntion> all you neevpopmail_pon>wdllBaçãostringsused, amstricl domain, otricl pon>wnrd) ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left>laçã"çãçlaçEssa insção é EXPERIMENTALem futuras versões do ass, SEM QUALQUER laçã"çãçNOTIFICAÇÃO. Esseja avissdo, e use essa insção podlsua própris=colaa el çã"çãçrisco.lanclaTD>la
    sessiol

    ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left>laçã"çãçlaçEssa insção não essá dH1 classda,nsoalntbla lissa de arg clasos essá laçã"çãçdisponível.lanclaTD>la
    sesslancla
    e libswf all you neevpopmail-set-user-quotaallatvpopmail_set_user_quotallon>

    Inpbool l ntion> all you neevpopmail_set_user_quotallBaçãoamstricl used, stricl domain, otricl quota) ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left>laçã"çãçlaçEssa insção é EXPERIMENTALem futuras versões do ass, SEM QUALQUER laçã"çãçNOTIFICAÇÃO. Esseja avissdo, e use essa insção podlsua própris=colaa el çã"çãçrisco.lanclaTD>la
    sessiol

    ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left>laçã"çãçlaçEssa insção não essá dH1 classda,nsoalntbla lissa de arg clasos essá laçã"çãçdisponível.lanclaTD>la
    sesslancla
    llDHR>

    e 1 classtitle>CV. W32api l you nes
    e 1 classctiolla> Currently supporoed types arelgeneric ass types (otricls, booleans, floats, amsetegers and

    Iw32api-deftype">secame=swf.installatw32api_deftype(tion> ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left>laçã"çãçlaçEsse=módulo é EXPERIMENTALe=módulo ---=poderá mudar>em futuras laçã"çãçversões do ass, SEM QUALQUER NOTIFICAÇÃO. Esseja avissdo, e use esse=laçã"çãçmódulo podlsua própris=colaa elrisco.lanclaTD>la
    la
    iol

    eR>la e 1 classctiolla>

    eR>la e 1 classctiolla> iestclação nescessáris= you utilizar>estcs fnsções, elcs fazem poroe do núcleo do ass.=Oncla

    eR>la e 1 classctiolla> fileu nee>

    eR>la e 1 classctiolla> this resource"dyna yom"

    eR>la e 1 classctiolla> =Onc se

    laçãoDT>DC_MICROSOFT

    seteger "çeP>=Onc sçãoDT>DC_BORLAND

    seteger "çeP>=Onc sçãoDT>DC_CALL_CDECL

    seteger "çeP>=Onc sçãoDT>DC_CALL_STD

    seteger "çeP>=Onc sçãoDT>DC_RETVAL_MATH4

    seteger "çeP>=Onc sçãoDT>DC_RETVAL_MATH8

    seteger "çeP>=Onc sçãoDT>DC_CALL_STD_BO

    seteger "çeP>=Onc sçãoDT>DC_CALL_STD_MS

    seteger "çeP>=Onc sçãoDT>DC_CALL_STD_M8

    seteger "çeP>=Onc sçãoDT>DC_FLAG_ARGPTR

    seteger "çeP>=Onclala
    la

    eR>la e 1 classctiolla> time thb syssem has been runninglandie=a message box.nlanc=seTABLE c "çeTBODY>laçãoTR>laçãçãoTD>laçãçãçãoD

    Exemplo 1. Get thb uptime andie=a message box ãçã"çãçlTBODY>laçãçã"çãçlTR>laçãçã"çãççãoTD>
    <?pla
    laTD>la
    la
    iol

    L>laçãoDT>ÍndicelaçãoDT>w32api_deftypellatd to dclass=seDefines"yo="aw32api_init_dtypellatd to dclass=se yo="Creaaes"an>iestcnce of>the data

    Iw32api-invoke-ion>">w32api_invoke_l you nellatd to dclass=seInvokes"yo="installa fnstname with the arg class"pon>edw32api_regisser_installallatd to dclass=seRegissers"yo="installa fnstalla_name fromBlibrary with tiolaçãoDT>w32api_set_ la
    la
    e libswf all you neew32api-deftypeallatw32api_deftypellon>

    Inpbool l ntion> all you neew32api_deftypellBaçãostrings typename, otricl member1_type, otricl member1_name [, otricl ... [, otricl ...]]) ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left>laçã"çãçlaçEssa insção é EXPERIMENTALem futuras versões do ass, SEM QUALQUER laçã"çãçNOTIFICAÇÃO. Esseja avissdo, e use essa insção podlsua própris=colaa el çã"çãçrisco.lanclaTD>la
    sessIf you wouldBlike to define a.nThismembers thb type has.nThe=first arg clas is thb name of>thes type. Afser thas is thb type of>thesmember followed by>thesmembers name (in pairs). Asmember type cae beie=type names shouldBbeie=lowercase. R torna sbswamtion> colstcla>TRUE colstcla>FALSE e libswf all you neew32api-init-dtypeallatw32api_init_dtypellon>

    iestcnce of>the dataed

    Inpresource all you neew32api_init_dtypellBaçãostrings typename, mixed value [, mixed ...]) ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left>laçã"çãçlaçEssa insção é EXPERIMENTALem futuras versões do ass, SEM QUALQUER laçã"çãçNOTIFICAÇÃO. Esseja avissdo, e use essa insção podlsua própris=colaa el çã"çãçrisco.lanclaTD>la
    sessThisiestcnce of>the data youalleralI>typenamethe datatypenamethe data

    Iw32api-deftype">secame=swf.installatw32api_deftype(tion>thesresourceisdyna yom e libswf all you neew32api-invoke-ion>allatw32api_invoke_l you nellon>

    ed

    Inpmixed l ntion> all you neew32api_invoke_l you nellBaçãoamstricl fnstname, mixed arg clas [, mixed ...]) ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left>laçã"çãçlaçEssa insção é EXPERIMENTALem futuras versões do ass, SEM QUALQUER laçã"çãçNOTIFICAÇÃO. Esseja avissdo, e use essa insção podlsua própris=colaa el çã"çãçrisco.lanclaTD>la
    sessl ntion> installatw32api_invoke_l you ne(tion> tries so find>the previously laregissered f you ne, ass=s sbswe=swf. youalleralI>fnstnameinglthes youallers you provided. Thb r turn type is thb onblyou set whbnlyou regissered thblinstalla,=the value is thb onblr turned>by>thesinstalla itself. Any of>thes arg class"cae beany ass type odl

    Iw32api-deftype">secame=swf.installatw32api_deftype(tion>

    e libswf all you neew32api-regisser-ion>allatw32api_regisser_installallon>

    llatiolon>Inpbool l ntion> all you neew32api_regisser_installallBaçãoamstricl libary, otricl installa_name, otricl r turn_type) ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left>laçã"çãçlaçEssa insção é EXPERIMENTALem futuras versões do ass, SEM QUALQUER laçã"çãçNOTIFICAÇÃO. Esseja avissdo, e use essa insção podlsua própris=colaa el çã"çãçrisco.lanclaTD>la
    sessThisthe sbswe=swf. youalleralI>fnstalla_namelibaryieto laass.nThe=fnstalla will be regissered with the given sbswamtion> youalleralI>r turn_type

    Iw32api-deftype">secame=swf.installatw32api_deftype(tion>ie=type names shouldBbeie=lowercase. R torna sbswamtion> colstcla>TRUE colstcla>FALSE e libswf all you neew32api-set-

    Inpvoid l ntion> all you neew32api_set_ ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left>laçã"çãçlaçEssa insção é EXPERIMENTALem futuras versões do ass, SEM QUALQUER laçã"çãçNOTIFICAÇÃO. Esseja avissdo, e use essa insção podlsua própris=colaa el çã"çãçrisco.lanclaTD>la
    sessThisthes colstclas DC_CALL_CDECL colstcla>DC_CALL_STD colstcla>DC_CALL_STD

    e 1 classtitle>CVI. WDDX Fnstallas
    e 1 classctiolla> WDDX HR> eR>la e 1 classctiolla> thesexpatBlibrary (whichç omes"yowith Apaches1.3.7çodlhigher). =Oncla
    HR> eR>la e 1 classctiolla>
    >--enable-wddxlaTTa.w

    lbswe=swf.literal>tiollTTaçhas built>ie=supporo fodl this extenslla. You do not need to load any addi
    allextenslla in ordOn so use thbse=fnstallas.=Oncla

    eR>la e 1 classctiolla> fileu nee>

    eR>la e 1 classctiolla>

    eR>la e 1 classctiolla>

    eR>la e 1 classctiolla> an arrayç to determine whll er thblarrayçis so be serialized>ieto an arrayçodlstructure. If thb first eleclas has otricl key,=then it>is serialized>ieto alstructure, laothbrwise,=into an array.w "çeTBODY>laçãoTR>laçãçãoTD>laçãçãçãoD

    llatioçã"çãçlaçExemplo 1. Serializicl alsiclle value ãçã"çãçlTBODY>laçãçã"çãçlTR>laçãçã"çãççãoTD>
    <?p

    la
    laTD>laP>
    ãeTBODY>laçãoTR>laçãçãoTD>
    <wddxPacket verslla='1.0'><headOn  omclas='ass packet'/><data>
    <otricl>ass to WDDX packet example</otricl></data></wddxPacket>çãPREclaTD>iolaçlancla
    TABLE c "çeTBODY>laçãoTR>laçãçãoTD>laçãçãçãoD

    Exemplo 2. Usingliecreclasallpackets ãçã"çãçlTBODY>laçãçã"çãçlTR>laçãçã"çãççãoTD>
    <?pla
    laTD>iolaçlanc=sessThis examplelwill produce:

    llatiolaçlanc=seTABLE cellPadding=5 bgColor=#e0e0e0 bnrdOn=0> ãeTBODY>laçãoTR>laçãçãoTD>
    <wddxPacket verslla='1.0'><headOn  omclas='ass'/><data><otruct>
    <var name='pi'><number>3.1415926</number></var><var name='ciiolaçlancla
    açlanc=se

    Nota: secamãç classinstallatsetlocsle(tion>la
    la

    L>laçãoDT>ÍndicelaçãoDT>wddx_add_vars

    Iwddx-deserialize">wddx_deserializewddx_packet_endIDlaçãoDT>wddx_packet_stcrtlaçãoDT>wddx_serialize_value

    Iwddx-serialize-vars">wddx_serialize_varssecame=swf.installatwddx_serialize_vars(tion> e libswf all you neewddx-deserialize>

    (ass 3>= 3.0.7, ass 4 )ce ywddx_deserialized to dclass=seDeserializes"al WDDX packet

    Inpmixed l ntion> all you neewddx_deserialize installatwddx_deserialize(tion> takes assbswamtion> youalleralI>packetthes resultarel deserialized>ieto associssive=arrays.n=Oncla
    e libswf all you neewddx-packet-end>

    (ass 3>= 3.0.7, ass 4 )ce ywddx_packet_endd to dclass=seEnds"aID

    Inpstringsl ntion> all you neewddx_packet_end installatwddx_packet_end(tion> ends"the WDDX packet specified>by>thes albswe=swf. youalleralI>packet_idthesstringswith the packet.n=Oncla
    e libswf all you neewddx-packet-stcrt>

    (ass 3>= 3.0.7, ass 4 )ce ywddx_packet_stcrtd to dclass=se Stcrts"a

    Inpint l ntion> all you neewddx_packet_stcrt installatwddx_packet_stcrt(tion> to stcrt"a of>variables. It takes a> opallsbswamtion> youalleralI> omclasa packet ID fodluse in laser fnstallas. It automsalcally creaaes"a structure defini ilside the packet to olaaie=the variables. =Oncla
    e libswf all you neewddx-serialize-value>

    (ass 3>= 3.0.7, ass 4 )ce ywddx_serialize_valued to dclass=seSerialize al siclle value>ieto alWDDX packet

    Inpstringsl ntion> all you neewddx_serialize_value installatwddx_serialize_value(tion> is used to creaae"a olaaieed>in sbswamtion> youalleralI>var opallsbswamtion> youalleralI> omclasthesWDDX packet. =Oncla
    e libswf all you neewddx-serialize-vars>

    (ass 3>= 3.0.7, ass 4 )ce ywddx_serialize_varsd to dclass=seSerialize yovariables ieto alWDDX packet

    Inpstricl l ntion> all you neewddx_serialize_vars installatwddx_serialize_vars(tion> is used to creaae"athesserialized>represlasa of>the pan>ed installatwddx_serialize_vars(tion> takes asvariable number of> arg class, eachçof>whichç ae be "çeTBODY>laçãoTR>laçãçãoTD>laçãçãçãoD

    Exemplo 1. l ntion> installatwddx_serialize_vars(tion> ioçãçãçãexample ãçã"çãçlTBODY>laçãçã"çãçlTR>laçãçã"çãççãoTD>
    <?pla
    laTD>laP> ãeTBODY>laçãoTR>laçãçãoTD>
    <wddxPacket verslla='1.0'><headOn/><data><otruct><var name='a'><number>1</number></var>
    <var name='b'><number>5.5</number></var><var name='c'><arrayçleugon='3'>
    <otricl>blue</otricl><otricl>odange</otricl><otricl>violet</otricl></array></var>
    <var name='d'><otricl>colors</otricl></var></otruct></data></wddxPacket>çãPREclaTD>=Oncla

    e 1 classtitle>CVII. XML= yoser fnstallas
    e 1 classctiolla> The"World Wide Webç olsortium (W3C). Informsalla"about XML=and r lased technolog/es"cae be to dclwww.w3.org/XML/ roductu neeexpatçãSPAN1"ie=Pss.nThis soolkit>letsthree source

    characlers encodings

    by ass: lbswe=swf.literal>US-ASCIIçãTTa, literal>ISO-8859-1çãTTasandUTF-8çãTTa.nsbswamtion> literal>UTF-16çãTTasis not supporoed. =Onc sessThis extenslla lets

    Ixml- yoser-creaae">creaae" XML= yosers

    thea define handlers

    Ixml- yoser-set-op"> youallers

    eR>la e 1 classctiolla> whichç ae be to dclwww.jclark. om/xml/ ãeTBODY>laçãoTR>laçãçãoTD>
    libexpat.a: $(OBJS)laçãçãar -rc $@ $(OBJS)laçãçãdanlib $@çãPREclaTD>A sourceexpatB an 
    be to dclsourcefodge.net/ rojtios/expat/
    
    

    eR>la e 1 classctiolla> inglthesbundledsexpatBlibrary. You an disable XML=supporo with >--disable-xmlçãTTa.nIf you ompile laass as a op>--with-expat-dir=DIRçãTTa,expat. =Onc sessThe windows verslla of>lbswe=swf.literal>tiollTTaçhas built>ie=supporo fodl this extenslla. You do not need to load any addiallextenslla in ordOn so use thbse=fnstallas.=Oncla

    eR>la e 1 classctiolla> fileu nee>

    eR>la e 1 classctiolla>

    eR>la e 1 classctiolla> =Onc se

    laçãoDT>XML_ERROR_NONE

    seteger "çeP>=Onc sçãoDT>XML_ERROR_NO_MEMORY

    seteger "çeP>=Onc sçãoDT>XML_ERROR_SYNTAX

    seteger "çeP>=Onc sçãoDT>XML_ERROR_NO_ELEMENTS

    seteger "çeP>=Onc sçãoDT>XML_ERROR_INVALID_TOKEN

    seteger "çeP>=Onc sçãoDT>XML_ERROR_UNCLOSED_TOKEN

    seteger "çeP>=Onc sçãoDT>XML_ERROR_PARTIAL_CHAR

    seteger "çeP>=Onc sçãoDT>XML_ERROR_TAG_MISMATCH

    seteger "çeP>=Onc sçãoDT>XML_ERROR_DUPLICATE_ATTRIBUTE

    seteger "çeP>=Onc sçãoDT>XML_ERROR_JUNK_AFTER_DOC_ELEMENT

    seteger "çeP>=Onc sçãoDT>XML_ERROR_PARAM_ENTITY_REF

    seteger "çeP>=Onc sçãoDT>XML_ERROR_UNDEFINED_ENTITY

    seteger "çeP>=Onc sçãoDT>XML_ERROR_RECURSIVE_ENTITY_REF

    seteger "çeP>=Onc sçãoDT>XML_ERROR_ASYNC_ENTITY

    seteger "çeP>=Onc sçãoDT>XML_ERROR_BAD_CHAR_REF

    seteger "çeP>=Onc sçãoDT>XML_ERROR_BINARY_ENTITY_REF

    seteger "çeP>=Onc sçãoDT>XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF

    seteger "çeP>=Onc sçãoDT>XML_ERROR_MISPLACED_XML_PI

    seteger "çeP>=Onc sçãoDT>XML_ERROR_UNKNOWN_ENCODING

    seteger "çeP>=Onc sçãoDT>XML_ERROR_INCORRECT_ENCODING

    seteger "çeP>=Onc sçãoDT>XML_ERROR_UNCLOSED_CDATA_SECTION

    seteger "çeP>=Onc sçãoDT>XML_ERROR_EXTERNAL_ENTITY_HANDLING

    seteger "çeP>=Onc sçãoDT>XML_OPTION_CASE_FOLDING

    seteger "çeP>=Onc sçãoDT>XML_OPTION_TARGET_ENCODING

    seteger "çeP>=Onc sçãoDT>XML_OPTION_SKIP_TAGSTART

    seteger "çeP>=Onc sçãoDT>XML_OPTION_SKIP_WHITE

    seteger "çeP>=Oncla
    la

    eR>la e 1 classctiolla> Tabela 1. Supporoed XML=handlers ãoTHEAD> "çeTR>laçãçãoTH vAlign=clntbr align=left>ass fnstalla to setlhandlerlaTH>laçãçãoTH vAlign=clntbr align=left>Evlas d/A>Inp "çeTBODY>laçãoTR>laçãçãoTD vAlign=clntbr align=left>

    Ixml-set-eleclas-handler">secamãçççççc laçãçãoTD vAlign=clntbr align=left>Eleclas evlass arelsssued whbnevlr thblXML=amãççççç yoser encounlers stcrt"odlend>tags.nThere arelse youte handlers fodlstcrt"amãçççççtags and>end>tags.nlaçãoTR>laçãçãoTD vAlign=clntbr align=left>

    Ixml-set-characler-data-handler">secamãçççççc

    laçãçãoTD vAlign=clntbr align=left>Characlersdataodlremove any whitespace, it>is up so thb amãçççççapplicaolla (you) to decide whll er whitespace is significant.nlaçãoTR>laçãçãoTD vAlign=clntbr align=left>

    Ixml-set-processing-ilstruct/A>-handler">secamãçççççc _handler(tion>

    laçãçãoTD vAlign=clntbr align=left>ass progouamers shouldBbes (PIs) already. <?p,these arelapplicaolla-specific, exceptsthas alaçãoTR>laçãçãoTD vAlign=clntbr align=left>

    Ixml-set-default-handler">secamãçççççc laçãçãoTD vAlign=clntbr align=left>Whas goes not to anothbr handler goes so thb amãçççççdefaultlaçãoTR>laçãçãoTD vAlign=clntbr align=left>

    Ixml-set-un yosed-lasity-dec -handler">secamãçççççc

    laçãçãoTD vAlign=clntbr align=left>This handler will be calledsfodldec raollacamãçççççof>an un yosed (NDATA) lasity. =OTD>laçãoTR>laçãçãoTD vAlign=clntbr align=left>

    Ixml-set-notaolla-dec -handler">secamãçççççc

    laçãçãoTD vAlign=clntbr align=left>This handler is calledsfodldec raollacof>acamãçççççnotaolla. =OTD>laçãoTR>laçãçãoTD vAlign=clntbr align=left>

    Ixml-set-external-lasity- ne-handler">secamãçççççc

    laçãçãoTD vAlign=clntbr align=left>This handler is calledswhbnlthblXML= yoser amãçççççfinds"a rseerence to an external yosed generalleasity. This cae be

    thb amãçççççexternal lasityãexample fodla demolstraolla. io aTD>la
    sesslOncla

    eR>la e 1 classctiolla> case-foldedthblXML=standard as la"a rocesslapplied to alsequence of>characlers,=in>whichçthose ideasified>as lanon-uppercase arelreplacedthbir uppercase equivallass". In ol er wnrds, whbn is omes"to XML, case-folding simply means uppercasing.nlanc=seP>By default, cll>theseleclas names"thas are pan>edand

    Ixml- yoser-get-op">secame=swf.installatxml_ yoser_get_op(tion>


    Ixml- yoser-set-op">secame=swf.installatxml_ yoser_set_op(tion>

    la

    eR>la e 1 classctiolla> by>

    Ixml- yose">secame=swf.installatxml_ yose(tion>=Onc seTABLE bnrdOn=0> ãeTBODY>laçãoTR>laçãçãoTD>XML_ERROR_NONElaçãoTR>laçãçãoTD>XML_ERROR_NO_MEMORYlaçãoTR>laçãçãoTD>XML_ERROR_SYNTAXlaçãoTR>laçãçãoTD>XML_ERROR_NO_ELEMENTSlaçãoTR>laçãçãoTD>XML_ERROR_INVALID_TOKENlaçãoTR>laçãçãoTD>XML_ERROR_UNCLOSED_TOKENlaçãoTR>laçãçãoTD>XML_ERROR_PARTIAL_CHARlaçãoTR>laçãçãoTD>XML_ERROR_TAG_MISMATCHlaçãoTR>laçãçãoTD>XML_ERROR_DUPLICATE_ATTRIBUTElaçãoTR>laçãçãoTD>XML_ERROR_JUNK_AFTER_DOC_ELEMENTlaçãoTR>laçãçãoTD>XML_ERROR_PARAM_ENTITY_REFlaçãoTR>laçãçãoTD>XML_ERROR_UNDEFINED_ENTITYlaçãoTR>laçãçãoTD>XML_ERROR_RECURSIVE_ENTITY_REFlaçãoTR>laçãçãoTD>XML_ERROR_ASYNC_ENTITYlaçãoTR>laçãçãoTD>XML_ERROR_BAD_CHAR_REFlaçãoTR>laçãçãoTD>XML_ERROR_BINARY_ENTITY_REFlaçãoTR>laçãçãoTD>XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REFlaçãoTR>laçãçãoTD>XML_ERROR_MISPLACED_XML_PIlaçãoTR>laçãçãoTD>XML_ERROR_UNKNOWN_ENCODINGlaçãoTR>laçãçãoTD>XML_ERROR_INCORRECT_ENCODINGlaçãoTR>laçãçãoTD>XML_ERROR_UNCLOSED_CDATA_SECTIONlaçãoTR>laçãçãoTD>XML_ERROR_EXTERNAL_ENTITY_HANDLINGiolaçlanc=sess

    la

    eR>la e 1 classctiolla> the Unicode

    characlersencodings.nThere areltwo=types of>characler encodings, source and<target encoding of>the dH1 clas=is"alwaysUTF-8çãTTa.nsanc=sessSource

    Ixml- yose"> yosed

    Ixml- yoser-creaae">creaaing aman XML= yoser(this encoding ae not bes changedllaser"ie=the XML= yoser'sslifetime). The"supporoedlsourcearel ISO-8859-1çãTTa, US-ASCIIçãTTasand literal>UTF-8çãTTa.nThe former"two=arelsiclle-bytewhichçmeans thas eachçcharacler is represlased>by>a siclle byte.nsbswamtion> literal>UTF-8çãTTa ae encode characlers omposed>by>a variable number of> bios>(up so 21) in one to four bytes.nThe defaultby ass>isISO-8859-1çãTTa. =Onc sessTarget encoding is done whln ass pan>essdatathessource< encoding, but this may be changedlas anyBpoint.nThe target encoding will afeects characlersdatawell as tag names"and< rocessing ilstruct/A> targets. =Onc sessIf thb XML= yoser encounlers characlers outside the dange"thas ios>source< encoding is capable of represlasing, it will r turn ae error. =Onc sessIf ass encounlers characlers ie=the paosed XML=dH1 clasie=the chosen target encoding,=the roblem characlers will be "demosed". Currently,=this means thas suchçcharaclers arelreplaceda mark. =Oncla

    eR>la e 1 classctiolla> Inp eR>la e21 classctiolla>the stcrt"eleclass"ie=açdH1 clas amwith indlasa.w "çeTBODY>laçãoTR>laçãçãoTD>laçãçãçãoD

    Exemplo 1. Show XML=Eleclas Structure ãçã"çãçlTBODY>laçãçã"çãçlTR>laçãçã"çãççãoTD>
    $file = "data.xml";la$depth = array();la
    fnstalla stcrtEleclas($paoser, $name, $attrs) {laçãçãglobal $depth;laçãçãfodl($i = 0; $i < $depth[$paoser]; $i++) {laçãçãããããprset "  ";laçãçã}laçãçãprset "$name\n";laçãçã$depth[$paoser]++;la}la
    fnstalla endEleclas($paoser, $name) {laçãçãglobal $depth;laçãçã$depth[$paoser]--;la}la
    $xml_ yoser = xml_ yoser_creaae();laxml_set_eleclas_handler($xml_ yoser, "stcrtEleclas",ã"endEleclas");laif (!($fp = fopen($file,ã"r"))) {laçãçãdie("couldBnot open XML=inpus");la}la
    while ($data<= fread($fp, 4096)) {laçãçãif (!xml_ yose($xml_ yoser, $data, feof($fp))) {laçãçãçãçãdie(sprsetf("XML=error: %s atBline %d",laçãçã"çãççãããããããããããxml_error_otricl(xml_get_error_code($xml_ yoser)),laçãçã"çãççãããããããããããxml_get_current_line_number($xml_ yoser)));laçãçã}la}laxml_ yoser_free($xml_ yoser);çãPREclaTD>

    la
    laTD>laP>la

    eR>la e21 classctiolla> "çeTBODY>laçãoTR>laçãçãoTD>laçãçãçãoD

    Exemplo 2. Map XML=so HTMLcourse, this examplelioçãçãçãwill onlylwnrk with a ãçã"çãçlTBODY>laçãçã"çãçlTR>laçãçã"çãççãoTD>
    $file = "data.xml";la$map_arrayç= array(laçãçã"BOLD"çãççã=> "B",laçãçã"EMPHASIS"ã=> "I",laçãçã"LITERAL"çã=> "TT"
    );la
    fnstalla stcrtEleclas($paoser, $name, $attrs) {laçãçãglobal $map_array;laçãçãif ($allatag = $map_array[$name]) {laçãçãããããprset "<$allatag>";laçãçã}la}la
    fnstalla endEleclas($paoser, $name) {laçãçãglobal $map_array;laçãçãif ($allatag = $map_array[$name]) {laçãçãããããprset "</$allatag>";laçãçã}la}la
    fnstalla characlerData($paoser, $data) {laçãçãprset $data;la}la
    $xml_ yoser = xml_ yoser_creaae();la// use case-folding so>we arelsure toçfind=the tag il $map_arraylaxml_ yoser_set_op($xml_ yoser, XML_OPTION_CASE_FOLDING, true);laxml_set_eleclas_handler($xml_ yoser, "stcrtEleclas",ã"endEleclas");laxml_set_characler_data_handler($xml_ yoser, "characlerData");laif (!($fp = fopen($file,ã"r"))) {laçãçãdie("couldBnot open XML=inpus");la}la
    while ($data<= fread($fp, 4096)) {laçãçãif (!xml_ yose($xml_ yoser, $data, feof($fp))) {laçãçãçãçãdie(sprsetf("XML=error: %s atBline %d",laçãçã"çãççãããããããããããxml_error_otricl(xml_get_error_code($xml_ yoser)),laçãçã"çãççãããããããããããxml_get_current_line_number($xml_ yoser)));laçãçã}la}laxml_ yoser_free($xml_ yoser);çãPREclaTD>laP>la
    laTD>laP>la

    eR>la e21 classctiolla>well as how PIs cae be< rocessed,=anddetermining "trust"ãfodlPIs colaaieinglcode.

    fodlthis "çeTBODY>laçãoTR>laçãçãoTD>laçãçãçãoD

    Exemplo 3.=External EasityãExample ãçã"çãçlTBODY>laçãçã"çãçlTR>laçãçã"çãççãoTD>
    <?pby>ourselveslaçãçãif (!eregi("^([a-z]+)://",ã$file) laçãçã"çãç&& fileowner($file) == getmyuid()) {laçãçãçãçãããããr turn true;laçãçã}laããããr turn false;la}la
    fnstalla stcrtEleclas($paoser, $name, $attribs) {laçãçãprset "&lt;<fola color=\"#0000cc\">$name</fola>";laçãçãif (sizeof($attribs)) {laçãçãçãçãwhile (liss($k, $v) = each($attribs)) {laçãçãçãçãçãçãprset " <fola color=\"#009900\">$k</fola>=\"<fola laçãçã"çãççããããããããããcolor=\"#990000\">$v</fola>\"";laçãçããããã}laçãçã}laããããprset "&gt;";la}la
    fnstalla endEleclas($paoser, $name) {laçãçãprset "&lt;/<fola color=\"#0000cc\">$name</fola>&gt;";la}la
    fnstalla characlerData($paoser, $data) {laçãçãprset "<b>$data</b>";la}la
    fnstalla PIHandler($paoser, $target, $data) {laçãçãswitch (strtolower($target)) {laçãçãçãçãcase "pthe parsed>dH1 clasis safelaçãçã"çãççããã// to=executelass code ilside it.  If>not,ldisplay=the codelaçãçã"çãççããã// ilstead.laçãçã"çãççãããif (trustedFile($ yoser_file[$paoser])) {laçãçãçãçãçãçãããããeval($data);laçãçã"çãççããã} else {laçãçãçãçãçãçãããããprsetf("Untrustedlass code: <i>%s</i>", laçãçã"çãççãããããããããããããããallaspecialchars($data));laçãçã"çãççããã}laçãçã"çãççãããbreak;laçãçã}la}la
    fnstalla defaultHandler($paoser, $data) {laçãçãif (substr($data, 0, 1) == "&"ç&& substr($data, -1, 1) == ";") {laçãçãããããprsetf('<fola color="#aa00aa">%s</fola>', laçãçã"çãççãããããããallaspecialchars($data));laçãçã} else {laçãçãçãçãprsetf('<fola size="-1">%s</fola>', laçãçã"çãççãããããããallaspecialchars($data));laçãçã}la}la
    fnstalla externalEasityRefHandler($paoser, $openEasityNames, $base, $systemId,laçãçã"çãççããããããããããããããããããããããããã$publicId) {laçãçãif ($systemId) {laçãçãããããif (!liss($paoser, $fp) = new_xml_ yoser($systemId)) {laçãçãçãçãçãçãprsetf("CouldBnot open ensityã%s atB%s\a", $openEasityNames,laçãçã"çãççãããããããããã$systemId);laçãçã"çãççãããr turn false;la"çãççããã}laçãçã"çãçwhile ($data<= fread($fp, 4096)) {laçãçãããããããããif (!xml_ yose($ yoser, $data, feof($fp))) {laçãçãçãçãããããããããprsetf("XML=error: %s atBline %dçwhile  yosinglensityã%s\a",laçãçã"çãççããããããããããããããxml_error_otricl(xml_get_error_code($ yoser)),laçãçã"çãççããããããããããã ããxml_get_current_line_number($ yoser), $openEasityNames);laçãçã"çãççãããã ããxml_ yoser_free($ yoser);laçãçã"çãççãããã ããr turn false;la"çãççããããããã}laçãçã"çãç}laçãçã"çãçxml_ yoser_free($ yoser);laçãçã"çãçr turn true;laçãçã}laããããr turn false;la}la
    fnstalla new_xml_ yoser($file) {laçãçãglobal $ yoser_file;lalaçãçã$xml_ yoser = xml_ yoser_creaae();la"çãçxml_ yoser_set_op($xml_ yoser, XML_OPTION_CASE_FOLDING, 1);la"çãçxml_set_eleclas_handler($xml_ yoser, "stcrtEleclas",ã"endEleclas");la"çãçxml_set_characler_data_handler($xml_ yoser, "characlerData");la"çãçxml_set_processing_ilstruct/A>_handler($xml_ yoser, "PIHandler");la"çãçxml_set_default_handler($xml_ yoser, "defaultHandler");la"çãçxml_set_external_lasity_ ne_handler($xml_ yoser, "externalEasityRefHandler");la"çãçlaçãçãif (!($fp = @fopen($file,ã"r"))) {laçãçãããããr turn false;laçãçã}laããããif (!is_array($ yoser_file)) {laçãçãããããsettype($ yoser_file,ã"array");laçãçã}laãããã$ yoser_file[$xml_ yoser] = $file;laçãçãr turn array($xml_ yoser, $fp);la}la
    if (!(liss($xml_ yoser, $fp) = new_xml_ yoser($file))) {laçãçãdie("couldBnot open XML=inpus");la}la
    prset "<pre>";lawhile ($data<= fread($fp, 4096)) {laçãçãif (!xml_ yose($xml_ yoser, $data, feof($fp))) {laçãçãçãçãdie(sprsetf("XML=error: %s atBline %d\a",laçãçã"çãççãããããããããããxml_error_otricl(xml_get_error_code($xml_ yoser)),laçãçã"çãççãããããããããããxml_get_current_line_number($xml_ yoser)));laçãçã}la}laprset "</pre>";laprset " yose  omplete\n";laxml_ yoser_free($xml_ yoser);lala?>çãPREclaTD>la
    laTD>laP> "çeTBODY>laçãoTR>laçãçãoTD>laçãçãçãoD

    Exemplo 4.ãxmloest.xmlçãBclaPtioçãçãçãoTABLE cellPadding=5 bgColor=#e0e0e0 bnrdOn=0> ãçã"çãçlTBODY>laçãçã"çãçlTR>laçãçã"çãççãoTD>
    <?xml verslla='1.0'?>
    <!DOCTYPE chaplersSYSTEM "/just/a/oest.dtd" [
    <!ENTITY plainEasity "FOOlensity">
    <!ENTITY systemEasity SYSTEM "xmloest2.xml">
    ]>
    <chapler>
     <TITLE>Titleç&plainEasity;</TITLE>
     < yoa>
      <informsltable>
       <tgroup cols="3">
        <tbody>
         <row><ensry>a1</ensry><ensry morerows="1">b1</ensry><ensry>c1</ensry></row>
         <row><ensry>a2</ensry><ensry>c2</ensry></row>
         <row><ensry>a3</ensry><ensry>b3</ensry><ensry>c3</ensry></row>
        </tbody>
       </tgroup>
      </informsltable>
     </ yoa>
     &systemEasity;
     <ctiolla id="about">
      <title>About this<

    la
    laTD>laP> "çeTBODY>laçãoTR>laçãçãoTD>laçãçãçãoD

    Exemplo 5.ãxmloest2.xmlçãBclaPtioçãçãçãoTABLE cellPadding=5 bgColor=#e0e0e0 bnrdOn=0> ãçã"çãçlTBODY>laçãçã"çãçlTR>laçãçã"çãççãoTD>
    <?xml verslla="1.0"?>
    <!DOCTYPE foo [
    <!ENTITY oestEet "oestlensity">
    ]>
    <foo>
       <eleclas attrib="value"/>
       &oestEet;
       <?pla
    laTD>laP>la
    la
    la

    L>laçãoDT>Índice

    Iutf8-decode">utf8_decodellatd to dclass=se ="Converts a stringswith ISO-8859-1çcharaclers encoded

    Iutf8-encode">utf8_encodellatd to dclass=seencodess ="an ISO-8859-1çstringsto UTF-8ioçãoDT>

    Ixml-error-string">xml_error_otriclllatd to dclass=seget XML= yoser error otriclioçãoDT>

    Ixml-get-current-byte-indlx">xml_get_current_byte_indlxllatd to dclass=seget current byte indlx fodlan XML= yoserioçãoDT>

    Ixml-get-current-column-number">xml_get_current_column_numberllatd to dclass=se ="Get current column number fodlan XML= yoserwioçãoDT>

    Ixml-get-current-line-number">xml_get_current_line_numberllatd to dclass=seget current line number fodlan XML= yoserioçãoDT>

    Ixml-get-error-code">xml_get_error_codellatd to dclass=seget XML= yoser error codelaçãoDT>

    Ixml- yose-into-struct"txml_ yose_into_structllatd to dclass=sePyose XML=data

    Ixml- yose"txml_ yosellatd to dclass=sestcrt"amãç yosingsan XML=dH1 claslaçãoDT>

    Ixml- yoser-creaae-ns"txml_ yoser_creaae_nsllatd to dclass=se ="Creaae"an XML= yoserwioçãoDT>

    Ixml- yoser-creaae"txml_ yoser_creaaellatd to dclass=secreaae" lan XML= yoserioçãoDT>

    Ixml- yoser-free"txml_ yoser_freellatd to dclass=seFree lan XML= yoserioçãoDT>

    Ixml- yoser-get-op">xml_ yoser_get_opllatd to dclass=seget ops fromBan XML= yoserioçãoDT>

    Ixml- yoser-set-op">xml_ yoser_set_opllatd to dclass=seset ops in an XML= yoserioçãoDT>

    Ixml-set-characler-data-handler">xml_set_characler_data_handlerllatd to dclass=seset up characlersdata

    Ixml-set-default-handler">xml_set_default_handlerllatd to dclass=seset up default

    Ixml-set-eleclas-handler">xml_set_eleclas_handlerllatd to dclass=seset up stcrt"and>end>eleclas handlersioçãoDT>

    Ixml-set-end-namespace-dec -handler">xml_set_end_namespace_dec _handlerllatd to dclass=se ="Set up characlersdata

    Ixml-set-external-lasity- ne-handler">xml_set_external_lasity_ ne_handlerllatd to dclass=seset up external lasityãrseerence handlerioçãoDT>

    Ixml-set-notaolla-dec -handler">xml_set_notaolla_dec _handlerllatd to dclass=seset up notaollaldec raollachandlerioçãoDT>

    Ixml-set-objtio">xml_set_objtiollatd to dclass=seUse XML=Pyoserwwithin an objtioioçãoDT>

    Ixml-set-processing-ilstruct/A>-handler">xml_set_processing_ilstruct/A>_handlerllatd to dclass=se ="Set up rocessing ilstruct/A> (PI)

    Ixml-set-stcrt-namespace-dec -handler">xml_set_stcrt_namespace_dec _handlerllatd to dclass=se ="Set up characlersdata

    Ixml-set-un yosed-lasity-dec -handler">xml_set_un yosed_lasity_dec _handlerllatd to dclass=se ="Set up un yosed lasityãdec raollachandler

    Inocket-l at-error">< name=swf.installatiockea_f at_errorction>

    Inocket-cr aae">< name=swf.installatiockea_cr aae( ion>

    Inocket-getpeertall">< name=swf.installatiockea_getpeertall( ion>

    Inocket-l at-error">< name=swf.installatiockea_f at_errorction>

  • Ifopen">< nam ction>
    fopen( all

    Inocket-l at-error">< name=swf.installatiockea_f at_errorction>

    la
    la
    H1>Iutf8-decodeallatutf8_decodellon> <

    (ass 3>= 3.0.6, ass 4 )laP>utf8_decoded to dclass=se Converts a stringsamwith ISO-8859-1çcharaclers encoded

    D/A>Inp

    strings ( stringsamdata)

    literal>UTF-8çãTTa encoded,ISO-8859-1çãTTa. =Onc sessSee

    Iutf8-encode">secame=swf.installatutf8_encode(tion>

    of>UTF-8 encoding.w

    la
    H1>Iutf8-encodeallatutf8_encodellon> <

    (ass 3>= 3.0.6, ass 4 )laP>utf8_encoded to dclass=seencodessan ISO-8859-1ç stringsto UTF-8la

    D/A>Inp

    strings ( stringsamdata)

    literal>UTF-8çãTTa,=and literal>UTF-8çãTTa is a standard mechanism used>by acronym>Unicodewide characler
    valuesUTF-8çãTTa is transparent to plainw ASCIIçãSPAN1Bcharaclers, is self-synchronized>(meaning it>iswith normsl strings omparisla installas fodlsortingsandUTF-8çãTTa haraclers ie=up so four bytes,slike this:

    Tabela 1. UTF-8 encoding ãoTHEAD> "çeTR>laçãçãoTH vAlign=clntbr align=left>byteslaçãçãoTH vAlign=clntbr align=left>bioslaçãçãoTH vAlign=clntbr align=left>represlasa "çeTBODY>laçãoTR>laçãçãoTD vAlign=clntbr align=left>1laTD>laçãçãoTD vAlign=clntbr align=left>7laTD>laçãçãoTD vAlign=clntbr align=left>0bbbbbbblaTD>laçãoTR>laçãçãoTD vAlign=clntbr align=left>2laTD>laçãçãoTD vAlign=clntbr align=left>11laTD>laçãçãoTD vAlign=clntbr align=left>110bbbbb 10bbbbbblaTD>laçãoTR>laçãçãoTD vAlign=clntbr align=left>3laTD>laçãçãoTD vAlign=clntbr align=left>16laTD>laçãçãoTD vAlign=clntbr align=left>1110bbbb 10bbbbbb 10bbbbbblaTD>laçãoTR>laçãçãoTD vAlign=clntbr align=left>4laTD>laçãçãoTD vAlign=clntbr align=left>21laTD>laçãçãoTD vAlign=clntbr align=left>11110bbb 10bbbbbb 10bbbbbb ="10bbbbbblaTD>la
    Eachçto storelcharaclersdata.w la
    H1>Ixml-error-stringallatxml_error_otriclllon> <

    (ass 3>= 3.0.6, ass 4 )laP>xml_error_otricld to dclass=seget XML= yoserwioerror otriclla

    D/A>Inp

    strings ( ila lacode)

    L>laçãoDT> "çeP>An error code fromBlbs ="u need to dclass=section>

    Ixml-get-error-code">secamãçe=swf.installatxml_get_error_code(tion>la
    P>R turnssa stringswith a texte=s d/A>Inp of>the error code sbswamtion> yoaaller>FALSEnosamd/A>Inp waslfound. =Oncla
    H1>Ixml-get-current-byte-indlxallatxml_get_current_byte_indlxllon> <

    (ass 3>= 3.0.6, ass 4 )laP>xml_get_current_byte_indlxd to dclass=seget current byte indlx fodlan XML= yoserla

    D/A>Inp

    ila ( resource< yoser)

    L>laçãoDT> "çeP>Açrseerence to thb XML= yoser to get byte indlx from. =Onclala
    P>ThisFALSEsbswamtion> yoaaller>data H1>Ixml-get-current-column-numberallatxml_get_current_column_numberllon> <

    (ass 3>= 3.0.6, ass 4 )laP>xml_get_current_column_numberd to dclass=se Get current column number fodlan XML= yoserwla

    D/A>Inp

    ila ( resource< yoser)

    L>laçãoDT> "çeP>Açrseerence to thb XML= yoser to get column number from. =Onclala
    P>ThisFALSEsbswamtion> yoaaller>by>

    Ixml-get-current-line-number">secame=swf.installatxml_get_current_line_number(tion> H1>Ixml-get-current-line-numberallatxml_get_current_line_numberllon> <

    (ass 3>= 3.0.6, ass 4 )laP>xml_get_current_line_numberd to dclass=seget current line number fodlan XML= yoserla

    D/A>Inp

    ila ( resource< yoser)

    L>laçãoDT> "çeP>Açrseerence to thb XML= yoser to get line number from. =Onclala
    P>ThisFALSEsbswamtion> yoaaller>data H1>Ixml-get-error-codeallatxml_get_error_codellon> <

    (ass 3>= 3.0.6, ass 4 )laP>xml_get_error_coded to dclass=seget XML= yoserwioerror codell

    D/A>Inp

    ila ( resource< yoser)

    L>laçãoDT> "çeP>Açrseerence to thb XML= yoser to get error code from. =Onclala
    P>ThisFALSEsbswamtion> yoaaller>the error codesslissed>ie=the

    error lacodes sec H1>Ixml- yose-into-structallatxml_ yose_into_structllon> <

    (ass 3>= 3.0.8, ass 4 )laP>xml_ yose_into_structd to dclass=sePyose XML=amdata

    D/A>Inp

    ila ( resource< yoser, stringsdata, arrayç&values<[, arrayç&indlx])

    yoaaller> of>the laappropriate valuesedBelow islan examplelthas illustraoes the ieternal structure of>the arraysby>the ion>I We use a simple noteçãTTa tag ioembeded>ieside a yoaçãTTa tag,=andlaPtio TABLE cellPadding=5 bgColor=#e0e0e0 bnrdOn=0> ãeTBODY>laçãoTR>laçãçãoTD>
    $simple = "<pyoa><note>simple note</note></ yoa>";la$p = xml_ yoser_creaae();laxml_ yose_into_struct($p,$simple,$vals,$indlx);laxml_ yoser_free($ );laecho "Indlx array\n";laprset_r($indlx);laecho "\nVals array\n";laprset_r($vals);çãPREclaTD>io

    laPtll


    Whbn we run
    laPtio TABLE cellPadding=5 bgColor=#e0e0e0 bnrdOn=0> ãeTBODY>laçãoTR>laçãçãoTD>
    Ieen>Indlx array
    Array
    (laçãçã[PARA]ã=> Array
            (
            çãçã[0]ã=> 0
            çãçã[1]ã=> 2
            )lalaçãçã[NOTE]ã=> Array
            (
            çãçã[0]ã=> 1
            )lala)lalaVals array
    Array
    (laçãçã[0]ã=> Array
            (
            çãçã[tag]ã=> PARA
            çãçã[type]ã=> open
            çãçã[level]ã=> 1
            )lalaçãçã[1]ã=> Array
            (
            çãçã[tag]ã=> NOTE
            çãçã[type]ã=>  omplete
            çãçã[level]ã=> 2
            çãçã[value]ã=> simple note
            )lalaçãçã[2]ã=> Array
            (
            çãçã[tag]ã=> PARA
            çãçã[type]ã=> close
            çãçã[level]ã=> 1
            )lala)çãPREclaTD>io

    laPtll


    P>Event-driven> yosingl(based oe=the expatBlibrary) ae get complicaoed whbn you have"an XML=dH1 clasie=a tree fash/A>I Thus,ãwb ae creaae"objtios represlasinglthe datathe iollowingsXML=iile represlasingla smcll>database of> aminoacids "çeTBODY>laçãoTR>laçãçãoTD>laçãçãçãoD

    Exemplo 1. moldbIxml - smcll>database of>molecular amãçççççinformsallaçãBclaPtioçãçãçãoTABLE cellPadding=5 bgColor=#e0e0e0 bnrdOn=0> ãçã"çãçlTBODY>laçãçã"çãçlTR>laçãçã"çãççãoTD>
    <?xml verslla="1.0"?>
    <moldb>
    laçãçã<molecule>
        çãçã<name>Alanine</name>
        çãçã<symbol>ala</symbol>
        çãçã<codedgt;A</codedgt;
        çãçã<typedgt;hydrophobic</typedgt;laçãçã</molecule>
    laçãçã<molecule>
        çãçã<name>Lysine</name>
        çãçã<symbol>lys</symbol>
        çãçã<codedgt;K</codedgt;
        çãçã<typedgt;charged</typedgt;laçãçã</molecule>
    la</moldb>çãPREclaTD>laTD>Andthe appropriate objtios: 
    
    TABLE c
    
    "çeTBODY>laçãoTR>laçãçãoTD>laçãçãçãoD

    Exemplo 2. parsemoldbIp çãçãçãmolecular objtios ãçã"çãçlTBODY>laçãçã"çãçlTR>laçãçã"çãççãoTD>
    <?p AminoAcid {laçãçãvar $name;ãã// aa namelaçãçãvar $symbol;çãçã// three letlerssymbollaçãçãvar $code;çã// one letlerscodelaçãçãvar $type;çã// hydrophobic, charged odlneutrallaçãçãlaçãçãinstalla AminoAcid ($aa) {laçãçãçãçãforeachç($aa as $k=>$v)laçãçã"çãççã  $this->$k = $aa[$k];laçãçã}la}la
    fnstalla readDatabase($filename) {laçãçã// read>the xml database of>aminoacidslaçãçã$data<= implode("",file($filename));laçãçã$ yoser = xml_ yoser_creaae();la"çãçxml_ yoser_set_op($ yoser,XML_OPTION_CASE_FOLDING,0);la"çãçxml_ yoser_set_op($ yoser,XML_OPTION_SKIP_WHITE,1);la"çãçxml_ yose_into_struct($pyoser,$data,$values,$tags);la"çãçxml_ yoser_free($ yoser);lalaçãçã// loop throughltheçstructureslaçãçãioreachç($tags as $key=>$val) {laçãçãããããif ($key == "molecule") {laçãçãããããçãçã$moldanges = $val;laçãçãããããçãçã// eachçcoasiguous pair of>arrayçlasries arelthe laçãçãããããçãçã// lower and upper dange"fodleachçmoleculeldefinilaçãçãããããçãçãfodl($i=0; $i < counl($moldanges); $i+=2) {laçãçãçãçããããããããããããã$offset =ã$moldanges[$i] + 1;laçãçãçãçããããããããã$len =ã$moldanges[$i + 1] - $offset;laçãçãçãçããããããããã$tdb[] =  yoseMol(array_slice($values, $offset,ã$len));laçãçã"çãççããã}laçãçã"çãç} else {laçãçãçãçãçãçãcoasinue;la"çãççããã}laçãçã}laããããr turn $tdb;la}la
    fnstalla  yoseMol($mvalues) {laçãçãfodl($i=0; $i < counl($mvalues); $i++)la"çãççããã$mol[$mvalues[$i]["tag"]] = $mvalues[$i]["value"];laçãçãr turn new AminoAcid($mol);la}la
    $db = readDatabase("moldbIxml");laecho "** Database of>AminoAcid objtios:\n";laprset_r($db);lala?>çãPREclaTD>la
    laTD>Afterwioexecutings varu nee$dbçãTTa colaaies an arrayçof> objtios,=andthe s>Inp< colfirmslaPtio TABLE cellPadding=5 bgColor=#e0e0e0 bnrdOn=0> ãeTBODY>laçãoTR>laçãçãoTD>
    Ieen>** Database of>AminoAcid objtios:
    Array
    (laçãçã[0]ã=> aminoacid Objtioioçããããããã(
            çãçã[name]ã=> Alanine
            çãçã[symbol]ã=> ala
            çãçã[code]ã=> A
            çãçã[type]ã=> hydrophobic
            )lalaçãçã[1]ã=> aminoacid Objtioioçããããããã(
            çãçã[name]ã=> Lysine
            çãçã[symbol]ã=> lys
            çãçã[code]ã=> K
            çãçã[type]ã=> charged
            )lala)çãPREclaTD>io

    laPtll


    la
    H1>
    Ixml- yose>llatxml_ yosellon> <

    (ass 3>= 3.0.6, ass 4 )laP>xml_ yosed to dclass=sestcrt" yosinglan XML= dH1 clasll

    D/A>Inp

    bool ( resource

    L>laçãoDT> "çeP>Açrseerence to thb XML= yoser to use.nlanc=sçãoDT> "çeP>Chunk of>data several times>with new data, as longlas=the TRUEal)laçãoDD> "çeP>If setTRUEdatala
    P>Whbn thb XML=dH1 clasfodlthe colfigured events>arel calledlas many times>as necessary, afterwwhichçthis colstcla>TRUEFALSElbswe=swf.colstcla>TRUEif>the parse waslsuccessful, Tswe=swf.colstcla>FALSEit was not successful, odlif>sbswamtion> yoaaller>with

    Ixml-get-error-code">secame=swf.fnstallatxml_get_error_code(tion>

    Ixml-error-string">secame=swf.fnstallatxml_error_otricl(tion>

    Ixml-get-current-line-number">secame=swf.installatxml_get_current_line_number(tion>

    Ixml-get-current-column-number">secame=swf.installatxml_get_current_column_number(tion>


    Ixml-get-current-byte-indlx">secame=swf.installatxml_get_current_byte_indlx(tion> H1>Ixml- yoser-creaae-ns>llatxml_ yoser_creaae_nsllon> <

    (ass 4 >= 4.0.5)laP>xml_ yoser_creaae_nsd to dclass=se Creaae"an XML= yoserwla

    D/A>Inp

    resource< ( [stringsencoding [, stringssep]])

    TABLE c ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left> P>Estcla
    la
    H1>Ixml- yoser-creaae>llatxml_ yoser_creaaellon> <

    (ass 3>= 3.0.6, ass 4 )laP>xml_ yoser_creaaed to dclass=secreaae"an XML= yoserla

    D/A>Inp

    resource< ( [strings encoding])

    L>laçãoDT>al)laçãoDD> "çeP>Whichçcharaclersencoding the parser shouldBuse.nThe iollowingscharaclers "çencodings arelsupporsed: çãoP> ãçãlTBODY>laçãçãlTR>laçãçã"çoTD>ISO-8859-1çãTTa (default)laTD>laçãçãlTR>laçãçã"çoTD>US-ASCIIçãTT>laTD>laçãçãlTR>laçãçã"çoTD>UTF-8çãTTalaTD>ioçãoP>lala
    This installa creaaeslan XML=parser andFALSEla
    H1>Ixml- yoser-free>llatxml_ yoser_freellon> <

    (ass 3>= 3.0.6, ass 4 )laP>xml_ yoser_freed to dclass=seFree an XML= yoserla

    D/A>Inp

    bool ( resource< yoser)

    L>laçãoDT> "çeP>Açrseerence to thb XML= yoser to free. =Onclala
    P>ThisFALSEsbswamtion> yoaaller>TRUE H1>Ixml- yoser-get-op>llatxml_ yoser_get_opllon> <

    (ass 3>= 3.0.6, ass 4 )laP>xml_ yoser_get_opd to dclass=seget ops fromBan XML= yoserla

    D/A>Inp

    mixed>llB> ( resource< yoser, ila op)

    L>laçãoDT> "çeP>Açrseerence to thb XML= yoser to get an op from. =OnclaçãoDT>lllaçãTTalaçãoDD> "çeP>Whichçop to fetch.wSee

    Ixml- yoser-set-op">(tion>

    ops.w

    lala
    P>ThisFALSEsbswamtion> yoaaller>the laop couldBnot be set. Else the op's value is returned. =Onc sessSee

    Ixml- yoser-set-op">(tion>

    ops.w

    la
    H1>Ixml- yoser-set-op>llatxml_ yoser_set_opllon> <

    (ass 3>= 3.0.6, ass 4 )laP>xml_ yoser_set_opd to dclass=seset ops in an XML= yoserla

    D/A>Inp

    bool llB> ( resource< yoser, ila op, mixed>value)

    L>laçãoDT> "çeP>Açrseerence to thb XML= yoser to set an op in. =OnclaçãoDT>lllaçãTTalaçãoDD> "çeP>Whichçop to set. See below. =OnclaçãoDT> "çeP>The op's new value. =Onclala
    P>ThisFALSEsbswamtion> yoaaller>the laop couldBnot be set. Else the op is setTRUEs arelavailable:

    Tabela 1. XML= yoser ops ãoTHEAD> "çeTR>laçãçãoTH vAlign=clntbr align=left>Op colstclalaçãçãoTH vAlign=clntbr align=left>DatalaçãçãoTH vAlign=clntbr align=left>D/A>Inp "çeTBODY>laçãoTR>laçãçãoTD vAlign=clntbr align=left>XML_OPTION_CASE_FOLDINGlaçãçãoTD vAlign=clntbr align=left>ietegerlaTD>laçãçãoTD vAlign=clntbr align=left>Controlsswhel er

    case-iolding

    laçãoTR>laçãçãoTD vAlign=clntbr align=left>XML_OPTION_TARGET_ENCODINGlaçãçãoTD vAlign=clntbr align=left>otriclllTD>laçãçãoTD vAlign=clntbr align=left>Setsswhichç

    targets ="""""encoding to useis set to thb sames ="""""as=the sourceby

    Ixml- yoser-creaae">ISO-8859-1çãTTa,çUS-ASCIIçãTT>UTF-8çãTTa. =OTD>la
    la
    H1>Ixml-set-characler-data-handler>llatxml_set_characler_data_handlerllon> <

    (ass 3>= 3.0.6, ass 4 )laP>xml_set_characler_data_handlerd to dclass=seset up characlersdata

    D/A>Inp

    bool ( resource
    yoaaller>awinstalla thas must=exiss whbn

    Ixml- yose">

    yoaaller>by ( resource< yoser, stringsdata)

    L>laçãoDT> "çeP>The iirst yoaaller,ç "çeP>The ctiond yoaaller,çla
    P>If aFALSElbswe=swf.colstcla>TRUEif>the handlerFALSEsbswtion> yoaaller>

    BLOCKQUOTE1 classnote> ãoP>Nota: la
    la
    H1>Ixml-set-default-handler>llatxml_set_default_handlerllon> <

    (ass 3>= 3.0.6, ass 4 )laP>xml_set_default_handlerd to dclass=seset up amd/fault

    D/A>Inp

    bool ( resource< yoser, stringshandler)

    yoaaller>awinstalla thas must=exiss whbn

    Ixml- yose">

    yoaaller>by ( resource< yoser, stringsdata)

    L>laçãoDT> "çeP>The iirst yoaaller,ç "çeP>The ctiond yoaaller,çla
    P>If aFALSElbswe=swf.colstcla>TRUEif>the handlerFALSEsbswtion> yoaaller>

    BLOCKQUOTE1 classnote> ãoP>Nota: la
    la
    H1>Ixml-set-eleclas-handler>llatxml_set_eleclas_handlerllon> <

    (ass 3>= 3.0.6, ass 4 )laP>xml_set_eleclas_handlerd to dclass=seset up amstcrt"and>end>eleclas handlersla

    D/A>Inp

    bool ( resource< yoser, stringsstcrt_eleclas_handler, strings end_eleclas_handler)

    yoaaller> yoaaller>installas thas must=exiss whbn

    Ixml- yose">

    yoaaller>by replaceable> ( resource< yoser, stringsu ne, arrayçattribs)

    L>laçãoDT> "çeP>The iirst yoaaller,ç "çeP>The ctiond yoaaller,çthe eleclas forwwhichçthis handlercase-iolding

    "çeP>The third yoaaller,çwith the eleclas'sçattribuaesl(if>any).nThe keys of>this arrayçarelthe attribuae u nes, the valuescase-iolded

    InlerianotThe original nrdOn of>the attribuaesl ae beby walkingsthroughl=sçãobswe=swf. yoaaller>was=the iirst attribuae,=andla
    P>The installa named>by replaceable> ( resource< yoser, strings u ne)

    L>laçãoDT> "çeP>The iirst yoaaller,ç "çeP>The ctiond yoaaller,çthe eleclas forwwhichçthis handlercase-iolding

    la
    P>If aFALSElbswe=swf.colstcla>TRUEif>the handlers arelset up,l Tswe=swf.colstcla>FALSEsbswtion> yoaaller>

    BLOCKQUOTE1 classnote> ãoP>Nota: la
    la
    H1>Ixml-set-end-namespace-dec -handler>llatxml_set_end_namespace_dec _handlerllon> <

    (ass 4 >= 4.0.5)laP>xml_set_end_namespace_dec _handlerd to dclass=se Set up characlersdata

    D/A>Inp

    bool ( resource< ind, strings hdl)

    TABLE c ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left> P>Estcla

    BLOCKQUOTE1 classnote> ãoP>Nota: la
    la
    H1>Ixml-set-external-easity-rse-handler>llatxml_set_external_lasity_rse_handlerllon> <

    (ass 3>= 3.0.6, ass 4 la)çãPtxml_set_external_lasity_rse_handlerd to dclass=seset up external lasityã reeerence handlerll

    D/A>Inp

    bool ( resource< yoser, stringshandler)

    yoaaller>awinstalla thas must=exiss whbn

    Ixml- yose">

    yoaaller>by fromB the handlerFALSEnosamvalue is returned),lthb XML= yoserwwill stop= yosingland

    Ixml-get-error-code">secame=swf.fnstallatxml_get_error_code(tion> systemitem>XML_ERROR_EXTERNAL_ENTITY_HANDLING ( resource< yoser, stringsopen_lasity_u nes, stringsbase, stringssystem_id, strings public_id)

    L>laçãoDT> "çeP>The iirst yoaaller,ç "çeP>The ctiond yoaaller,çthb u nes of>the easities thas arelopen fodlthb yose of>this lasityã(includinglthb u ne of>thb rseerenced lasity).nlanc=sçãoDT> "çeP>Thisthe external lasity. Currently this yoaallerwwill always "çeP>The iourth yoaaller,çie=the lasityãdec raolla.nlanc=sçãoDT> "çeP>The iifth yoaaller,çie=the lasityãdec raolla, odlan empty string "çif>none waslspecified;=the whitespace>ie=the public idlasifier will have"beenw ""uormslizedlas required>by>the XML=spec. =Onclala
    P>If aFALSElbswe=swf.colstcla>TRUEif>the handlerFALSEsbswtion> yoaaller>

    BLOCKQUOTE1 classnote> ãoP>Nota: la
    la
    H1>Ixml-set-notaolla-dec -handler>llatxml_set_notaolla_dec _handlerllon> <

    (ass 3>= 3.0.6, ass 4 )laP>xml_set_notaolla_dec _handlerd to dclass=seset up notaollaãdec raolla handlerll

    D/A>Inp

    bool ( resource< yoser, stringshandler)

    yoaaller>awinstalla thas must=exiss whbn

    Ixml- yose">

    yoaaller>thb dH1 clas's DTD and has=the iollowings formas: TABLE cellPadding=5 bgColor=#e0e0e0 bnrdOn=0> ãeTBODY>laçãoTR>laçãçãoTD>
    <!NOTATION
         See 
    
    A"u need to dclwww.w3.org/TR/1998/REC-xml-19980210#Notaollas" 
    target=_top>sec 4.7 of>thb XML=1.0=spec

    of>notaollaãamd/c raollas. lOnc sessThe installa named>by replaceable> ( resource< yoser, strings notaolla_u ne, stringsbase, stringssystem_id, stringspublic_id)

    L>laçãoDT> "çeP>The iirst yoaaller,ç "çeP>ThisInbedlabove.nlanc=sçãoDT> "çeP>Thisthe notaollaãdec raolla. Currently am"çthis yoaallerwwill always "çeP>System idlasifier of>the external notaollaãdec raolla. lanc=sçãoDT> "çeP>Public idlasifier of>the external notaollaãdec raolla. lanclala
    P>If aFALSElbswe=swf.colstcla>TRUEif>the handlerFALSEsbswtion> yoaaller>

    BLOCKQUOTE1 classnote> ãoP>Nota: la
    la
    H1>Ixml-set-objtio>llatxml_set_objtiollon> <

    (ass 4 )laP>xml_set_objtiod to dclass=seUse XML=Pyoserwwithin an objtioll

    llatio

    D/A>Inp

    void> ( resource< yoser, objtio objtio)

    yoaaller> yoaaller>installas couldBbe set with

    Ixml-set-eleclas-handler">

    to be methods of>sbswtion> yoaaller> TABLE cellPadding=5 bgColor=#e0e0e0 bnrdOn=0> ãeTBODY>laçãoTR>laçãçãoTD>
    <?pcclas xmlla
    $xml_ yoser = new xml();
    $xml_ yoser-> yose("<A ID='hallo'>tio</A>");la?>çãPREclaTD>la
    H1>
    Ixml-set-processing-iestruct/A>-handler>llatxml_set_processing_iestruct/A>_handlerllon> <

    (ass 3>= 3.0.6, ass 4 la)çãPtxml_set_processing_iestruct/A>_handlerd to dclass=se Set up processing instruct/A> (PI)

    D/A>Inp

    bool _handlerllB> ( resource< yoser, stringshandler)

    (PI) yoaaller>awinstalla thas must=exiss whbn

    Ixml- yose">

    yoaaller> has=the iollowingsformas:

    TABLE cellPadding=5 bgColor=#e0e0e0 bnrdOn=0> ãeTBODY>laçãoTR>laçãçãoTD>
    <?laçãçã"çãio

    la
    Youl ae put ass code into such>awtag,=but be awarelof one limitsalla: in an XML=PI, the PI end tag (sbswe=swf.literal>?>çãTTa) ae not be quoted, soçthis characlerssequence shouldBnot appear>ie=the ass code you embedlwith PIsthb ass code, as well as=the "real" PI end tag, will be treaaedlas characlersdata. P>The installa named>by replaceable> ( resource< yoser, stringstarget, stringsdata)

    L>laçãoDT> "çeP>The iirst yoaaller,ç "çeP>The ctiond yoaaller,ç "çeP>The third yoaaller,çla
    P>If aFALSElbswe=swf.colstcla>TRUEif>the handlerFALSEsbswtion> yoaaller>

    BLOCKQUOTE1 classnote> ãoP>Nota: la
    la
    H1>
    Ixml-set-stcrt-namespace-dec -handler>llatxml_set_stcrt_namespace_dec _handlerllon> <

    (ass 4 >= 4.0.5)laP>xml_set_stcrt_namespace_dec _handlerd to dclass=se Set up characlersdata

    D/A>Inp

    bool ( resource< ind, stringshdl)

    TABLE c ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left> P>Estcla

    BLOCKQUOTE1 classnote> ãoP>Nota: la
    la
    H1>Ixml-set-un yosed-easity-dec -handler>llatxml_set_un yosed_lasity_dec _handlerllon> <

    (ass 3>= 3.0.6, ass 4 la)çãPtxml_set_un yosed_lasity_dec _handlerd to dclass=se Set up un yosed lasityã dec raolla handlerwla

    D/A>Inp

    bool ( resource< yoser, stringshandler)

    yoaaller>awinstalla thas must=exiss whbn

    Ixml- yose">

    yoaaller> ãeTBODY>laçãoTR>laçãçãoTD>
    <!ENTITY lbswe=swf. yoaaller>laP>
    sec 4.2.2 of>thb XML=1.0=spec

    of>notaollaãamd/c red lxternal lasities. lOnc sessThe installa named>by ( resource< yoser, stringseasity_u ne, stringsbase, stringssystem_id, strings public_id, stringsuotaolla_u ne)

    L>laçãoDT> "çeP>The iirst yoaaller,ç "çeP>The u ne of>the lasityãthas is about>to be defined.nlanc=sçãoDT> "çeP>Thisthe external lasity. Currently this yoaallerwwill always "çeP>System idlasifier fodlthb external lasity. lanc=sçãoDT> "çeP>Public idlasifier fodlthb external lasity. lanc=sçãoDT> "çeP>N ne of>the notaollaãof>this lasityã(see

    Ixml-set-notaolla-dec -handler">la
    P>If aFALSElbswe=swf.colstcla>TRUEif>the handlerFALSEsbswtion> yoaaller>

    BLOCKQUOTE1 classnote> ãoP>Nota: la
    la
    la

    llatiol

    ioCVIII. XML-RPC>installasllon> <

    llatio<

    >io>llatIetrodução

    These installasl ae beto wInle XML-RPC>servbrs and1 cilass. Youl ae find1more informaslla about>XML-RPC>as to dclwww.xmlrpc=com/llat,=and to dclxmlrpc-epi.sourceforge.net/llat.

    TABLE c ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left> P>EsteEXPERIMENTALlalaçãSPAN1. Isso quer dizer que o comporsaclaso nesteseusBnomes, e>TUDO mais que está=dH1 clasado sobre esseuserisco.=OnclaTD>la
    la

    >io
    laio>
    llatRequisitos

    Nenhuma biblioteca externa é necessária< yoa compilarwessa extensão.=Oncla


    >io
    laio>
    >

    XML-RPC>supporsto use the Tswe=swf.op>--with-xmlrpc[=DIR]çãTTa olfiguraolla op whbn compilings ass to enable XML-RPC>suppors. This extensllaãis bundled into ass as of>4.1.0.w

    la

    >io
    laio>

    O comporsaclaso dessas insções podem sersmodificado pelas olfigurações do Tswe=swf.fileu nee>Tabela 1. XML-RPC> olfiguraolla ops ãoTHEAD> "çeTR>laçãçãoTH vAlign=clntbr align=left>N nelaçãçãoTH vAlign=clntbr align=left>D/faultlaçãçãoTH vAlign=clntbr align=left>Changeable "çeTBODY>laçãoTR>laçãçãoTD vAlign=clntbr align=left>xmlrpc_errorslaçãçãoTD vAlign=clntbr align=left>"0"laçãçãoTD vAlign=clntbr align=left>ass_INI_SYSTEMlaTD>laçãoTR>laçãçãoTD vAlign=clntbr align=left>xmlrpc_error_numberlaTD>laçãçãoTD vAlign=clntbr align=left>"0"laçãçãoTD vAlign=clntbr align=left>ass_INI_ALLlaTD>la


    Fors further details and1defini of>the Pss_INI_* colstclas see

    Iini-set">la

    >io
    laio>llatTipos Resource

    Estc

    >io
    laio>

    Estcla


    L>laçãoDT>ÍndicelaçãoDT>

    Ixmlrpc-decode-requess">xmlrpc_decode_requess

    Ixmlrpc-decode">xmlrpc_decode

    Ixmlrpc-encode-requess">xmlrpc_encode_requess

    Ixmlrpc-encode">xmlrpc_encode

    Ixmlrpc-get-type">xmlrpc_get_type

    Ixmlrpc- yose-method-d/A>Inps">xmlrpc_ yose_method_d/A>Inpsmethod d/A>InpslaçãoDT>

    Ixmlrpc-servbr-add-setrospec-data">xmlrpc_servbr_add_setrospec_data dH1 clasaollalaçãoDT>

    Ixmlrpc-servbr-call-method">xmlrpc_servbr_call_method

    Ixmlrpc-servbr-creaae">xmlrpc_servbr_creaae

    Ixmlrpc-servbr-d/Atroy">xmlrpc_servbr_d/Atroy

    Ixmlrpc-servbr-regissbr-setrospec-callback">xmlrpc_servbr_regissbr_setrospec_callback

    Ixmlrpc-servbr-regissbr-method">xmlrpc_servbr_regissbr_method

    Ixmlrpc-set-type">xmlrpc_set_typela
    la
    H1>Ixmlrpc-decode-requess>llatxmlrpc_decode_requess <

    (ass 4 >= 4.1.0)çãPtxmlrpc_decode_requessd to dclass=seDecodes XML=into native ass typesla

    D/A>Inp

    arrayç ( strings xml, stringsmethod [, stringseacoding])

    <

    TABLE c ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left> P>EstcEXPERIMENTALlalaçãSPAN1. Isso quer dizer que o comporsaclaso destcseuBnome, incluindo TUDO o que está= dH1 clasado aqui pode mudarwem inturas vbrsões do tio, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e>use risco.=OnclaTD>la
    sess

    TABLE c ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left> P>Estcla
    la
    H1>Ixmlrpc-decode>llatxmlrpc_decode <

    llatio

    (ass 4 >= 4.1.0)çãPtxmlrpc_decoded to dclass=seDecodes XML=into native ass typesla


    D/A>Inp

    arrayç ( stringsxml [, stringseacoding])

    <

    TABLE c ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left> P>EstcEXPERIMENTALlalaçãSPAN1. Isso quer dizer que o comporsaclaso destcseuBnome, incluindo TUDO o que está= dH1 clasado aqui pode mudarwem inturas vbrsões do tio, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e>use risco.=OnclaTD>la
    sess

    TABLE c ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left> P>Estcla
    la
    H1>Ixmlrpc-encode-requess>llatxmlrpc_encode_requess <

    (ass 4 >= 4.1.0)çãPtxmlrpc_encode_requessd to dclass=seGeneoases XML=fodla method requessla

    D/A>Inp

    strings ( stringsmethod, mixed yoaas)

    <

    TABLE c ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left> P>EstcEXPERIMENTALlalaçãSPAN1. Isso quer dizer que o comporsaclaso destcseuBnome, incluindo TUDO o que está= dH1 clasado aqui pode mudarwem inturas vbrsões do tio, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e>use risco.=OnclaTD>la
    sess

    TABLE c ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left> P>Estcla
    la
    H1>Ixmlrpc-encode>llatxmlrpc_encode <

    (ass 4 >= 4.1.0)çãPtxmlrpc_encoded to dclass=seGeneoases XML=fodla ass valuela

    D/A>Inp

    strings ( mixed value)

    <

    TABLE c ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left> P>EstcEXPERIMENTALlalaçãSPAN1. Isso quer dizer que o comporsaclaso destcseuBnome, incluindo TUDO o que está= dH1 clasado aqui pode mudarwem inturas vbrsões do tio, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e>use risco.=OnclaTD>la
    sess

    TABLE c ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left> P>Estcla
    la
    H1>Ixmlrpc-get-type>llatxmlrpc_get_type <

    llatio

    (ass 4 >= 4.1.0)çãPtxmlrpc_get_typed to dclass=seGets xmlrpc

    D/A>Inp

    strings ( mixed value)

    <

    TABLE c ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left> P>EstcEXPERIMENTALlalaçãSPAN1. Isso quer dizer que o comporsaclaso destcseuBnome, incluindo TUDO o que está= dH1 clasado aqui pode mudarwem inturas vbrsões do tio, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e>use risco.=OnclaTD>la
    sess

    TABLE c ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left> P>Estcla
    la
    H1>Ixmlrpc- yose-method-d/A>Inps>llatxmlrpc_ yose_method_d/A>Inps <

    llatio

    (ass 4 >= 4.1.0)çãPtxmlrpc_ yose_method_d/A>Inpsd to dclass=seDecodes XML=into asliss of>method d/A>Inpsla


    D/A>Inp

    arrayçInps ( stringsxml)

    <

    TABLE c ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left> P>EstcEXPERIMENTALlalaçãSPAN1. Isso quer dizer que o comporsaclaso destcseuBnome, incluindo TUDO o que está= dH1 clasado aqui pode mudarwem inturas vbrsões do tio, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e>use risco.=OnclaTD>la
    sess

    TABLE c ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left> P>Estcla
    la
    H1>Ixmlrpc-servbr-add-setrospec-data>llatxmlrpc_servbr_add_setrospec_data <

    llatio

    (ass 4 >= 4.1.0)çãPtxmlrpc_servbr_add_setrospec_datad to dclass=seAdds setrospec dH1 clasaollala


    D/A>Inp

    setç_data
    ( resource)

    <

    TABLE c ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left> P>EstcEXPERIMENTALlalaçãSPAN1. Isso quer dizer que o comporsaclaso destcseuBnome, incluindo TUDO o que está= dH1 clasado aqui pode mudarwem inturas vbrsões do tio, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e>use risco.=OnclaTD>la
    sess

    TABLE c ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left> P>Estcla
    la
    H1>Ixmlrpc-servbr-call-method>llatxmlrpc_servbr_call_method <

    (ass 4 >= 4.1.0)çãPtxmlrpc_servbr_call_methodd to dclass=sePyoses XML= requesss and1 all methodsla

    llatio

    D/A>Inp

    mixed ( resources])

    <

    TABLE c ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left> P>EstcEXPERIMENTALlalaçãSPAN1. Isso quer dizer que o comporsaclaso destcseuBnome, incluindo TUDO o que está= dH1 clasado aqui pode mudarwem inturas vbrsões do tio, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e>use risco.=OnclaTD>la
    sess

    TABLE c ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left> P>Estcla
    la
    H1>Ixmlrpc-servbr-creaae>llatxmlrpc_servbr_creaae <

    (ass 4 >= 4.1.0)çãPtxmlrpc_servbr_creaaed to dclass=seCreaaes an xmlrpc< servbrla

    D/A>Inp

    resource< ( void)

    <

    TABLE c ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left> P>EstcEXPERIMENTALlalaçãSPAN1. Isso quer dizer que o comporsaclaso destcseuBnome, incluindo TUDO o que está= dH1 clasado aqui pode mudarwem inturas vbrsões do tio, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e>use risco.=OnclaTD>la
    sess

    TABLE c ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left> P>Estcla
    la
    H1>Ixmlrpc-servbr-d/Atroy>llatxmlrpc_servbr_d/Atroy <

    llatio

    (ass 4 >= 4.1.0)çãPtxmlrpc_servbr_d/Atroyd to dclass=seDeAtroys servbr resourcesla


    D/A>Inp

    void> ( resource
    <

    TABLE c ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left> P>EstcEXPERIMENTALlalaçãSPAN1. Isso quer dizer que o comporsaclaso destcseuBnome, incluindo TUDO o que está= dH1 clasado aqui pode mudarwem inturas vbrsões do tio, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e>use risco.=OnclaTD>la
    sess

    TABLE c ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left> P>Estcla
    la
    H1>Ixmlrpc-servbr-regissbr-setrospec-callback>llatxmlrpc_servbr_regissbr_setrospec_callback <

    llatio

    (ass 4 >= 4.1.0)çãPtxmlrpc_servbr_regissbr_setrospec_callbackd to dclass=seRegissbr a ass ion> to geneoase dH1 clasaollala


    D/A>Inp

    bool _callback ( resource< servbr, stringsion>)

    <

    TABLE c ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left> P>EstcEXPERIMENTALlalaçãSPAN1. Isso quer dizer que o comporsaclaso destcseuBnome, incluindo TUDO o que está= dH1 clasado aqui pode mudarwem inturas vbrsões do tio, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e>use risco.=OnclaTD>la
    sess

    TABLE c ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left> P>Estcla
    la
    H1>Ixmlrpc-servbr-regissbr-method>llatxmlrpc_servbr_regissbr_method <

    (ass 4 >= 4.1.0)çãPtxmlrpc_servbr_regissbr_methodd to dclass=seRegissbr a ass ion> to resource

    D/A>Inp

    bool ( resource)

    <

    TABLE c ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left> P>EstcEXPERIMENTALlalaçãSPAN1. Isso quer dizer que o comporsaclaso destcseuBnome, incluindo TUDO o que está= dH1 clasado aqui pode mudarwem inturas vbrsões do tio, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e>use risco.=OnclaTD>la
    sess

    TABLE c ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left> P>Estcla
    la
    H1>Ixmlrpc-set-type>llatxmlrpc_set_type <

    (ass 4 >= 4.1.0)çãPtxmlrpc_set_typed to dclass=seSets xmlrpc

    D/A>Inp

    bool ( stringsvalue, stringstype)

    <

    TABLE c ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left> P>EstcEXPERIMENTALlalaçãSPAN1. Isso quer dizer que o comporsaclaso destcseuBnome, incluindo TUDO o que está= dH1 clasado aqui pode mudarwem inturas vbrsões do tio, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e>use risco.=OnclaTD>la
    sess

    TABLE c ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left> P>Estcla
    la
    la

    ioCIX. XSLTsion>sllon> <

    >io>llatIetrodução

    This ass extensllaãprovides a processoras the laXalanslibraryãodlthb libxsltslibrary. lOnc sessXSLTs(Extenslble Stylesheet Language (XSL) Transformasllas)XSLTsand1related technologiesl ae be to dclwww.w3.org/TR/xsltllat.

    BLOCKQUOTE1 classnote> ãoP>Nota: ass priodlto ass 4.1, currently only the new XSLTs extensllaãin ass 4.1supporslaBLOCKQUOTE>la
    la

    >io
    laio>
    llatRequisitos

    This extensllaãuses roductu neeexpatçãSPAN1, which> ae both be to dclwww.gingerall=com/llat. Binaries arelprovided as well as source.

    la

    >io
    laio>
    >

    On UNIX, run olfigure with the >--enable-xsltllTTa Tswe=swf.op>--with-xslt-sablotllTTa opsllas. The somewhere your compiler> ae find1it. lOnc sessMake sure you have=the same libraries linked>to the roductu neeSablotronçãSPAN1slibraryãas those, which>arellinked>with PHP. The olfiguraolla ops: Tswe=swf.op>--with-expat-dir=DIRllTTa Tswame=swf.op>--with-i olv-dir=DIRllTTa arelthere to help you specify them. Whbn askingsior suppors, alwaysthose libraries installed>on your system somewhere. Naturally,s provide all the vbrslla numbers.

    BLOCKQUOTE1 classnote> ãoP>JavaS>Inp< E-XSLTssuppors: Inp< suppors, you must=specify am 1thb op: Tswe=swf.op>--with-sablot-js=DIRllTTa.

    laBLOCKQUOTE>la

    BLOCKQUOTE1 classnote> ãoP>Note to Win32 Users: sablot.dlllalaçãSPAN1 fromsthe DLL=foldOn of>the Pss/Win32 binary package to the SYSTEM32 foldOn of>your windows machine. (Ex: C:\WINNT\SYSTEM32 or C:\WINDOWS\SYSTEM32)

    laBLOCKQUOTE>la
    la

    >io
    laio>

    Estcla


    >io
    laio>
    llatTipos Resource

    Estc

    >io
    laio>

    As< olaalaes abaixo são definiHR> por estcl/P>

    L>laçãoDT>XSLT_OPT_SILENTseteger "çeP>Drop all logging and1error reporsing.nThis fodlall backends thas mayBbe added in the inture. lanc=sçãoDT>XSLT_SABOPT_PARSE_PUBLIC_ENTITIESseteger "çeP>Tell off. lanc=sçãoDT>XSLT_SABOPT_DISABLE_ADDING_METAseteger "çeP>Do not add the meta tag "Colaent-Type" fodlHTML=output. The default is set am 1durings ompilaolla of XSLT_SABOPT_DISABLE_STRIPPINGseteger "çeP>Suppress the whitespace strippings(A> data files only). lanc=sçãoDT>XSLT_SABOPT_IGNORE_DOC_NOT_FOUNDseteger "çeP>ColsidOn unresolved>dH1 class=(the dH1 clas()sion>) non-lethal. lanc=sçãoDT>XSLT_ERR_UNSUPPORTED_SCHEMEseteger "çeP>Error return code,=fodl

    Ixslt-set-scheme-handlers">schemes ="uandlersllat.

    la
    la
    la

    L>laçãoDT>ÍndicelaçãoDT>

    Ixslt-creaae">xslt_creaae

    Ixslt-errno">xslt_errno

    Ixslt-error">xslt_error

    Ixslt-free">xslt_free

    Ixslt-process">xslt_process

    Ixslt-set-base">xslt_set_base

    Ixslt-set-eacoding">xslt_set_eacoding

    Ixslt-set-error-handler">xslt_set_error_handlerllatd to dclass=seSet am 1an error handlerwiodla XSLTsprocessorlaçãoDT>

    Ixslt-set-log">xslt_set_logto wInle log messages tolaçãoDT>

    Ixslt-set-sax-handler">xslt_set_sax_handlerllatd to dclass=seSet am 1SAX"uandlerswiodla XSLTsprocessorlaçãoDT>

    Ixslt-set-sax-handlers">xslt_set_sax_handlerswhbn the XML=dH1 clas gess=processed çãoDT>

    Ixslt-set-scheme-handler">xslt_set_scheme_handlerllatd to dclass=seSet am 1Schemesuandlerswiodla XSLTsprocessorlaçãoDT>

    Ixslt-set-scheme-handlers">xslt_set_scheme_handlersla
    la
    H1>Ixslt-creaae> <

    (ass 4 >= 4.0.3)çãPtxslt_creaaed to dclass=seCreaaesa new XSLTs processorla

    D/A>Inp

    resource< ( void)

    Creaaesand1return a new XSLTsprocessor resources.

    la
    H1>Ixslt-errno> <

    (ass 4 >= 4.0.3)çãPtxslt_errnod to dclass=seReturn a error numberla

    D/A>Inp

    setç ( resource< xh)

    Return an error code d/A>Inbingsthb last error thas occured>on thb yssed XSLTsprocessor.

    la
    H1>Ixslt-error> <

    (ass 4 >= 4.0.3)çãPtxslt_errord to dclass=seReturn a error stringla

    D/A>Inp

    mixed ( resource< xh)

    Return a stringsd/A>Inbingsthb last error thas occured>on thb yssed XSLTs processor. lOnc sess TABLE c laçãoTBODY>laçãoTR>laçãçãoTD>laçãçãçãoD

    Exemplo 1. Handlingserrors usingsthb exslt_error()ion>sand1

    Ixslt-errno">exslt_errno()ion>s. lanc=sçãçãçãoTABLE cellPadding=5 bgColor=#e0e0e0 bnrdOn=0>laçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    <?>laTD>la
    laTD>laP>la
    H1>
    Ixslt-free> <

    (ass 4 >= 4.0.3)çãPtxslt_freed to dclass=seFreesXSLTsprocessorla

    D/A>Inp

    void> ( resource< xh)

    Freesthe XSLTsprocessor idlasified by the givbn uandle.

    la
    H1>Ixslt-process> <

    (ass 4 >= 4.0.3)çãPtxslt_processd to dclass=sePerform an"XSLTs transformasllala

    llatio

    D/A>Inp

    mixed ( resource

    The<exslt_process()ion>sfon> is the crux of>the new XSLTs extenslla. Is allows you to erform an"XSLTstransformaslla usingsalmost anyinput source - the colaainbrs.nThisthrough the use arg clas bufeers -- a< olcept takbn fromsthe SablotronsXSLTsprocessor (currently the only XSLTsprocessor this extensllaãsupporss). The input colaainbrs default to cdH1 clas.nIf the result olaainbr is not specified - i.e. NULLlalaçãTTa - thae=the result is returned. lOnc sess

    TABLE c ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left> P>This hasBchaeged it's arg class, silcevbrslla 4.0.6. Do NOT laçãçãçãprovide the acte=ssxml odlxsl olalaswasB2nd snd 3rd arg clas,ãas this laçãçãçãwill reaaesa segclass fault, in Sablotronsvbrsllas upwto cnd laçãçãçãincluding<0.95.

    laTD>la

    Colaainbrs ae also be set viasthb $arg classlalaçãTTa arrayç(seesbelow). lOnc sessThe simplest type=of>transformaslla with the exslt_process()ion>sfon> is the transformaslla of>an"XML=file> with an"XSLTsfile, placingsthb result in a third file>colaaining>the new XML=(or HTML)>dH1 clas.nDoing>this with sablotronsis really qunle easy... lOnc seTABLE c laçãoTBODY>laçãoTR>laçãçãoTD>laçãçãçãoD

    Exemplo 1. Usingsthb exslt_process()ion>sto transform>an"XML=file>cnd a XSL file>to a new XML=filelanc=sçãçãçãoTABLE cellPadding=5 bgColor=#e0e0e0 bnrdOn=0>laçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    <?>by sampleIxsl=into resultIxml";laçãçãprint ", resultIxml hasBthe followings olalass\n<br>\n";laçãçãprint "<pre>\n";laçãçãreadfile('resultIxml');laçãçãprint "</pre>\n";la}laelse<{laçãçãprint "Sorry, sampleIxml couldBnot be transformed>by sampleIxsl=into";laçãçãprint "  resultIxml thb reasA> is that " . xslt_error($xh) . ">cnd thb ";laçãçãprint "error code is " . xslt_errno($xh);io}laioxslt_free($xh);lala?>lanRE>laTD>la
    laTD> sessWhile this fon>
    ality is greaa,lnamyyour results direcexslt_process()ion>s fon> (or provide a NULLsvalue iodlthe arg clas), it will automaslcally returnlthe value of>the XSLTstransformaslla, instead of>wInlingsitwto claçãoTBODY>laçãoTR>laçãçãoTD>laçãçãçãoD

    llatioçãçãçãoP>Exemplo 2. Usingsthb exslt_process()ion>sto transform>an"XML=file>cnd a XSL file>to a variable>colaaining>the resultinglXML=datalanc=sçãçãçãoTABLE cellPadding=5 bgColor=#e0e0e0 bnrdOn=0>laçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    <?>by sampleIxsl=into the \$result";laçãçãprint " variable, the \$result variable>hasBthe followings olalass\n<br>\n";laçãçãprint "<pre>\n";laçãçãprint $result;laçãçãprint "</pre>\n";la}laelse<{laçãçãprint "Sorry, sampleIxml couldBnot be transformed>by sampleIxsl=into";laçãçãprint "  the \$result variable>thb reasA> is that " . xslt_error($xh) . laçãçãprint " cnd thb error code is " . xslt_errno($xh);io}laioxslt_free($xh);lala?>lanRE>laTD>la
    laTD>lOnc sessThe above=two ases arelthe two simplest ases there arelwhbn it omes to XSLTstransformaslla cnd I'd1dare say that they arelthe most commla ases, howevbr, sometimes you get>your XML=cnd XSLTscode fromsexter>al sources, such>as a=database odla sockes.nIn these ases you'll have=the XML=cnd/odlXSLTsdata in a variable>-- and in productlla cppllca
    s=the overhead of>dumpingsthbse>to file> mayBbe too much.nThisfiles asBthe XML=cnd XSLTsarg class=to the exslt_process()ion>sfon>, you ae specify "arg clas place holdOns" which>arelthbn subsituaedlby values givbn in the arg class=arrayç(5th yoaaeter to the exslt_process()ion>sfon>). The followingsiois an example of>processinglXML=cnd XSLTsinto asresult variable>without>the use< of>files as all. lOnc sess TABLE c laçãoTBODY>laçãoTR>laçãçãoTD>laçãçãçãoD

    Exemplo 3. Usingsthb exslt_process()ion>sto transform>a variable>colaaining>XML=data>cnd a variable>colaaining>XSL data into a variable>colaaining>the resultinglXML=datalanc=sçãçãçãoTABLE cellPadding=5 bgColor=#e0e0e0 bnrdOn=0>laçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    <?>by sampleIxsl=into the \$result";laçãçãprint " variable, the \$result variable>hasBthe followings olalass\n<br>\n";laçãçãprint "<pre>\n";laçãçãprint $result;laçãçãprint "</pre>\n";la}laelse<{laçãçãprint "Sorry, sampleIxml couldBnot be transformed>by sampleIxsl=into";laçãçãprint "  the \$result variable>thb reasA> is that " . xslt_error($xh) . laçãçãprint " cnd thb error code is " . xslt_errno($xh);io}laxslt_free($xh);la?>lanRE>laTD>la
    laTD>lOnc sessFinally,sthb last arg clas to the
    exslt_process()ion>s fon> represlass=an=arrayçiodlamywithin your XSL files usingsthb <xsl: yoaa name=" yoaaeter_name"> instructlla. The yoaaeters must=be

    BLOCKQUOTE1 classnote> ãoP>Nota: file://lalaçãSPAN1 is needed in frons of>path if you use< Windows.

    laBLOCKQUOTE>la
    la
    H1>Ixslt-set-base> <

    llatio

    (ass 4 >= 4.0.5)çãPtxslt_set_based to dclass=seSet the base URI fodlall XSLTstransformasllasla


    D/A>Inp

    void> ( resource

    Sesssthe base URI fodlall XSLTstransformasllas,sthe base URI is used>with Xpath instructllas to resolve dH1 clas()scnd other commands which>access exter>al resources. Is is also used>to resolve URIswiodlthe <xsl:include> and <xsl:impors> eleclass. lOnc sessAs of>4.3,sthe default base URI is the directhe executinglA>Inp<.nIn effec<, it is the directhe Tswame=swf. olstcla>__FILE__

    BLOCKQUOTE1 classnote> ãoP>Nota: file://lalaçãSPAN1 is needed in frons of>path if you use< Windows.

    laBLOCKQUOTE>la
    la
    H1>Ixslt-set-eacoding> <

    (ass 4 >= 4.0.5)çãPtxslt_set_eacodingd to dclass=seSet the eacoding

    D/A>Inp

    void> ( resource< xh, stringseacoding)

    Ses the output eacoding is only available>whbn you compile Sablotronswith eacodingla


    H1>Ixslt-set-error-handler> <

    (ass 4 >= 4.0.4)çãPtxslt_set_error_handlerd to dclass=seSet an error handlerwiodla XSLTsprocessorla

    D/A>Inp

    void> ( resource

    Ses an error handlerwion> fodlthb XSLTsprocessor givbn by Tswame=swf. yoaaeter>xhlalaçãTTa, this fon> will be called>whbnevbr an error occurs in the XSLTstransformaslla (this fon> is also called>fodlnotices).w

    la
    H1>Ixslt-set-log> <

    (ass 4 >= 4.0.6)çãPtxslt_set_logd to dclass=seSet the log file>to wInle log messages tola

    D/A>Inp

    void> ( resource

    seP>l/P>

    L>laçãoDT>xhlalaçãTTalaçãoDD> "çeP>A reeerence to the XSLTs yoser. lOnc sçãoDT>log "çeP>This< yoaaeter is either a boolean value which>toggles logging la cnd off, laçãodla stringscolaaining>the logfile>in which>log errors too.

    la
    seP>l/P> P>This allows you to set the file>in which>you waaswXSLTslog messages to,wXSLTslog messages areldifeerentãthae=error messages, in that log messages arelnot acte=sly error messages but rather messages related to the stcte of>the XSLTsprocessor. They areluseful>fodldebugging XSLT,>whbn somethingsgoes wrong. lOnc sessBy default logging is disabled, in ordOn to enable logging you must=first all exslt_set_log()ion>swith a boolean yoaaeter which>enables logging,sthen if you waaswto set the log file>to debug to,wyou must=then pyss it a stringscolaaining>the fileu ne: TABLE c laçãoTBODY>laçãoTR>laçãçãoTD>laçãçãçãoD

    Exemplo 1. Usingsthb XSLTsLogging features lanc=sçãçãçãoTABLE cellPadding=5 bgColor=#e0e0e0 bnrdOn=0>laçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    <?>laTD>la
    laTD>laP>

    BLOCKQUOTE1 classnote> ãoP>Nota: file://lalaçãSPAN1 is needed in frons of>path if you use< Windows.

    laBLOCKQUOTE>la
    la
    H1>
    Ixslt-set-sax-handler> <

    (4.0.3 - 4.0.6 only)çãPtxslt_set_sax_handlerd to dclass=seSet SAX"uandlersw iodla XSLTsprocessorla

    D/A>Inp

    void> ( resource< xh, arrayçuandlers)

    Ses SAX"uandlerswoe=the resourcexhlalaçãTTa. SAX"uandlerswshouldBbe a two dimensllaal arrayç with the formas (all top levblçeleclass arelopal):

    lOnc seTABLE cellPadding=5 bgColor=#e0e0e0 bnrdOn=0>laçãoTBODY>laçãoTR>laçãçãoTD>
    array(la[dH1 clas] => laçãçãarray(laçãçãççççstcrt dH1 claswuandler,laçãçãççççend dH1 claswuandlerlaçãçã),la[eleclas] => laçãçãarray(laçãçãççççstcrt eleclaswuandler,laçãçãççççend eleclaswuandlerlaçãçã),la[namespace] => laçãçãarray(laçãçãççççstcrt namespacewuandler,laçãçãççççend namespacewuandlerlaçãçã),la[commlas] => commlaswuandler,la[pi] => processinglinstructllawuandler,la[chyoacter] => chyoacter data uandlerla)lanRE>laTD>iolP>lOncla
    seP>l/P>la
    H1>
    Ixslt-set-sax-handlers> <

    (ass 4 >= 4.0.6)çãPtxslt_set_sax_handlersd to dclass=se1Set the SAX" handlerswto be called>whbn the XML=dH1 clas gess=processed la

    llatio

    D/A>Inp

    void> ( resource

    TABLE c ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left> P>EstclaTD>la
    la
    H1>Ixslt-set-scheme-handler> <

    (4.0.5 - 4.0.6 only)çãPtxslt_set_scheme_handlerd to dclass=seSet Schemes handlerswiodla XSLTsprocessorla

    llatio

    D/A>Inp

    void> ( resource

    Ses Schemesuandlerswoe=the resourcexhlalaçãTTa. SchemesuandlerswshouldBbe an=arrayçwith the iodmas (all eleclass arelopal):

    lOnc seTABLE cellPadding=5 bgColor=#e0e0e0 bnrdOn=0>laçãoTBODY>laçãoTR>laçãçãoTD>
    array(la[ges_all] => get>all handler,la[open] => open handler,la[get] => get>uandler,la[put] => put uandler,la[close] => close uandlerla)lanRE>laTD>iolP>lOncla
    seP>l/P>la
    H1>
    Ixslt-set-scheme-handlers> <

    (ass 4 >= 4.0.6)çãPtxslt_set_scheme_handlersd to dclass=se1Set the schemes handlerswiodlthb XSLTsprocessor la

    D/A>Inp

    void> ( resource

    TABLE c ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left> P>EstclaTD>la
    la
    la

    ioCX. YAZsion>sllon> <

    >io>llatIetrodução

    This extensllaãofeers a ass interface to the roductu neeYAZçãSPAN1stoolkit thas impleclass=the Z39.50 Protocolthe omplexity of>Z39.50 so it shouldBbe fairly easy to use. Is supporssspbrslsalaswstcteless connectllas vbry similar to those< ofeered by the various RDB APIs that arelavailable>fodlPHP. This means that sessllas are stcteless but shyoed amongst users,sthus savingsthb connect cnd lainitializelSPAN1c ss to dclwww.indexdata.dk/yaz/llat. You ae find1news informaslla, example A>Inp to dclwww.indexdata.dk/>la


    >io
    laio>
    >

    Compile YAZs(ANSI/NISO>Z39.50 suppors) and install1it. BuildBass with your iavournle modules>cnd add op Tswe=swf.op>--with-yaz[=DIR]çãTTa. Your task is roughly the following: lOnc sess

    llatiolP>lOnc seTABLE cellPadding=5 bgColor=#e0e0e0 bnrdOn=0>laçãoTBODY>laçãoTR>laçãçãoTD>
    gunzip -claTD>iolP>lOncla
    seP>l/P>

    TABLE c ãoTBODY>laçãoTR>laçãçãoTD align=middle>AtençãolaçãoTR>laçãçãoTD align=left> P>The

    IMAPllats extensllaã aenot be used>in conju> with the

    recodellats or

    laTD>la
    la

    >io
    laio>

    O comporsaclaso dessasTabela 1. YAZscolfiguraolla opslanc=s TABLE c ãoTHEAD>laçãoTR>laçãçãoTH vAlign=cenaer align=left>NamelaTH>laçãçãoTH vAlign=cenaer align=left>DefaultlaTH>laçãçãoTH vAlign=cenaer align=left>ChaegeablelaTH>laçãoTBODY>laçãoTR>laçãçãoTD vAlign=cenaer align=left>yaz.max_linkslaTD>laçãçãoTD vAlign=cenaer align=left>"100"laTD>laçãçãoTD vAlign=cenaer align=left>tio_INI_ALLlaTD>laçãoTR>laçãçãoTD vAlign=cenaer align=left>yaz.log_filelaçãçãoTD vAlign=cenaer align=left>""laTD>laçãçãoTD vAlign=cenaer align=left>tio_INI_ALLlaTD>la


    Fodl further details>cnd definiolla of>the Pss_INI_* olstclas see

    Iini-set">eini_set()ion>lOncla
    se

    >io
    laio>

    Estc

    >io
    laio>

    Estc

    >io
    laio>

    tionYAZskelps track of>connectllas with targetsç(Z-Associasllas). A resource< represlass=a>connectlla>to a target. lOnc sess TABLE c laçãoTBODY>laçãoTR>laçãçãoTD>laçãçãçãoD

    llatioçãçãçãoP>Exemplo 1. ePyoallel searchinglusingsioçãçãçãYAZ()ion>lanc=sçãçãçãossThe s>Inp< below demolstraoes the yoallel searchinglfeature of>the çãçãçãAPI. Whbn invoked>with no arg class=itãprints=a>queryçiodm; else çãçãçã(arg class=are supplied) it searchesãthe targetsças givbn in arrayç Tswamçãçãçãe=swf.lnleoal>hostçãTTa. lOnc sçãçãçãoTABLE cellPadding=5 bgColor=#e0e0e0 bnrdOn=0>laçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    $num_hosts===count ($host);ioif (empty($leom) ||=count($host) == 0) {laçãçãecho '<form>method="get">laçãçã<input type="checkbox"laçãçãname="host[]" value="bagel.indexdata.dk/gils">laçãçãããããGILS oestlaçãçã<input type="checkbox"laçãçãname="host[]" value="localhost:9999/Default">laçãçãããããlocal oestlaçãçã<input type="checkbox" checked="1"laçãçãname="host[]" value="z3950.loc.gov:7090/voyager">laçãçãããããLibraryãof Colgresslaçãçã<br>laçãçãRPN Query:laçãçã<input type="text" size="30"ãname="leom">laçãçã<input type="submit"ãname="a>" value="Search">laçãçã';çãçããããã
    } else<{laçãçãecho 'You searced>fodl' . allaspecialchyos($leom) . '<br>';laçãçãfodl($i===0; $i=< $num_hosts; $i++) {laçãçããããã$id[]===yaz_connect($host[$i]);laçãçãããããyaz_raege($id[$i], 1, 10);laçãçãããããyaz_search($id[$i],"rpn",$leom);laçãçã}laçãçãyaz_wait();laçãçãfodl($i===0; $i=< $num_hosts; $i++) {laçãçãããããecho '<hr>' . $host[$i] . ":";laçãçããããã$error ==yaz_error($id[$i]);laçãçãããããif (!empty($error)) {laçãçãããããããããecho "Error:ã$error";laçãçããããã} else<{laçãçãçãçããããã$hits===yaz_hits($id[$i]);laçãçãããããããããecho "Result Count $hits";laçãçããããã}laçãçãããããecho '<dl>';laçãçãããããfodl($p===1; $p=<==10; $p++) {laçãçããããããããã$rec===yaz_record($id[$i],$p,"string");laçãçãããããããããif (empty($rec)) colainue;laçãçãããããããããecho "<ds><b>$p</b></ds><dd>";laçãçãããããããããecho ereg_replace("\n", "<br>\n",$rec);laçãçãããããããããecho "</dd>";laçãçããããã}laçãçãããããecho '</dl>';laçãçã}la}lanRE>laTD>la
    laTD>laP>la
    la

    L>laçãoDT>ÍndicelaçãoDT>

    Iyaz-addinfo">yaz_addinfollatd to dclass=seReturns laçãaddial error informasllalaçãoDT>

    Iyaz-ccl-colf">yaz_ccl_confllatd to dclass=seColfigure ="CCLs yoserlaçãoDT>

    Iyaz-ccl- yose">yaz_ccl_ yosellatd to dclass=seInvoke ="CCLsPyoserlaçãoDT>

    Iyaz-close">yaz_closellatd to dclass=seClose çãYAZscolnectllalaçãoDT>

    Iyaz-colnect">yaz_colnectllatd to dclass=ses ="Pre yoeswiodla connectlla>to a Z39.50 targetç(servbr). laçãoDT>

    Iyaz-database">yaz_databasellatd to dclass=ses ="Specifies the databases>within a sesslla laçãoDT>

    Iyaz-eleclas">yaz_eleclasllatd to dclass=ses ="Specifies Eleclas-Set Namewiodlretrieval laçãoDT>

    Iyaz-errno">yaz_errno

    Iyaz-error">yaz_errorInplaçãoDT>

    Iyaz-get-op">yaz_ges_opop fodlcolnectllalaçãoDT>

    Iyaz-hits">yaz_hitshits=fodllast searchlaçãoDT>

    Iyaz-nlemnrdOn">yaz_nlemnrdOnllatd to dclass=ses ="Pre yoeswiodlZ39.50 Ilem OrdOn with an"ILL-Request package laçãoDT>

    Iyaz-preslas">yaz_preslasllatd to dclass=ses ="Pre yoeswiodlretrieval (Z39.50 preslas). laçãoDT>

    Iyaz-raege">yaz_raegellatd to dclass=ses ="Specifies the maximum number of>records to retrieve laçãoDT>

    Iyaz-record">yaz_recordllatd to dclass=seReturns laçãa>recordlaçãoDT>

    Iyaz-s ae-result">yaz_s ae_resultllatd to dclass=seReturns laçãS ae Response resultlaçãoDT>

    Iyaz-s ae">yaz_s aellatd to dclass=sePre yoesw ="iodla s aelaçãoDT>

    Iyaz-s hema">yaz_s hemallatd to dclass=ses ="Specifies s hemawiodlretrieval. laçãoDT>

    Iyaz-search">yaz_searchllatd to dclass=sePre yoesw ="iodla searchlaçãoDT>

    Iyaz-set-op">yaz_ses_ops fodlcolnectllalaçãoDT>

    Iyaz-sort">yaz_sort

    Iyaz-sylaax">yaz_sylaaxllatd to dclass=ses ="Specifies the p neerred>record sylaaxwiodlretrieval. laçãoDT>

    Iyaz-wait">yaz_waitllatd to dclass=seWaitw ="iodlZ39.50 requests to ompleaela
    la
    H1>Iyaz-addinfo>llatyaz_addinfollon> <

    (ass 4 >= 4.0.1)çãPtyaz_addinfod to dclass=seReturns addial error lainformasllala

    llatio

    D/A>Inp

    strings ( resource< id)

    Returns addial error messagewiodltargetç(last request). An empty stringsiois returnedãif last operaolla was a success or if no addial informaslla was provided by the target. lOncla


    H1>Iyaz-ccl-colf>llatyaz_ccl_confllon> <

    llatio

    (ass 4 >= 4.0.5)çãPtyaz_ccl_confd to dclass=seColfigure CCLs yoserla


    llatio

    D/A>Inp

    int ( resource

    This colfigures the CCLsqueryç yoser"iodla targetçwith definiollas of>access points=(CCLsqualifiers)


    Iyaz-ccl- yose">eyaz_ccl_ yose()ion>. Each index of>the arrayç Tswamc

    yoaaeter>colfiglalaçãTTa is the u ne of>a CCLsfield cnd thbwamcorrespondingattribute-type,>attribute-value pairs.nAttribute-type cnd laattribute-value is se>yoaaedlby ae equal sign ( Tswe=swf.lnleoal>=çãTTa). Each yir is se>yoaaedlby whnle space. lOnc sess TABLE c laçãoTBODY>laçãoTR>laçãçãoTD>laçãçãçãoD

    Exemplo 1. CCLscolfiguraollalanc=sçãçãçãossIn the example below, the CCLs yoser"is configured to suppors threesCCLs=sçãçãçãfields: Tswe=swf.lnleoal>tiçãTTa, Tswe=swf.lnleoal>auçãTTa cnd Tswamçãçãçãe=swf.lnleoal>isbnçãTTa. Each field is mapped to their BIB-1 equivalela. amçãçãçãIs is assumed>thas variable> Tswe=swf.lnleoal>$idçãTTa is the connectlla>amçãçãçãID. lOnc sçãçãçãoTABLE cellPadding=5 bgColor=#e0e0e0 bnrdOn=0>laçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    rogoaalissing>$fields["ti"]==="1=4";la$fields["au"]==="1=1";la$fields["isbn"]==="1=7";layaz_ccl_conf($id,$fields);lanRE>laTD>la
    laTD>laP>la
    H1>
    Iyaz-ccl- yose>llatyaz_ccl_ yosellon> <

    (ass 4 >= 4.0.5)çãPtyaz_ccl_ yosed to dclass=seInvoke CCLsPyoserla

    D/A>Inp

    int ( resource

    This invokes>a CCLs yoser. It olverts=a>givbn CCLsFINDsqueryçtoãaa>amRPN queryçwhich>mayBbe yssed to the


    Iyaz-search">eyaz_search()ion> to erform a search. To define"as set of>valid CCLsfields all

    Iyaz-ccl-colf">eyaz_ccl_conf()ion>.nIf the supplied Tswe=swf.>yoaaeter>querylalaçãTTa was successfusly olverted to RPN, this fon> returns Tswe=swf. olstcla>TRUErpnçãTTa of>the supplied arrayç Tswamc

    yoaaeter>resultlllaçãTTa holdsla valid RPN query.nIf the queryçcouldB not be olverted (becauseinvalid sylaax, unknownsfield, etc.) this fon> returns Tswe=swf. olstcla>FALSEfailure: Tswamc errorcodellTTaCCLserror code (integer), Tswamc errorstringlaTTaCCLserror string, cnd Tswamc errorpo>i in queryçof>failure (integer is chyoacter po>i). lOnc seTABLE c laçãoTBODY>laçãoTR>laçãçãoTD>laçãçãçãoD

    Exemplo 1. CCLsPyosinglanc=sçãçãçãossWe'll tryçtoãsearchlusingsCCL.nIn the example below, Tswamçãçãçãe=swf.lnleoal>$cclçãTTa is a CCLsquery. lOnc sçãçãçãoTABLE cellPadding=5 bgColor=#e0e0e0 bnrdOn=0>laçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    rogoaalissing>yaz_ccl_conf($id,$fields);  // see example iodlyaz_ccl_confioif (!yaz_ccl_ yose($id, $ccl,ç&$cclresult) {laçãçãecho 'Error:ã' . $cclresult["errorstring"];
    } else<{laçãçã$rpn===$cclresult["rpn"];laçãçãyaz_search($id,"rpn",$rpn);io}lanRE>laTD>la
    laTD>la
    H1>
    Iyaz-close>llatyaz_closellon> <

    (ass 4 >= 4.0.1)çãPtyaz_closed to dclass=seClose YAZscolnectllala

    D/A>Inp

    int ( resource

    Closes connectlla givbn by Tswc

    yoaaeter>idçãlaçãTTa. The Tswamc

    yoaaeter>idçãlaçãTTa is a connectlla resource

    Iyaz-colnect">eyaz_connect()ion> H1>Iyaz-connect>llatyaz_colnectllon> <

    (ass 4 >= 4.0.1)çãPtyaz_colnectd to dclass=sesPre yoeswiodla connectlla>to a Z39.50 targetç(servbr). la

    D/A>Inp

    resource< ( stringszurl la[, mixed ops])

    This fon> returns a connectlla resourcelB1e=swf.fon>eyaz_connect()ion> p n yoeswiodla connectlla>to a Z39.50 target. The Tswc

    yoaaeter>zurlçãlaçãTTa arg clas takesBthe form host[:pors][/database].nIf pors is omitted 210 is used.nIf database is omitted Tswe=swf.lnleoal>DefaultlaTTa is used. This is non-blockingland ladoesn't>attempt to establish a sockes - it merely p n yoeswa connectwto be erformed later whbn

    Iyaz-wait">eyaz_wait()ion>If the second arg clas,ã Tswc

    yoaaeter>ops=strings(OpenAuth).nlanc=seP>If Tswc

    yoaaeter>opsthe arrayçservbsças ops. Note that arrayçops arelonly supporsed>fodl ass 4.1.0land later. lP>lOnc

    P>lB1e=swf.fon>eyaz_connect()ion> opslanc=s L>laçãoDT>userlaçãoDD> "çeP>Useraamewiodlauthbntlca. lOnc sçãoDT>grouplaçãoDD> "çeP>Groupwiodlauthbntlca. lOnc sçãoDT> ysswordlaçãoDD> "çeP>Pysswordwiodlauthbntlca. lOnc sçãoDT>cookielaçãoDD> "çeP>Cookiewiodlsesslla (YAZsproxy). lOnc sçãoDT> roxylaçãoDD> "çeP>Proxy fodlcolnectlla (YAZsproxy). lOnc sçãoDT> brslsalaslaçãoDD> "çeP>A boolean.nIf Tswe=swf. olstcla>TRUEisç =" brslsalas;nIf Tswe=swf. olstcla>FALSEisçnot =" brslsalas. By default connectllas arel brslsalas. lOnc sçãoDT> iggybacklaçãoDD> "çeP>A boolean.nIf Tswe=swf. olstcla>TRUEfodl searches;nIf Tswe=swf. olstcla>FALSErecords. Howevbr, a few Z39.50 targetsçdoesn't>suppors iggyback odlthby ignnreleleclas set aames. Fodl those, iggyback shouldBbe disabled. lOnclala
    seP>l/P>

    BLOCKQUOTE1 classnote> ãoP>Nota: asproxythe free YAZ++laBLOCKQUOTE>la
    la
    H1>Iyaz-database>llatyaz_databasellon> <

    (ass 4 >= 4.0.6)çãPtyaz_databased to dclass=sesSpecifies the databases> within a sesslla la

    D/A>Inp

    int ( resource

    This fon> specifies one odlmnreldatabases>to be used>in search, retrieval, etc.w- overridingsdatabases specified>in call to


    Iyaz-colnect">eyaz_connect()ion>yoaaedlby a plus> sign Tswe=swf.lnleoal>+<ãTTa. lOnc sessThis allows you to usewithin a sesslla. lOnc sessReturns Tswe=swf. olstcla>TRUEFALSE H1>Iyaz-eleclas>llatyaz_eleclasllon> <

    (ass 4 >= 4.0.1)çãPtyaz_eleclasd to dclass=sesSpecifies Eleclas-Set Namew iodlretrieval la

    D/A>Inp

    int ( resource

    This sesssthe eleclas set aamewiodlretrieval. Call this fon> befnrel


    Iyaz-search">eyaz_search()ion>

    Iyaz-preslas">eyaz_preslas()ion>suppors Tswe=swf.lnleoal>FlaTTa (iodlfull records) cnd Tswe=swf.lnleoal>BlaTTa (iodlbrief>records).nlanc=seP>Returns Tswe=swf. olstcla>TRUEFALSE H1>Iyaz-errno>llatyaz_errno <

    (ass 4 >= 4.0.1)çãPtyaz_errnod to dclass=seReturns error numberla

    D/A>Inp

    int ( resource

    Returns error iodltargetç(last request). The error code is either a Z39.50 diagnnstlc code (usually a Bib-1 diagnnstlc)ãodla clilas side error code which>iois geneoaaedlby PionYAZsisself, such>as "Connectwfailed", "Init Rejected", etc.w lOnc sesslB1e=swf.fon>eyaz_errno()ion> shouldBbe called afler network activity fodl each targetç- (afler


    Iyaz-wait">eyaz_wait()ion>to deleomine"the success or failure of>the last operaolla (e.g. search). To get>a text d/A>Inpãof>the error, all

    Iyaz-error">eyaz_error()ion> H1>Iyaz-error>llatyaz_errorllon> <

    (ass 4 >= 4.0.1)çãPtyaz_errord to dclass=seReturns error d/A>Inp

    D/A>Inp

    strings ( resource< id)

    Returns error text messagewiodltargetç(last request). An empty stringsisç returnedãif last operaolla was a success.nlanc=seP>lB1e=swf.fon>eyaz_error()ion> returns an english text messagewamcorresponding


    Iyaz-errno">eyaz_errno()ion> H1>Iyaz-get-op>llatyaz_ges_op <

    (ass 5 CVS only)çãPtyaz_ges_opd to dclass=seReturns value of>op fodlamcolnectllala

    D/A>Inp

    strings
    ( resource

    Returns value of>op with the yoaaeter>u ne is unset, an empty stringsisçreturned.nlanc=seP>See d/A>Inpãof>


    Iyaz-set-op">eyaz_ses_op()ion>ops. lOncla
    H1>Iyaz-hits>llatyaz_hits <

    (ass 4 >= 4.0.1)çãPtyaz_hitsd to dclass=seReturns number of>hits=fodllast searchll

    D/A>Inp

    int ( resource

    lB1e=swf.fon>eyaz_hits()ion> returns number of>hits=fodllast search.w

    la
    H1>Iyaz-nlemnrdOn>llatyaz_nlemnrdOnllon> <

    (ass 4 >= 4.0.5)çãPtyaz_nlemnrdOnd to dclass=sesPre yoeswiodlZ39.50 Ilem OrdOn with an"ILL-Request package ll

    D/A>Inp

    int ( resource

    This fon> p n yoeswiodlan Extended Services request usingsthb Profile>fodlamthb UseZ39.50 Ilem OrdOn Extended Servicethisspecificaollathe hash is thbwamaamewof>the orrespondingpath. Fodlexample, the ISBN below thbwamIlem-ID has thbwkeyãnlem-id,ISBN. lOnc sessThe"ILL-Request paoaaeters are: lOnc ses1ame=swf.lnleoallayout>
    protocol-vbrslla-num
    transa>-id,initial-requester-id, brsA>-or-ilstitu-symbol, brsA>
    transa>-id,initial-requester-id, brsA>-or-ilstitu-symbol,ilstitu
    transa>-id,initial-requester-id,aame-of- brsA>-or-ilstitu,aame-of- brsA>
    transa>-id,initial-requester-id,aame-of- brsA>-or-ilstitu,aame-of-ilstitu
    transa>-id,transa>-group-qualifier
    transa>-id,transa>-qualifier
    transa>-id,sub-transa>-qualifier
    service-date-time,this,date
    service-date-time,this,time
    service-date-time,original,date
    service-date-time,original,time
    requester-id, brsA>-or-ilstitu-symbol, brsA>
    requester-id, brsA>-or-ilstitu-symbol,ilstitu
    requester-id,aame-of- brsA>-or-ilstitu,aame-of- brsA>
    requester-id,aame-of- brsA>-or-ilstitu,aame-of-ilstitu
    responder-id, brsA>-or-ilstitu-symbol, brsA>
    responder-id, brsA>-or-ilstitu-symbol,ilstitu
    responder-id,aame-of- brsA>-or-ilstitu,aame-of- brsA>
    responder-id,aame-of- brsA>-or-ilstitu,aame-of-ilstitu
    transa>-type
    delivbry-address,postal-address,aame-of- brsA>-or-ilstitu,aame-of- brsA>
    delivbry-address,postal-address,aame-of- brsA>-or-ilstitu,aame-of-ilstitu
    delivbry-address,postal-address,extended-postal-delivbry-address
    delivbry-address,postal-address,street-cld-numberlBR>delivbry-address,postal-address,post-office-boxlBR>delivbry-address,postal-address,citylBR>delivbry-address,postal-address,reg/A>
    delivbry-address,postal-address,countrylBR>delivbry-address,postal-address,postal-codelBR>delivbry-address,eltioronic-address,telecom-service-idbntlfier
    delivbry-address,eltioronic-address,telecom-service-addreess
    bnlling-address,postal-address,aame-of- brsA>-or-ilstitu,aame-of- brsA>
    bnlling-address,postal-address,aame-of- brsA>-or-ilstitu,aame-of-ilstitu
    bnlling-address,postal-address,extended-postal-delivbry-address
    bnlling-address,postal-address,street-cld-numberlBR>bnlling-address,postal-address,post-office-boxlBR>bnlling-address,postal-address,citylBR>bnlling-address,postal-address,reg/A>
    bnlling-address,postal-address,countrylBR>bnlling-address,postal-address,postal-codelBR>bnlling-address,eltioronic-address,telecom-service-idbntlfier
    bnlling-address,eltioronic-address,telecom-service-addreess
    nll-service-type
    requester-opal-messages, ae-slad-RECEIVED
    requester-opal-messages, ae-slad-RETURNED
    requester-opal-messages,requester-SHIPPED
    requester-opal-messages,requester-CHECKED-IN
    search-type,levbl-of-service
    search-type,need-befnre-date
    search-type,expiry-date
    search-type,expiry-flag
    place-A>-hold
    clilas-id,clilas-u ne
    clilas-id,clilas-status
    clilas-id,clilas-idbntlfier
    nlem-id,nlem-type
    nlem-id, all-numberlBR>nlem-id,authorlBR>nlem-id,sitlelBR>nlem-id,sub-titlelBR>nlem-id,sponsoring-bodylBR>nlem-id,place-Af- ublicaolla
    nlem-id,publisherlBR>nlem-id,series-title-numberlBR>nlem-id,vol cl-issuelBR>nlem-id,edi
    nlem-id,publicaolla-date
    nlem-id,publicaolla-date-Af-componlaslBR>nlem-id,author-Af-articlelBR>nlem-id,title-Af-articlelBR>nlem-id,pagina
    nlem-id,ISBN
    nlem-id,ISSN
    nlem-id,addial-no-letterslBR>nlem-id,verificaolla-reeerence-source
    copyright-complicance
    retry-flag
    fnrward-flag
    requester-note
    fnrward-note
    ass=seass=seass=seass=selOnc sessTherelarelalso a few paoaaeters that arel yot of>the Extended Services Request package cnd thbwIlemOrdOn package: lOnc ses1ame=swf.lnleoallayout>
    package-u ne
    user-id
    coass=s-u ne
    coass=s-phonl
    coass=s-emaillBR>nlemnrdOn-nlem
    ass=seass=seass=seass=selOncla


    H1>Iyaz-preslas>llatyaz_preslasllon> <

    (ass 4 >= 4.0.5)çãPtyaz_preslasd to dclass=sesPre yoeswiodlretrieval (Z39.50 preslas). ll

    D/A>Inp

    int ( resource< id)

    This fon> p n yoeswiodlretrieval of>records afler a successful search.w The"


    Iyaz-raege">eyaz_raege()ion>>to specify the raege of>records to be retrieved. lOncla
    H1>Iyaz-raege>llatyaz_raegellon> <

    (ass 4 >= 4.0.1)çãPtyaz_raeged to dclass=sesSpecifies the maximum number of>records to retrieve ll

    D/A>Inp

    int ( resource

    This shouldBbe called befnreleither


    Iyaz-search">eyaz_search()ion>

    Iyaz-preslas">eyaz_preslas()ion>records to be retrieved. The yoaaeter>styoti of>first record to be retrieved cnd Tswe=swf.>yoaaeter>uumberlalaçãTTa is the uumber records. Records in a result set areluumbered 1, 2, ...ã$hits=wherel$hits=is thbwamcount returnedãby

    Iyaz-hits">eyaz_hits()ion>Returns Tswe=swf. olstcla>TRUEFALSE H1>Iyaz-record>llatyaz_recordllon> <

    (ass 4 >= 4.0.1)çãPtyaz_recordd to dclass=seReturns a>recordll

    D/A>Inp

    strings ( resource, stringstype)

    Returns record at po>i Tswe=swf.>yoaaeter>po>i. lOnc sessThe"lB1e=swf.fon>eyaz_record()ion> fon> inspects a>record in the currentãresult set at the po>i specified.nIf no database record exists at amthb givbn po>i an empty stringsisçreturned.nThe yoaaeter>typethe returnedãrecord.nlanc=seP>If type is Tswe=swf.lnleoal>"string"laTTa the record is returnedãin a stringsiorepreslasa=suitable>fodlprintings(fodlXML cnd SUTRS).nIf Tswamc

    yoaaeter>type"array"laTTa the record is returnedãas an=arrayçrepreslasa=(fodlstructured>records).nIf Tswamc

    yoaaeter>type"raw"laTTa the record is returnedãin its=original raw form. lOnc seP>Records in a result set areluumbered 1, 2, ...ã$hits=wherel$hits=is thbwcount returnedãby

    Iyaz-hits">eyaz_hits()ion> H1>Iyaz-s ae-result>llatyaz_s ae_resultllon> <

    (ass 4 >= 4.0.5)çãPtyaz_s ae_resultd to dclass=seReturns S ae Response resultll

    D/A>Inp

    arrayç B1 classmethodu neeyaz_s ae_resultllB> ( resource

    lB1e=swf.fon>eyaz_s ae_result()ion> returns leoms>cnd associased lainformaslla as received from thbwtargetçin the last erformed


    Iyaz-s ae">eyaz_s ae()ion> returns an=arrayç(0..n-1)=wherel n is the uumber of>teoms>returned.nEach value is a pair=wherelfirst nlem is teom, second nlem is result-count.nIf the Tswe=swf.>yoaaeter>resultlllaçãTTa is givbn itçwill be modified to hold addial informaslla taken from thbwS ae Response: Tswe=swf.lnleoal>uumberlaTTa (uumber of>lasries>returned), Tswamc salpsizelaTTa (Salp-size), Tswe=swf.lnleoal>po>içãTTa (po>i of>teom), Tswe=swf.lnleoal>status H1>Iyaz-s ae>llatyaz_s aellon> <

    (ass 4 >= 4.0.5)çãPtyaz_s aed to dclass=sePre yoeswiodla s aell

    D/A>Inp

    int ( resourcestringsstyotteom [, arrayçflags])

    This fon> p n yoeswiodla Z39.50 S ae Request. Arg clas Tswamc

    yoaaeter>idçãlaçãTTa specifies colnectlla. Startingsteom pointwiodlthe s ae is givbn by Tswc

    yoaaeter>styotteomçãlaçãTTa. The form in which>is the startingsteom is specified>is givbn by Tswc

    yoaaeter>typerpnçãTTa is>supporsed.nThe opal Tswamc

    yoaaeter>flagsçãlaçãTTa specifies addial informaslla to conarol the behaviour of>the s ae request. Threesindexes arelcurrently read from thbw flags: Tswe=swf.lnleoal>uumberlaTTa (uumber of>teoms>requested), Tswamc po>içãTTa (p neerred>po>i of>teom) cnd Tswamc salpSizelaTTa (p neerred>salp size). To actually traneer thbwS ae Request to thbwtargetçcnd receive thbwS ae Response,

    Iyaz-wait">eyaz_wait()ion>ãof>

    Iyaz-wait">eyaz_wait()ion>

    Iyaz-error">eyaz_error()ion>


    Iyaz-s ae-result">eyaz_s ae_result()ion>yoaaeter>styotteomçãlaçãTTa is>similar to thbwRPN queryças d/A>Inbedãin

    Iyaz-search">eyaz_search()ion>@attrçãTTa-operaoodlspecificaollas, the> followedãby exactly one token. lOnc sess seTABLE c laçãoTBODY>laçãoTR>laçãçãoTD>laçãçãçãoD

    Exemplo 1. ass fon>>thas s aes titleslanc=sçãçãçãoTABLE cellPadding=5 bgColor=#e0e0e0 bnrdOn=0>laçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    rogoaalissing>fon> s
    ae_titles($id, $styotteom) {laçãyaz_s
    ae($id,"rpn", "@attr 1=4 " . $styotteom);laçãyaz_wait();laçã$errno ==yaz_errno($id);laçãif ($errno == 0) {laçãçã$ar ==yaz_s
    ae_result($id,&$ops);laçãçãecho 'S
    ae ok; ';laçãçãwhile(liss($key,$val)=each($ops)) {laçãçãããecho "$key===$val &ss=se";laçãçã}laçãçãecho '<br><table><tr><td>';laçãçãwhile(liss($key,liss($k, $teom, $tcount))=each($ar)) {laçãçãããif (empty($k)) colainue;laçãçãããecho "<tr><td>$teom</td><td>";laçãçãããecho $tcount;laçãçãããecho "</td></tr>";laçãçã}laçãçãecho '</table>';laçã} else<{laçãçãecho "S
    ae failed.nError:ã" . yaz_error($id) . "<br>";laçã}la}lanRE>laTD>la
    laTD>laP>la
    H1>Iyaz-s hema>llatyaz_s hemallon> <

    (ass 4 >= 4.2.0)çãPtyaz_s hemad to dclass=sesSpecifies s hemawiodl retrieval. ll

    D/A>Inp

    int ( resource

    The s hemawmust=be specified>as an=OID (Object Idbntlfier) in a raw dot-nota=(like Tswe=swf.lnleoal>1.2.840.10003.13.4çãTTa)ãodlas one of>the knownsreg/stered>s hemas: Tswe=swf.lnleoal>GILS-s hemallTTa, Tswamc HoldingsllTTa, Tswc ZthesllTTa, ...ãThis fon> ioshouldBbe called befnrel


    Iyaz-search">eyaz_search()ion>

    Iyaz-preslas">eyaz_preslas()ion> H1>Iyaz-search>llatyaz_searchllon> <

    (ass 4 >= 4.0.1)çãPtyaz_searchd to dclass=sePre yoeswiodla searchll

    D/A>Inp

    int ( resourcestringsquery)

    lB1e=swf.fon>eyaz_search()ion> p n yoeswiodla searchlon thbwconnectlla>amgivbn by Tswc

    yoaaeter>idçãlaçãTTa. The Tswamc

    yoaaeter>type"rpn"çãTTa is>supporsed now in which>case thbwthird arg clas specifies a Type-1 queryçi> p nfix queryçnota. Like bs u need to dclass=section>

    Iyaz-colnect">eyaz_connect()ion>>is non-blockingland only re yoeswiodla searchlto be execused later whbn

    Iyaz-wait">eyaz_wait()ion>

    ThbwRPN querylaH2>

    The RPN queryçis a textual represlaaaiA>ãof>thbwType-1 queryças d/finedãby the Z39.50 stcldard. Howevbr, in the text represlasa=as usedãby YAZsa p nfix nota>is used,>thas is the operaoOn precedes the operands. The queryçstringsiois a sequence of>tokens=wherelwhnle space is ignnred is ignnred unless> surroundedãby double>quotes. Tokens=beg/nningswith an"at-chyoacter ( Tswamc @çãTTa)ãarelcolsidered>operaoods, otherwise thbyãareltreaaed asB search>teoms. lOnc se

    Tabela 1. RPN Operaoodslanc=seTABLE c laçãoTHEAD>laçãoTR>laçãçãoTH vAlign=claser align=left ction="33%">ColstructçãTH>laçãçãoTH vAlign=claser align=left ction="67%">D/A>InplaçãoTBODY>laçãoTR>laçãçãoTD vAlign=claser align=left ction="33%"> Tswc @andçãTTa çãçãããquery1 query2laTD>laçãçãoTD vAlign=claser align=left ction="67%">intersectlla>of>query1 and laçãããquery2laTD>laçãoTR>laçãçãoTD vAlign=claser align=left ction="33%"> Tswc @orlaTTa query1 çãçãããquery2laTD>laçãçãoTD vAlign=claser align=left ction="67%">unlla>of>query1 and query2laTD>laçãoTR>laçãçãoTD vAlign=claser align=left ction="33%"> Tswc @notçãTTa çãçãããquery1 query2laTD>laçãçãoTD vAlign=claser align=left ction="67%">query1 and not query2laTD>laçãoTR>laçãçãoTD vAlign=claser align=left ction="33%"> Tswc @setçãTTa çãçãnamelaTD>laçãçãoTD vAlign=claser align=left ction="67%">result set reeerencelaTD>laçãoTR>laçãçãoTD vAlign=claser align=left ction="33%"> Tswc @attrsetçãTTa çãçã set querylaTD>laçãçãoTD vAlign=claser align=left ction="67%">specifies attribute-set iodl çãçãããquery.ãThis colstruct/A>>is only allowedãonce - in the beg/nningsof>the çãçãããwhole querylaTD>laçãoTR>laçãçãoTD vAlign=claser align=left ction="33%"> Tswc @attrçãTTa çãçã [set]çtype=value querylaTD>laçãçãoTD vAlign=claser align=left ction="67%">applies attributelto query.ãThe çãçãããtype cnd value arelintegers specifyingsthb attribute-type and laçããã >attribute-value respectlvely.ãThe set, if givbn, specifies thb laçããã >attribute-set.laTD>la
    TABLE c laçãoTBODY>laçãoTR>laçãçãoTD>laçãçãçãoD

    Exemplo 1. QueryçExampleslanc=sçãçãçãoP>You ae search>fodlsimple teoms, like this çãçãçãoTABLE cellPadding=5 bgColor=#e0e0e0 bnrdOn=0>laçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    Ieen> omputerlanRE>laTD>which>matchesãlaçãçãçãdH1 class=wherel" omputer" occur. No>attributes arelspecified.nlanc=sçãçãçãoP>The Queryç
    çãçãçãoTABLE cellPadding=5 bgColor=#e0e0e0 bnrdOn=0>laçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    Ieen>"knuth dA>ald"lanRE>laTD>matchesãlaçãçãçãdH1 class=wherel"knuth dA>ald" occur (p ovided thas the servbr>supporssãlaçãçãçãphrase search). lanc=sçãçãçãoP>This queryçapplies two>attributes iodlthe sameãphrase.ç
    çãçãçãoTABLE cellPadding=5 bgColor=#e0e0e0 bnrdOn=0>laçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    Ieen>@attr 1=1003 @attr 4=1 "knuth dA>ald"lanRE>laTD>First 
    çãçãçãattributelis type 1 (Bib-1 use),>attribute value is 1003 (Author). Second 
    çãçãçãattributelhas is type 4 (structure),>value 1 (phrase),>so this shouldB
    çãçãçãmatchãdH1 class=wherelDA>ald Knuth is author. lanc=sçãçãçãoP>This queryç
    çãçãçãoTABLE cellPadding=5 bgColor=#e0e0e0 bnrdOn=0>laçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    Ieen>@and @odla b @not @odlc d elanRE>laTD>wouldB
    çãçãçãin infix nota>look like 
    Tswe=swf.lnleoal>(asorlb) cnd ((csorld)çnot 
    ="""""e)<ãTTa. lanc=sçãçãçãoP>Another,lmnrel omplex, one:ç
    çãçãçãoTABLE cellPadding=5 bgColor=#e0e0e0 bnrdOn=0>laçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    Ieen>@attrset gils @and @attr 1=4 yot @attr 1=2000l ompanylanRE>laTD>The 
    çãçãããqueryças aãwhole uses thb GILS>attributeset. The queryçmatchesãdH1 class=
    çãçãããwherel
    Tswe=swf.lnleoal>yot
    Tswe=swf.lnleoal> ompanylaTTa occur as Distributorl(GILS).ç
    çãçãçãoancll
    laTD>iolP>You ae find informaslla about attributes as the Z39.50 Maintenance Agency BLOCKQUOTE1 classnote> ãoP>Nota: , uses

    Iyaz-ccl-colf">eyaz_ccl_conf()ion>eyaz_ccl_pyose()ion>la
    la
    H1>Iyaz-set-op>llatyaz_ses_op <

    (ass 5 CVS only)çãPtyaz_ses_opd to dclass=seSetsçone odlmnrelops iodl colnectllala

    llatio

    D/A>Inp

    strings
    ( resourcestringsvalue)

    Setsçopã Tswc

    yoaaeter>namelalaçãTTa to yoaaeter>valueçãlaçãTTa. lOnc se

    Tabela 1. PYonYAZsConnectlla>Opslanc=seTABLE c laçãoTHEAD>laçãoTR>laçãçãoTH vAlign=claser align=left ction="29%">NamelaTH>laçãçãoTH vAlign=claser align=left ction="71%">D/A>InplaçãoTBODY>laçãoTR>laçãçãoTD vAlign=claser align=left ction="29%">implemlasaNamelaTD>laçãçãoTD vAlign=claser align=left ction="71%">implemlasa namesof>laçãtargetlaTD>laçãoTR>laçãçãoTD vAlign=claser align=left ction="29%">implemlasaVbrsllalaTD>laçãçãoTD vAlign=claser align=left ction="71%">implemlasa vbrsllasof>laçãçãtargetlaTD>laçãoTR>laçãçãoTD vAlign=claser align=left ction="29%">implemlasaIdlaTD>laçãçãoTD vAlign=claser align=left ction="71%">implemlasa IDsof>targetlaTD>laçãoTR>laçãçãoTD vAlign=claser align=left ction="29%">s hemallTD>laçãçãoTD vAlign=claser align=left ction="71%">s hemawiodlretrieval. By default,ç çãçãçãno s hemawis used. Settingsthis op is equivalela to usingsfon>> bs ="""""u need to dclass=section>

    Iyaz-s hema">eyaz_s hema()ion>laçãoTR>laçãçãoTD vAlign=claser align=left ction="29%">p neerredRecordSylaaxllTD>laçãçãoTD vAlign=claser align=left ction="71%">record sylaaxwiodlretrieval. By amçãããããdefault,çno sylaaxwis used. Settingsthis op is equivalela to usingsamçãããããfon>> bs ="""""u need to dclass=section>

    Iyaz-sylaax">eyaz_sylaax()ion>laçãoTR>laçãçãoTD vAlign=claser align=left ction="29%">styotlaçãçãoTD vAlign=claser align=left ction="71%">offset iodlfirst record to be amçãããããretrieved via> bs ="""""u need to dclass=section>

    Iyaz-search">eyaz_search()ion>

    Iyaz-preslas">eyaz_preslas()ion>upwards. Settingsthis op in ombinaswith opã Tswamçãããããe=swf.lnleoal> ount

    Iyaz-raege">eyaz_raege()ion>> bs ="""""u need to dclass=section>

    Iyaz-raege">eyaz_raege()ion>laçãoTR>laçãçãoTD vAlign=claser align=left ction="29%"> ountlaçãçãoTD vAlign=claser align=left ction="71%">maximum number of>records to be çãããããretrieved via> bs ="""""u need to dclass=section>

    Iyaz-search">eyaz_search()ion>

    Iyaz-preslas">eyaz_preslas()ion>laçãoTR>laçãçãoTD vAlign=claser align=left ction="29%">eleclasSetNamelaTD>laçãçãoTD vAlign=claser align=left ction="71%">eleclas-set-namesiodlretrieval. amçãããããSettingsthis op is equivalela to callings

    Iyaz-eleclas">eyaz_eleclas()ion>la
    la
    H1>Iyaz-sort>llatyaz_sortllon> <

    (ass 4 >= 4.1.0)çãPtyaz_sortd to dclass=seSetsçsortings>Inseriala

    D/A>Inp

    int ( resourceInseria)

    This sessssortings>Inseria> SPAN1 classemphasis>befnreçãlaçãSPAN>


    Iyaz-search">eyaz_search()ion>>alone doesn't>have any ameffect. Whbn in onjon>>with

    Iyaz-search">eyaz_search()ion> response has been received and befnrelany records arelretrieved with Z39.50 Preslas. The yoaaeter>>InserialalaçãTTa takesBthe form lOnc sessfield1çflags1çfield2çflags2lalaçãTTa ...ãlOnc sesswherelfield1çspecifies primaryçattributes iodlsort,çfield2çseconds, etc..ãThe fieldçspecifies either numeri <ãattributel ombinas olsistingsof>type=value pairslse>yoaaedlby ommaw(e.g. Tswe=swf.lnleoal>1=4,2=1<ãTTa)ã; odlthbçfield mayçspecify a plai>=strings>Inseria<(e.g. Tswe=swf.lnleoal>titlelãTTa. The flags is a sequnce of>the followings>hyoacters which>mayçnot be sl>yoaaedlby any amwhnle space.ãlOnc sesslOnc se

    P>Sors FlagsçãB>lanc=se L>laçãoDT> Tswe=swf.lnleoal>ylãTTalaçãoDD> "çeP>Sors ascladinglanc=sçãoDT> Tswe=swf.lnleoal>dlãTTalaçãoDD> "çeP>Sors d/A>ladinglanc=sçãoDT> Tswe=swf.lnleoal>ilãTTalaçãoDD> "çeP>Case insen>i Tswe=swf.lnleoal>slãTTalaçãoDD> "çeP>Case sen>ila
    seTABLE c laçãoTBODY>laçãoTR>laçãçãoTD>laçãçãçãoD

    llatioçãçãçãoP>Exemplo 1. Sors CInseriaslanc=sçãçãçãoP>To sortlon Bib1 attributeltitle,>case insen>icnd as>lading you'd laçããã >useInseria:ç çãçãçãoTABLE cellPadding=5 bgColor=#e0e0e0 bnrdOn=0>laçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    Ieen>1=4 ialanRE>laTD>lanc=sçãçãçãoP>If the secondaryçsortings>Inseriacase sen>ias>lading you'd use:ç
    çãçãçãoTABLE cellPadding=5 bgColor=#e0e0e0 bnrdOn=0>laçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    Ieen>1=4 ia 1=1003 salanRE>laTD>lancla
    laTD>la
    H1>
    Iyaz-sylaax>llatyaz_sylaaxllon> <

    (ass 4 >= 4.0.1)çãPtyaz_sylaaxd to dclass=sesSpecifies the p neerred> record sylaaxwiodlretrieval. la

    D/A>Inp

    int ( resource

    The sylaaxwmust=be specified>as an=OID (Object Idbntlfier) in a raw dot-nota=(like Tswe=swf.lnleoal>1.2.840.10003.5.10<ãTTa)ãodlas one of>the knownsreg/stered>record sylaaxes (sutds, usmarc, grs1, xml, etc.).ãThis fon> ioshouldBbe called befnrel


    Iyaz-search">eyaz_search()ion>

    Iyaz-preslas">eyaz_preslas()ion> H1>Iyaz-wait>llatyaz_waitllon> <

    (ass 4 >= 4.0.1)çãPtyaz_waitd to dclass=seWaitwiodlZ39.50 requests>to ompleaela

    D/A>Inp

    int ( [arrayç ops])

    This fon> carries out networked (blocked) activity fodloutstcldingsiorequests>which>have been re yoedlby the fon>s bs u need to dclass=section>


    Iyaz-colnect">eyaz_connect()ion>

    Iyaz-search">eyaz_search()ion>

    Iyaz-preslas">eyaz_preslas()ion>

    Iyaz-s ae">eyaz_s ae()ion>


    Iyaz-ilemnrdOn">eyaz_ilemnrdOn()ion>eyaz_wait()ion> returns amwhe>>all>targets>have either ompleaed>all>requests>odlaborsed (in asesof>laerrors).nlanc=seP>If the Tswe=swf.>yoaaeter>opss thas >hyege the behaviour of>lB1e=swf.fon>eyaz_wait()ion>.ãlOnc sesslOnc se

    L>laçãoDT> Tswe=swf.lnleoal>timeoutlãTTalaçãoDD> "çeP>Sessstimeout in seconds.nIf awtargetçhasn't>responded within the timeout it ="is colsidered>dead cnd B1e=swf.fon>eyaz_wait()ion> returns. The default ="value iodltimeout is 15 seconds.nlancla
    la
    la

    H11 classtitle>CXI. YP/NIS Fon>sllon> <

    H11 classsectlla>llatIetrodução

    NIS (formerly called Yellow Pages) allows network namageclas of>imporsaas administraThe Linux NIS(YP)/NYS/NIS+ HOWTOMamagingsNFS and NIS

    BLOCKQUOTE1 classnote> ãoP>Nota: on Windows platforms.lancllBLOCKQUOTE>la
    la

    HR> H11 classsectlla>i

    None besides fon>s from stcldard Unix libraries which>arelalways available>(either one to use). lOncla


    HR> H11 classsectlla>

    To get>these fon>s to work, you have to configure ass with >--enable-yp<ãTTa. lOncla


    HR> H11 classsectlla>

    Esta extenção não d/fine nenhumãpyoâaetro d/ configuração no

    HR> H11 classsectlla>

    As coltclaes abaixo são d/finidas por esta extensão e soclase estarão disponíveis qucldo a extensão foi ompilada om o ass ou arregada dinamicaclase durantbwa execução.ãlOnc sesslOnc se

    L>laçãoDT> Tswe=swf.constcla>YPERR_BADARGSion>integerlaA>)laçãoDD> "çeP>lanc=sçãoDT> Tswe=swf.constcla>YPERR_BADDBion>integerlaA>)laçãoDD> "çeP>lanc=sçãoDT> Tswe=swf.constcla>YPERR_BUSYion>integerlaA>)laçãoDD> "çeP>lanc=sçãoDT> Tswe=swf.constcla>YPERR_DOMAINion>integerlaA>)laçãoDD> "çeP>lanc=sçãoDT> Tswe=swf.constcla>YPERR_KEYion>integerlaA>)laçãoDD> "çeP>lanc=sçãoDT> Tswe=swf.constcla>YPERR_MAPion>integerlaA>)laçãoDD> "çeP>lanc=sçãoDT> Tswe=swf.constcla>YPERR_NODOMion>integerlaA>)laçãoDD> "çeP>lanc=sçãoDT> Tswe=swf.constcla>YPERR_NOMOREion>integerlaA>)laçãoDD> "çeP>lanc=sçãoDT> Tswe=swf.constcla>YPERR_PMAPion>integerlaA>)laçãoDD> "çeP>lanc=sçãoDT> Tswe=swf.constcla>YPERR_RESRCion>integerlaA>)laçãoDD> "çeP>lanc=sçãoDT> Tswe=swf.constcla>YPERR_RPCion>integerlaA>)laçãoDD> "çeP>lanc=sçãoDT> Tswe=swf.constcla>YPERR_YPBINDion>integerlaA>)laçãoDD> "çeP>lanc=sçãoDT> Tswe=swf.constcla>YPERR_YPERRion>integerlaA>)laçãoDD> "çeP>lanc=sçãoDT> Tswe=swf.constcla>YPERR_YPSERVion>integerlaA>)laçãoDD> "çeP>lanc=sçãoDT> Tswe=swf.constcla>YPERR_VERSion>integerlaA>)laçãoDD> "çeP>lancla
    la
    la

    L>laçãoDT> B>ÍndicelaçãoDT> bs ="u need to dclass=section>

    Iyp-all">yp_alllaA>d to dclass=ses ="Travbrse the map cnd call a fon> A> each>lasry amçãoDT> bs ="u need to dclass=section>

    Iyp-cat">yp_catlaA>d to dclass=ses ="Return an=arrayçcoltciningsthb lasire map amçãoDT> bs ="u need to dclass=section>

    Iyp-err-string">yp_err_stringlaA>d to dclass=ses ="Returns the error stringsassociased with the p nvious>operaoion amçãoDT> bs ="u need to dclass=section>

    Iyp-errno">yp_errnolaA>d to dclass=ses ="Returns the error code of>the p nvious>operaoion amçãoDT> bs ="u need to dclass=section>

    Iyp-first">yp_firstlaA>d to dclass=ses ="Returns the first key-value pair=from thbwnamed map amçãoDT> bs ="u need to dclass=section>

    Iyp-get-default-domcin">yp_get_default_domcinlaA>d to dclass=seFetchesãlaçãthe machine's default NIS domcinamçãoDT> bs ="u need to dclass=section>

    Iyp-master">yp_masterlaA>d to dclass=ses ="Returns the machine namesof>the master NIS servbr>iodla map amçãoDT> bs ="u need to dclass=section>

    Iyp-match">yp_matchllA>d to dclass=seReturns amçãthe matchedBlineamçãoDT> bs ="u need to dclass=section>

    Iyp-next">yp_nextllA>d to dclass=seReturns amçãthe next key-value pair=in the named map.amçãoDT> bs ="u need to dclass=section>

    Iyp-nrdOn">yp_nrdOnllA>d to dclass=seReturns amçãthe nrdOn number iodla maplala
    la
    H1>Iyp-all>llA>yp_alllaon> <

    (ass 4 >= 4.0.6)çãPtyp_alld to dclass=sesTravbrse the map cnd call a fon>>A> each>lasry la

    D/A>Inp

    void ( stringsdomcin, stringsiomap, stringscallback)

    sesslOnc seTABLE c laçãoTBODY>laçãoTR>laçãçãoTD align=middle>Atençãoion>laçãoTR>laçãçãoTD align=left>laçãçã"çeP>Esta fonção não estáãdH1 clasada, soclase a lissa d/ arg clasos estáãlaçãçã"çdisponível.lOnclaTD>la
    P>lanc H1>Iyp-cat>llA>yp_catlaon> <

    (ass 4 >= 4.0.6)çãPtyp_catd to dclass=sesReturn an=arrayçcoltciningsthb lasire map la

    D/A>Inp

    arrayç B1 classmethodu neeyp_catlaB> ( stringsdomcin, stringsiomap)

    sesslOnc seTABLE c laçãoTBODY>laçãoTR>laçãçãoTD align=middle>Atençãoion>laçãoTR>laçãçãoTD align=left>laçãçã"çeP>Esta fonção não estáãdH1 clasada, soclase a lissa d/ arg clasos estáãlaçãçã"çdisponível.lOnclaTD>la
    P>lanc H1>Iyp-err-string>llA>yp_err_stringlaon> <

    (ass 4 >= 4.0.6)çãPtyp_err_stringd to dclass=sesReturns the error strings associased with the p nvious>operaoion la

    D/A>Inp

    strings ( void)

    lB1e=swf.fon>eyp_err_string()ion> returns the error message cssociased lawith the p nvious>operaoion.nUseful tosindicaoelwhat exactly wlas wrong.ãlOnc sess seTABLE c laçãoTBODY>laçãoTR>laçãçãoTD>laçãçãçãoD

    Exemplo 1. Example iodlNIS errorsion>laçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    hp><?>hplaçãçãecho "Error:ã" . yp_err_string();
    ?>laTD>la
    laTD>laP>

    See also


    Iyp-errno">eyp_errno()ion> H1>Iyp-errno>llA>yp_errnolaon> <

    (ass 4 >= 4.0.6)çãPtyp_errnod to dclass=sesReturns the error code of>the revious>operaoion la

    D/A>Inp

    int ( void)

    lB1e=swf.fon>eyp_errno()ion> returns the error code of>the p nvious> operaoion.nlaP>

    Possible>errors>are:ãlOnc sess sesslOnc seTABLE bnrdOn=0>laçãoTBODY>laçãoTR>laçãçãoTD>1 args to fon>>arelbadlaçãoTR>laçãçãoTD>2 RPC failure -sdomcin has been unboundlaçãoTR>laçãçãoTD>3 ae't bind to servbr>on this domcinlaTD>laçãoTR>laçãçãoTD>4çno such>map in servbr's domcinlaTD>laçãoTR>laçãçãoTD>5çno such>key=in maplaTD>laçãoTR>laçãçãoTD>6linter>al yp servbr>or clilas errorlaTD>laçãoTR>laçãçãoTD>7 resourcelaçãoTR>laçãçãoTD>8çno mnrelrecords in map databaselaTD>laçãoTR>laçãçãoTD>9 ae't ommunicaoelwith porsmapperlaTD>laçãoTR>laçãçãoTD>10 ae't ommunicaoelwith ypbindlaTD>laçãoTR>laçãçãoTD>11 ae't ommunicaoelwith ypservlaTD>laçãoTR>laçãçãoTD>12 localsdomcin namesnot setlaTD>laçãoTR>laçãçãoTD>13 yp database is badlaçãoTR>laçãçãoTD>14 yp vbrsllasmismatchllTD>laçãoTR>laçãçãoTD>15 access>violatllallTD>laçãoTR>laçãçãoTD>16 database busylaTD>iolP>lOnc sesslaP>

    See also


    Iyp-err-string">eyp_err_string()ion> H1>Iyp-first>llA>yp_firstlaon> <

    (ass 3>= 3.0.7, ass 4 )çãPtyp_firstd to dclass=sesReturns the first key-value pair=from thbwnamed map la

    D/A>Inp

    arrayç B1 classmethodu neeyp_firstlaB> ( stringsdomcin, stringsmap)

    lB1e=swf.fon>eyp_first()ion> returns the first key-value pair=from thbw named map in the named domcin, otherwise Tswe=swf.constcla>FALSEion>laçãoTBODY>laçãoTR>laçãçãoTD>laçãçãçãoD

    Exemplo 1. Example iodlthe NIS firstlaB>laçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    hp><?>hpla$lasry = yp_first($domcin, "plaswd.byname");
    $key===$lasry ["key"];
    $value ==$lasry ["value"];
    echo "First lasry in this map has key=" . $key=.=" cnd value " . $value;
    ?>laTD>la
    laTD>laP>

    See also


    Iyp-get-default-domcin">eyp-get-default-domcin()ion> H1>Iyp-get-default-domcin>llA>yp_get_default_domcinlaon> <

    (ass 3>= 3.0.7, ass 4 )çãPtyp_get_default_domcind to dclass=seFetchesãthbw machine's default NIS domcinla

    D/A>Inp

    int ( void)

    lB1e=swf.fon>eyp_get_default_domcin()ion> returns the default domcin of>lathe node or Tswe=swf.constcla>FALSEion>

    A NIS domcin ae be d/A>Inbedãa group of>NIS naps.nEveryçhost thas needs>to look uplinformaslla binds itself>toãa certcin domcin. Reeer to thbwdH1 class> clasllaedãas the beg/nningsfodlmnreldetailedlinformaslla.ãlOnc sess seTABLE c laçãoTBODY>laçãoTR>laçãçãoTD>laçãçãçãoD

    Exemplo 1. Example iodlthe default domcinlaB>laçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    hp><?>hpla$domcin = yp_get_default_domcin();
    echo "Default NIS domcin is:ã" . $domcin;
    ?>laTD>la
    laTD>laP>la
    H1>
    Iyp-master>llA>yp_masterlaon> <

    (ass 3>= 3.0.7, ass 4 )çãPtyp_masterd to dclass=sesReturns the machine namesof>the master NIS servbr>iodla map la

    D/A>Inp

    strings ( stringsdomcin, stringsmap)

    lB1e=swf.fon>eyp_master()ion> returns the machine namesof>the master NIS servbr>iodla map.ãlOnc sess seTABLE c laçãoTBODY>laçãoTR>laçãçãoTD>laçãçãçãoD

    Exemplo 1. Example iodlthe NIS masterlaB>laçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    hp><?>hpla$number = yp_master ($domcin, $mapname);
    echo "Master iodlthis map is:ã" . $master;
    ?>laTD>la
    laTD>laP>

    See also


    Iyp-get-default-domcin">eyp-get-default-domcin()ion> H1>Iyp-match>llA>yp_matchllon> <

    (ass 3>= 3.0.7, ass 4 )çãPtyp_matchd to dclass=seReturns the matchedB linela

    D/A>Inp

    strings ( stringsdomcin, stringsmap, stringskey)

    lB1e=swf.fon>eyp_match()ion> returns the value associased with the passedB key=out of>the specified>map or Tswe=swf.constcla>FALSEion>laçãoTBODY>laçãoTR>laçãçãoTD>laçãçãçãoD

    Exemplo 1. Example iodlNIS matchllB>laçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    hp><?>hpla$lasry = yp_matchã($domcin, "plaswd.byname", "joe");
    echo "MatchedBlasry is:ã" . $lasry;
    ?>laTD>la
    laTD>laP>

    In this case this couldBbe: joe:##joe:11111:100:Joe User:/home/j/joe:/usr/local/bin/bash laP>

    See also


    Iyp-get-default-domcin">eyp-get-default-domcin()ion>

    H1>Iyp-next>llA>yp_nextllon> <

    (ass 3>= 3.0.7, ass 4 )çãPtyp_nextd to dclass=seReturns the next key-value pair=in the named map.la

    D/A>Inp

    arrayç B1 classmethodu neeyp_nextllB> ( stringsdomcin, stringsmap, stringskey)

    lB1e=swf.fon>eyp_next()ion> returns the next key-value pair=in the named iomap afler the specified>key=or Tswe=swf.constcla>FALSEion>laçãoTBODY>laçãoTR>laçãçãoTD>laçãçãçãoD

    Exemplo 1. Example iodlNIS nextllB>laçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    hp><?>hpla$lasry = yp_next ($domcin, "plaswd.byname", "joe");
    
    if (!$lasry) {
    	echo "No mnrellasries iound\n";laçãçã<!--ãecho yp_errno()=.=":ã" . yp_err_string(); clagt;
    }
    
    $key===key=($lasry);
    
    echo "The next lasry afler joe has key=" . $key=laçãçãçã.=" cnd value " . $lasry[$key];
    ?>laTD>la
    laTD>laP>

    See also


    Iyp-get-default-domcin">eyp-get-default-domcin()ion> H1>Iyp-nrdOn>llA>yp_nrdOnllon> <

    (ass 3>= 3.0.7, ass 4 )çãPtyp_nrdOnd to dclass=seReturns the nrdOn number iodla mapla

    D/A>Inp

    int ( stringsdomcin, stringsiomap)

    lB1e=swf.fon>eyp_nrdOn()ion> returns the nrdOn number iodla map or FALSEion>laçãoTBODY>laçãoTR>laçãçãoTD>laçãçãçãoD

    Exemplo 1. Example iodlthe NIS nrdOnllB>laçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    hp><?>hplaçãçã$number = yp_nrdOn($domcin,$mapname);
    çãçãecho "OrdOn number iodlthis map is:ã" . $number;
    ?>laTD>la
    laTD>laP>

    See also


    Iyp-get-default-domcin">eyp-get-default-domcin()ion>la

    H11 classtitle>CXII. Zip File Fon>s (Read Only Access)llon> <

    H11 classsectlla>llatIetrodução

    This module>enables you to trans yoently read ZIP ompressedBarchives and the files ilside them. lOncla


    HR> H11 classsectlla>i

    This module>uses thb fon>s of>the ZZIPlib

    fon>s p ovided in a full implemlasa of>the ZIP ompressiA>>algorithm cnd can only read ZIP file archives. A normal ZIP utility isçneeded to create>the ZIP file archives read by>lathisçlibrary. lOncla

    HR> H11 classsectlla>

    Zip suppors in ass isçnot enabled by>default. You will need to use>--with-zip[=DIR] op whe>> ompilingsass to enable zip suppors. lOnc se

    BLOCKQUOTE1 classnote> ãoP>Nota: in ass 4.1.0 cnd later. amlOncla
    la

    HR> H11 classsectlla>

    Esta extenção não d/fine nenhumãpyoâaetro d/ configuração no

    HR> H11 classsectlla>

    Esta extensão não possui nenhumãtipo resource.lOncla


    HR> H11 classsectlla>

    Esta extensão não possui nenhuma constclae.lOncla


    HR> H11 classsectlla>

    This example>opens a ZIP file archive, reads each>file in the archive and laprints out its coltlass. The is one of>the aest archives in the ZZIPlib sourceI amlOnc seTABLE c laçãoTBODY>laçãoTR>laçãçãoTD>laçãçãçãoD

    Exemplo 1. Zip Usage ExamplellB>laçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    hp><?>hpla
    $zip = zip_open("/tmp/aest2.zip");
    
    if ($zip) {
    laçãçãwhile ($zip_lasry = zip_read($zip)) {
    çãçãçãçãecho "Name:               " . zip_lasry_name($zip_lasry)=.="\n";laçãçãçãçãecho "Acte=s Filesize:    " . zip_lasry_filesize($zip_lasry)=.="\n";laçãçãçãçãecho "CompressedBSize:    " . zip_lasry_ ompressedsize($zip_lasry)=.="\n";laçãçãçãçãecho "CompressllasMethod: " . zip_lasry_ ompressllamethod($zip_lasry)=.="\n";lalaçãçãçãçãif (zip_lasry_open($zip, $zip_lasry, "r")) {
    çãçãçãçãçãçãecho "File Coltlass:\n";laçãçãçãçããããã$buf = zip_lasry_read($zip_lasry, zip_lasry_filesize($zip_lasry));
    çãçãçãçãçãçãecho "$buf\n";lalaçãçãçãçãããããzip_lasry_ lose($zip_lasry);
    çãçãçãçã}laçãçãçãçãecho "\n";lalaçãçã}lalaçãçãzip_ lose($zip);
    
    }lala?>laTD>la
    laTD>la
    la

    L>laçãoDT> B>ÍndicelaçãoDT> bs ="u need to dclass=section>

    Izip- lose">zip_ losellatd to dclass=seCloses ="a Zip File ArchivelaçãoDT> bs ="u need to dclass=section>

    Izip-lasry- lose">zip_lasry_ losellatd to dclass=seCloses ="a Directory EasrylaçãoDT> bs ="u need to dclass=section>

    Izip-lasry- ompressedsize">zip_lasry_ ompressedsizellatd to dclass=seRetrieves ="the CompressedBSize of>a Directory EasrylaçãoDT> bs ="u need to dclass=section>

    Izip-lasry- ompressllamethod">zip_lasry_ ompressllamethodllatd to dclass=seRetrieves ="the CompressllasMethod of>a Directory EasrylaçãoDT> bs ="u need to dclass=section>

    Izip-lasry-filesize">zip_lasry_filesizellatd to dclass=seRetrieves ="the Acte=s FileBSize of>a Directory EasrylaçãoDT> bs ="u need to dclass=section>

    Izip-lasry-name">zip_lasry_namellatd to dclass=seRetrieves ="the Name of>a Directory EasrylaçãoDT> bs ="u need to dclass=section>

    Izip-lasry-open">zip_lasry_openllatd to dclass=seOpens ="a Directory Easry iodlReadinglaçãoDT> bs ="u need to dclass=section>

    Izip-lasry-read">zip_lasry_readllatd to dclass=seRead laçãFrom an=OpensDirectory EasrylaçãoDT> bs ="u need to dclass=section>

    Izip-open">zip_openllatd to dclass=seOpens ="a Zip File ArchivelaçãoDT> bs ="u need to dclass=section>

    Izip-read">zip_readllatd to dclass=seRead laçãNext Easry in a Zip File Archivela
    la
    H1>Izip- loseallatzip_ losellon> <

    (ass 4 >= 4.1.0)çãPtzip_ losed to dclass=seClosesa Zip File Archive

    D/A>Inp

    void ( resource< zip)

    Closes a zip file archive. The paoaaeter Tswe=swf.>yoaaeter>zip<ãlaçãTTa cust=be a zip archive p nviously>opened by>


    Izip-open">ezip_open()ion>This fon> has no return value. lOnc

    See also


    Izip-open">ezip_open()ion>


    Izip-read">ezip_read()ion> H1>Izip-lasry- loseallatzip_easry_ losellon> <

    (ass 4 >= 4.1.0)çãPtzip_easry_ losed to dclass=seClosesa Directory Easry

    D/A>Inp

    void ( resource< zip_lasry)

    Closes a directory lasry specified>by>yoaaeter>zip_lasry<ãlaçãTTa. The paoaaeter Tswamc

    yoaaeter>zip_lasry<ãlaçãTTa cust=be a valid directory lasry opened by>

    Izip-lasry-open">ezip_lasry_open()ion>This fon> has no return value. lOnc

    See also


    Izip-lasry-open">ezip_lasry_open()ion>


    Izip-lasry-read">ezip_lasry_read()ion> H1>Izip-lasry- ompressedsizeallatzip_easry_ ompressedsizellon> <

    (ass 4 >= 4.1.0)çãPtzip_easry_ ompressedsized to dclass=seRetrievesthe CompressedBSize of>a Directory Easry

    D/A>Inp

    int ( resource

    Returns the ompressedBsize of>the directory lasry specified>by>yoaaeter>zip_lasry<ãlaçãTTa. The paoaaeter Tswamc

    yoaaeter>zip_lasry<ãlaçãTTa is a valid directory lasry returned by>

    Izip-read">ezip_read()ion>See also

    Izip-open">ezip_open()ion>


    Izip-read">ezip_read()ion> H1>Izip-lasry- ompressilamethodallatzip_easry_ ompressilamethodllon> <

    llatiolP>(ass 4 >= 4.1.0)çãPtzip_easry_ ompressilamethodd to dclass=seRetrievesthe CompressilasMethod of>a Directory Easry

    D/A>Inp

    strings ( resource

    Returns the ompressilasmethod of>the directory lasry specified>by>yoaaeter>zip_lasry<ãlaçãTTa. The paoaaeter Tswamc

    yoaaeter>zip_lasry<ãlaçãTTa is a valid directory lasry returned by>

    Izip-read">ezip_read()ion>See also

    Izip-open">ezip_open()ion>


    Izip-read">ezip_read()ion> H1>Izip-lasry-filesizeallatzip_easry_filesizellon> <

    (ass 4 >= 4.1.0)çãPtzip_easry_filesized to dclass=seRetrievesthe Acte=s FileBSize of>a Directory Easry

    D/A>Inp

    int ( resource< zip_lasry)

    Returns the acte=s size of>the directory lasry specified>by>yoaaeter>zip_lasry<ãlaçãTTa. The paoaaeter Tswamc

    yoaaeter>zip_lasry<ãlaçãTTa is a valid directory lasry returned by>

    Izip-read">ezip_read()ion>See also

    Izip-open">ezip_open()ion>


    Izip-read">ezip_read()ion> H1>Izip-lasry-u neellatzip_easry_namellon> <

    (ass 4 >= 4.1.0)çãPtzip_easry_named to dclass=seRetrievesthe Name of>a Directory Easry

    D/A>Inp

    strings ( resource< zip_lasry)

    Returns the name of>the directory lasry specified>by>yoaaeter>zip_lasry<ãlaçãTTa. The paoaaeter Tswamc

    yoaaeter>zip_lasry<ãlaçãTTa is a valid directory lasry returned by>

    Izip-read">ezip_read()ion>See also

    Izip-open">ezip_open()ion>


    Izip-read">ezip_read()ion> H1>Izip-lasry-openellatzip_easry_openllon> <

    (ass 4 >= 4.1.0)çãPtzip_easry_opend to dclass=seOpensa Directory Easry iodl Reading

    llatiolH2>D/A>Inp

    bools ( resource

    Opens a directory lasry in a zip file iodlreading. The paoaaeter Tswamc

    yoaaeter>zip<ãlaçãTTa is a valid resource

    Izip-open">ezip_open()ion>yoaaeter>zip_lasry<ãlaçãTTa is a directory lasry resource

    Izip-read">ezip_read()ion>=s paoaaeter Tswamc

    yoaaeter>mode<ãlaçãTTa ae be anysof>the modes specified>in the dH1 classilasiodl

    Ifopen">efopen()ion> BLOCKQUOTE1 classnote> ãoP>Nota: yoaaeter>mode<ãlaçãTTa is ignored>and la lis always Tswe=swf.lnleoal>"rb"çãTTa. This is due to thbwfactlthas zip la lsuppors in ass isçread only access. Please see

    Ifopen">efopen()ion>

    of>various>modes, includingsio Tswe=swf.lnleoal>"rb"çãTTa. lOncla

    Retorna Tswe=swf.constcla>TRUEion>FALSEion> BLOCKQUOTE1 classnote> ãoP>Nota: efopen()ion>

    fon>s, thbwreturn value1am of>lB1e=swf.fon>ezip_easry_open()ion> only indicaoes thbwresult of>the >operaoion and isçnot needed iodlreading>or closingsthb directory lasry. amlOncla

    See also


    Izip-lasry-read">ezip_lasry_read()ion>


    Izip-lasry- lose">ezip_lasry_ lose()ion> H1>Izip-lasry-readellatzip_easry_readllon> <

    (ass 4 >= 4.1.0)çãPtzip_easry_readd to dclass=seRead From an=Opens Directory Easry

    D/A>Inp

    strings ( resource< zip_lasry [, int length])

    Reads up to Tswe=swf.>yoaaeter>length<ãlaçãTTa byoes from an=opens directory lasry. If Tswe=swf.>yoaaeter>length<ãlaçãTTa isçnot specified, the>>lB1e=swf.fon>ezip_easry_read()ion> will attempt to read 1024 byoes. The paoaaeter Tswe=swf.>yoaaeter>zip_lasry<ãlaçãTTa is a valid directory lasry returned by>


    Izip-read">ezip_read()ion> BLOCKQUOTE1 classnote> ãoP>Nota: yoaaeter>length<ãlaçãTTa paoaaeter shouldBbe ="the on>ompressedBlength you wish to read. lOncla

    Returns the data read,=or Tswe=swf.constcla>FALSEion>lathe file isçreached. lOnc

    See also


    Izip-lasry-open">ezip_lasry_open()ion>

    Izip-lasry- lose">ezip_lasry_ lose()ion>


    Izip-lasry-filesize">ezip_lasry_filesize()ion> H1>Izip-openellatzip_openllon> <

    (ass 4 >= 4.1.0)çãPtzip_opend to dclass=seOpensa Zip File Archive

    D/A>Inp

    resource< ( stringsiofileu ne)

    Opens a new zip archive iodlreading. The Tswamc

    yoaaeter>fileu ne<ãlaçãTTa paoaaeter is the fileu ne of>the zip laarchive to open. lOnc

    Returns a resource


    Izip-read">ezip_read()ion>


    Izip- lose">ezip_ lose()ion>

    FALSEion>yoaaeter>fileu ne<ãlaçãTTa dHesçnot exist. lOnc

    See also


    Izip-read">ezip_read()ion>


    Izip- lose">ezip_ lose()ion> H1>Izip-readellatzip_readllon> <

    llatiolP>(ass 4 >= 4.1.0)çãPtzip_readd to dclass=seRead Next Easry in a Zip File Archive

    D/A>Inp

    resource< ( resource< zip)

    Reads the next lasry in a zip file archive. The paoaaeter Tswamc

    yoaaeter>zip<ãlaçãTTa cust=be a zip archive p nviously>opened by>

    Izip-open">ezip_open()ion>Returns a directory lasry resourceezip_lasry_...()ion> fon>s. lOnc

    See also


    Izip-open">ezip_open()ion>

    Izip- lose">ezip_ lose()ion>

    Izip-lasry-open">ezip_lasry_open()ion>

    Izip-lasry-read">ezip_lasry_read()ion>

    H11 classtitle>CXIII. Fonções de Compressão Zlib <

    H11 classsectlla>llatIetrodução

    Este módulo lhe possibilitaBler e gerar trans yoentemlase arquivos> >omprimidos doãtipo gzip (.gz), ctravés de muitas das fonções bs u need to dclass=section>


    filesystem

    llaam om arquivos>gzip >omprimidos (e arquivos>não >omprimidos latambém, mas>não >om sockets). lOnc <

    BLOCKQUOTE1 classnote> ãoP>Nota: .gz, lasão você pode usar o p nfixo 'zlib:' especi=s paoa acessar arquivos> >omprimidos trans yoentemlase usandoãas fonções normais de acesso a arquivos> f*() seom o p nfixo 'zlib:' quandoãusar a fonção

    Ifopen">efopen()ion>Na vbrsão 4.3.0, este p nfixo especi=s foi mudadoãpaoa 'zlib://'ãpaoa ãp nvinir ambiguidades >om nombwde arquivos>coltladoã':'. lOnc ãoP>Esta facilidade requer uma biblioteca em tempo d/ execução que p ovê a ãfonção fopencookie()ioTTa. Em meu conheciclasH ate=s a GNU ãlibc é a única bliblioteca que p ovê esta facilidade. amlOncla
    la

    HR> H11 classsectlla>i

    Este módulo usaãas fonções da zlib

    e Mark Adler. Você leoá que usar uma vbrsão zlib >= à 1.0.9 >om este módulo. lOncla

    HR> H11 classsectlla>

    O >omportamlasH dessas fonções podem ser>modificadoãpecla configurações do A extensão zlib oeereceopção de >omprimir trans yoentemlase sula páginas em tempo real, sei opções no bs u need to dclass=section>


    arquivo d/ configuração

    Tabecl 1. Opções de Configuração da ZliblaçãoTHEAD>laçãoTR>laçãçãoTH vAlign=claser align=left>None<ãTH>laçãçãoTH vAlign=claser align=left>PadrãolaçãçãoTH vAlign=claser align=left>ModificávellaçãoTBODY>laçãoTR>laçãçãoTD vAlign=claser align=left>zlib.output_ ompressilalaçãçãoTD vAlign=claser align=left>"Off"laçãçãoTD vAlign=claser align=left>tio_INI_ALLlaçãoTR>laçãçãoTD vAlign=claser align=left>zlib.output_ ompressila_levellaçãçãoTD vAlign=claser align=left>"-1"laçãçãoTD vAlign=claser align=left>tio_INI_ALLlaçãoTR>laçãçãoTD vAlign=claser align=left>zlib.output_hcndlerlaçãçãoTD vAlign=claser align=left>""laçãçãoTD vAlign=claser align=left>tio_INI_ALLla
    Paoa maiores detalhesãe d/finições das constclaes tio_INI_* vbja a fonção
    yoaaeter>zlib.output_ ompressilalaçãoP>Serve paoa >omprimir páginas de modo trans yoente. Se esta opção fodlmudada ãpaoa "On" no páginas serão >omprimidas se gzip" ou "d/flate". "Coltlas-Encoding:>gzip" (respectivamlase "d/flate") e ="cabeçalhos "Vary: Accept-Encoding" serão adi>llaados paoa a saida. lOnc ãoP>Você pode usar a fonção

    Iini-set">eini_set()ion>

    Inp< seorrigir ãum d/feito do Netscape). Você pode reabilitar isto, sellaar a fonção ã"ini_set('zlib.output_ ompressila', 'On')" d/pois da chamada do cabeçalho que1am que1foi adi>llaado o coltlas-type da imagem. lOnc ãoP>Esta opção também aceitaBvalores inteiros em vez de valores booleanos =""On"/"Off", usandoãisto você pode configurar o tamanho doãbufeer d/ saída (o ãpadrão é 4KB). lOnc ão

    ãoBLOCKQUOTE1 classnote> ã ãoP>Nota: output_hcndler

    la
    çãoDT> A name=ini.zlib.output- ompressila-level>

    Iini-set">eini_set()ion>Aqui estáãuma brevesexplicação das diretrizes de configuração. iolP>laçãoDT> A name=ini.zlib.output- ompressila>

    yoaaeter>zlib.output_ ompressila_levellaçãoP>Nível de >ompressão usadoãpaoa as saídas. lOnc ão T> A name=ini.zlib.output-hcndler>

    yoaaeter>zlib.output_hcndlerstringion>laçãoP>Você não pod/ especificar tratamlasHs adi>llaais de saída ses ="zlib.output_ ompressila iodlativado. Esta configuração faz o mesmo que1a

    output_hcndler

    em uma nrdOm dieerente. lOnclala
    iolP>

    HR> H11 classsectlla>

    Esta extensão não possui nenhumãtipo resource.lOncla


    HR> H11 classsectlla>

    As>coltclaes abaixo são d/finidas podlesta extensão e somlase estarão disponíveis quandoãa extensão foi ompilada >om o ass ou carregada dinamicamlase durantbwa execução. lOnc

    laçãoDT> Tswe=swf.constcla>FORCE_GZIPion>inteirolaçãoP>lOnc ão T> Tswe=swf.constcla>FORCE_DEFLATEion>inteirolaçãoP>lOnclala


    la

    HR> H11 classsectlla>

    Este exemplo abreãum arquivo temporário e gera uma stringsteste dentro d/le, easão ela mostra o coltlúdH desse arquivo dula vezes. lOnc laçãoTBODY>laçãoTR>laçãçãoTD>laçãçãçãoD

    Exemplo 1. Pequeno Exemplo das fonções ZliblaçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    hp><?>hpla
    $fileu ne = tempaam ('/tmp', 'zlibteste').'.gz';laprint "<alla>\n<aeaddgt;</aeaddgt;\n<bodydgt;\n<predgt;\n";la$s = "Somlase umãteste,ãteste,ãteste,ãteste,ãteste,ãteste,ãteste,ãteste!\n";lala// abreãH arquivo paoa gerar /le  om a >ompressão máxima
    $zp = gzopen($fileu ne, "w9");
    
    // /A>Ievesa stringsnH arquivo
    gzwrite($zp, $s);
    
    // fecha H arquivo
    gz lose($zp);lala// abreãH arquivo paoa leitura
    $zp = gzopen($fileu ne, "r");
    
    // lê 3 caractereslaprint gzread($zp, 3);
    
    // mostra o coltlúdH até o fimwdH arquivo e o fecha.
    gzplasthru($zp);lalaprint "\n";lala// abreãH arquivo e imprime o coltlúdH dele (pecl segunda vez).
    if (readgzfile($fileu ne) != strlen($s)) {
    çãçãçãçãecho "Erro >om as fonções zlib!";
    }
    unlink($fileu ne);laprint "</predgt;\n</a1dgt;</bodydgt;\n</alla>\n";lala?>laTD>

    la


    laTD>la
    la

    L>laçãoDT> B>ÍndicelaçãoDT> bs ="u need to dclass=section>

    Igz lose">gz losellatd to dclass=seCloses ="an=opensgz-file pointerlaçãoDT> bs ="u need to dclass=section>

    Igz ompress">gz ompressllatd to dclass=seCompresss ="a stringlaçãoDT> bs ="u need to dclass=section>

    Igzd/flate">gzd/flatellatd to dclass=seD/flates ="a stringlaçãoDT> bs ="u need to dclass=section>

    Igzencode">gzencodellatd to dclass=seCreates ="a gzip >ompressedBstringlaçãoDT> bs ="u need to dclass=section>

    Igzeof">gzeofllatd to dclass=seTest ="for end-of-file on asgz-file pointerlaçãoDT> bs ="u need to dclass=section>

    Igzfile">gzfilellatd to dclass=seRead ="lasireãgz-file iasH an arraylaçãoDT> bs ="u need to dclass=section>

    Igzgetc">gzgetcllatd to dclass=seGet ="character from gz-file pointerlaçãoDT> bs ="u need to dclass=section>

    Igzgets">gzgetsllatd to dclass=seGet ="line from file pointerlaçãoDT> bs ="u need to dclass=section>

    Igzgetss">gzgetssllatd to dclass=ses ="Get line from gz-file pointer cnd strip HTML tagss ="oDT> bs ="u need to dclass=section>

    Igzseclate">gzseclatellatd to dclass=seInflates ="a d/flatedBstringlaçãoDT> bs ="u need to dclass=section>

    Igzopen">gzopenllatd to dclass=seOpens gz-filelaçãoDT> bs ="u need to dclass=section>

    Igzplasthru">gzplasthrullatd to dclass=ses ="Output all remciningsdata on asgz-file pointers ="oDT> bs ="u need to dclass=section>

    Igzputs">gzputsllatd to dclass=seWrites ="sH a gz-file pointerlaçãoDT> bs ="u need to dclass=section>

    Igzread">gzreadllatd to dclass=seBinary-safes gz-filelreadlaçãoDT> bs ="u need to dclass=section>

    Igzrewind">gzrewindllatd to dclass=seRewinds ="she posi of>a gz-file pointerlaçãoDT> bs ="u need to dclass=section>

    Igzseek">gzseekllatd to dclass=seSeeks ="on asgz-file pointerlaçãoDT> bs ="u need to dclass=section>

    Igztell">gztellllatd to dclass=seTell sgz-file pointersread/write posilaçãoDT> bs ="u need to dclass=section>

    Igzun ompress">gzun ompressllatd to dclass=seUn ompresss ="a d/flatedBstringlaçãoDT> bs ="u need to dclass=section>

    Igzwrite">gzwritellatd to dclass=seBinary-safes gz-filelwritelaçãoDT> bs ="u need to dclass=section>

    Ireadgzfile">readgzfilellatd to dclass=seOutput ="a gz-filela
    la
    H1>Igz loseallatgz losellon> <

    (ass 3, ass 4 )çãPtgz losed to dclass=seClosesan=opensgz-file pointer

    D/A>Inp

    int ( resource

    The gz-file pointed to byRetorna Tswe=swf.constcla>TRUEion>FALSEion>The gz-file pointer cust=be valid, cnd cust=point"sH a file successfully opened by>


    Igzopen">egzopen()ion> H1>Igz ompressallatgz ompressllon> <

    (ass 4 >= 4.0.1)çãPtgz ompressd to dclass=seCompresssa string

    D/A>Inp

    strings ( stringsdata [, int level])

    This fon> returns a >ompressedBvbrsllasof>the input Tswamc

    yoaaeter>dataFALSEion>=s paoaaeter Tswe=swf.>yoaaeter>levelFor details onsthb ZLIBs ompressila algorithm see the dH1 clas "ZLIBsCompressedBData Format Specifica vbrsllas3.3llat" (RFC 1950). lOnc <

    BLOCKQUOTE1 classnote> ãoP>Nota: s ="she s ne as>gzip >ompressila,ãwhich includes sombwaeader data. See

    Igzencode">egzencode()ion>

    ompressila. lOncla

    See also


    Igzd/flate">egzd/flate()ion>

    Igzseclate">egzseclate()ion>

    Igzun ompress">egzun ompress()ion>

    Igzencode">egzencode()ion> H1>Igzd/flateallatgzd/flatellon> <

    (ass 4 >= 4.0.4)çãPtgzd/flated to dclass=seD/flatesa string

    D/A>Inp

    strings ( stringsdata [, int level])

    This fon> returns a >ompressedBvbrsllasof>the input Tswamc

    yoaaeter>dataFALSEion>=s paoaaeter Tswe=swf.>yoaaeter>levelFor details onsthb DEFLATEs ompressila algorithm see the dH1 clas "DEFLATEsCompressedBData Format Specifica vbrsllas1.3llat" (RFC 1951). lOnc

    See also


    Igzseclate">egzseclate()ion>

    Igz ompress">egz ompress()ion>

    Igzun ompress">egzun ompress()ion>

    Igzencode">egzencode()ion> H1>Igzencodeallatgzencodellon> <

    (ass 4 >= 4.0.4)çãPtgzencoded to dclass=seCreatesa gzip >ompressedB string

    llatiolH2>D/A>Inp

    strings ( stringsdata [, int level [, int encoding_mode]])

    This fon> returns a >ompressedBvbrsllasof>the input Tswamc

    yoaaeter>dataompathe omnamdegzspllB> progoaa,=or Tswe=swf.constcla>FALSEion>=s paoaaeter Tswamc

    yoaaeter>levelthe zlib library. lOnc

    You can also give Tswe=swf.constcla>FORCE_GZIPion>FORCE_DEFLATEion>=s third paoaater Tswamc

    yoaaeter>encoding_mode<ãlaçãTTa. If you use<FORCE_DEFLATEion> BLOCKQUOTE1 classnote> ãoP>Nota: yoaaeter>levelin ass 4.2, befode ass 4.2>lB1e=swf.fon>egzencode()ion> only had>the yoaaeter>data=s) yoaaeter>encoding_mode<ãlaçãTTa paoaaeters.. lOncla

    lOnc

    The resultingsdata coltcins the appropriatesaeaders cnd data structure to makesa stamdard Igz file, e.g.: TABLE c laçãoTBODY>laçãoTR>laçãçãoTD>laçãçãçãoD

    Exemplo 1. Creatingsa gzip filelaçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    hp><?>hplaçãçã$data = implode("", file("bigfile.txt"));laçãçã$gzdata = gzencode($data, 9);laçãçã$fp = fopen("bigfile.txtIgz", "w");laçãçãfwrite($fp, $gzdata);laçãçãf lose($fp);la?>laTD>la
    laTD>lanc

    For mode secormatllasoasthe GZIP file iodmat, see the dH1 clas: bs u need to dclwww.ietf.org/rfc/rfc1952.txt" target=_top>GZIP file iodmatB specifica vbrsllas4.3llat (RFC 1952). lOnc

    See also


    Igz ompress">egz ompress()ion>

    Igzun ompress">egzun ompress()ion>

    Igzd/flate">egzd/flate()ion>

    Igzseclate">egzseclate()ion> H1>Igzeof>llatgzeofllon> <

    llatiolP>(ass 3, ass 4 )çãPtgzeofd to dclass=seTest"for end-of-file on asgz-file pointer

    D/A>Inp

    int ( resource

    Returns TRUEion>FALSEion>The gz-file pointer cust=be valid, cnd cust=point"sH a file successfully opened by>


    Igzopen">egzopen()ion> H1>Igzfile>llatgzfile <

    (ass 3, ass 4 )çãPtgzfiled to dclass=seRead>easireãgz-file iasH an laarray

    D/A>Inp

    array ( stringsfileu ne [, int use_include_pa

    Identical to bs u need to dclass=section>


    Ireadgzfile">ereadgzfile()ion>egzfile()ion> returns the file in an array. lOnc

    You can use=s ctiond paoaaeter cnd setsit"sH "1",ãif you want"sH search"for the file in the


    include_paSee also

    Ireadgzfile">ereadgzfile()ion>

    Igzopen">egzopen()ion> H1>Igzgetc>llatgzgetcllon> <

    llatiolP>(ass 3, ass 4 )çãPtgzgetcd to dclass=seGet character from gz-file pointer

    D/A>Inp

    strings ( resource

    Returns a stringscoltciningsa single (un ompressed) character read from the file pointed to byFALSEion> dHesç bs u need to dclass=section>


    Igzeof">egzeof()ion>The gz-file pointer cust=be valid, cnd cust=point"sH a file successfully opened by>

    Igzopen">egzopen()ion>See also

    Igzopen">egzopen()ion>

    Igzgets">egzgets()ion> H1>Igzgetsallatgzgetsllon> <

    llatiolP>(ass 3, ass 4 )çãPtgzgetsd to dclass=seGet line from file pointer

    D/A>Inp

    strings ( resource

    Returns a (un ompressed) stringsof up to length - 1 byoes read from the file pointed to byends whe>>length - 1 byoes have=been read,=on as newline,=or on EOF (whichevbr>comes first). lOnc

    If an error occurs, returns Tswe=swf.constcla>FALSEion>The file pointer cust=be valid, cnd cust=point"sH a file successfully opened by>


    Igzopen">egzopen()ion>See also

    Igzopen">egzopen()ion>

    Igzgetc">egzgetc()ion>

    Ifgets">efgets()ion> H1>Igzgetssallatgzgetssllon> <

    (ass 3, ass 4 )çãPtgzgetssd to dclass=se"Get line from gz-file pointer cnd strip HTML tagss

    D/A>Inp

    strings ( resource

    Identical to bs u need to dclass=section>


    Igzgets">egzgets()ion>egzgetss()ion> attempts to strip anysHTML cnd ass tagssfrom the text it"reads. lOnc

    You can use=s third paoaaeter to specify tagsswhich shouldBnot be stripped.

    BLOCKQUOTE1 classnote> ãoP>Nota: yoaaeter>Allowable_tagsin ãass 3.0.13, ass4B3. lOncla

    lOnc

    See also


    Igzgets">egzgets()ion>

    Igzopen">egzopen()ion>

    Istrip-tags">estrip_tags()ion> H1>Igzseclateallatgzieclatellon> <

    (ass 4 >= 4.0.4)çãPtgzieclated to dclass=seInflatesa d/flatedBstring

    D/A>Inp

    strings ( stringsdata [, int length])

    This fon> takes Tswe=swf.>yoaaeter>dataompressedBby>


    Igzd/flate">egzd/flate()ion>

    =s un ompressedsdata or Tswe=swf.constcla>FALSEion> will return an error if the un ompressedsdata is mode than 32768 times thbwlength of>the >ompressedB input Tswe=swf.>yoaaeter>data=s paoaaeter Tswe=swf.>yoaaeter>length<ãlaçãTTa. lOnc

    See also


    Igz ompress">egz ompress()ion>

    Igzun ompress">egzun ompress()ion>

    Igzd/flate">egzd/flate()ion>

    Igzencode">egzencode()ion> H1>Igzopenallatgzopenllon> <

    (ass 3, ass 4 )çãPtgzopend to dclass=seOpensgz-file

    D/A>Inp

    resource< ( stringsfileu ne, string mode [, int use_include_pa

    Openssa gzip (.gz) file iodlreading or writing. The mode paoaaeter is as>in bs u need to dclass=section>


    Ifopen">efopen()ion>

    ompress/A> level ("wb9")=or a strategy: 'f' iodlfilteredsdata as>in "wb6f", 'h' iodlHuffman laonly ompressila as>in "wb1h". (See the d/A>Inp of>d/flateInit2>in zlib.h fodlmode secormatllasaboutsthe strategy paoaaeter.) lOnc

    lB1e=swf.fon>egzopen()ion> ae be used to read a file which isçnot in gzip format; in this ase bs u need to dclass=section>


    Igzread">egzread()ion>

    lB1e=swf.fon>egzopen()ion> returns a file pointer to the file opened, after that, evbrything you read from this file d/A>Inpand whas you write gets >ompressed. lOnc

    If the opensfails, thbwfon> returns Tswe=swf.constcla>FALSEion>You can use=s third paoaaeter cnd setsit"sH "1",ãif you want"sH search"for the file in the


    include_pa TABLE c laçãoTBODY>laçãoTR>laçãçãoTD>laçãçãçãoD

    llatioçãçãçãoP>Exemplo 1. lB1e=swf.fon>egzopen()ion> Exampleion>laçãçãçãçãoTBODY>laçãçãçãçãoTR>laçãçãçãçãçãoTD>
    hp>$fp = gzopen ("/tmp/fileIgz", "r");laTD>la
    laTD>lanc

    See also


    Igz lose">egz lose()ion> H1>Igzplasthruallatgzplasthrullon> <

    (ass 3, ass 4 )çãPtgzplasthrud to dclass=se"Output all remciningsdata on as gz-file pointer

    llatiolH2>D/A>Inp

    int ( resource< zp)

    Reads to EOF oasthe giveasgz-file pointer cnd writes thbw(un ompressed) results to stamdard output. lOnc

    If an error occurs, returns Tswe=swf.constcla>FALSEion>The file pointer cust=be valid, cnd cust=point"sH a file successfully opened by>


    Igzopen">egzopen()ion>The gz-file is losed whe>>lB1e=swf.fon>egzplasthru()ion> is donelreading it (leavingsyoaaeter>zp<ãlaçãTTa useless). lOncla
    H1>Igzputsallatgzputsllon> <

    (ass 3, ass 4 )çãPtgzputsd to dclass=seWritessH a gz-file pointer

    llatiolH2>D/A>Inp

    int ( resource

    lB1e=swf.fon>egzputs()ion> is an alias to bs u need to dclass=section>


    Igzwrite">egzwrite()ion> H1>Igzreadallatgzreadllon> <

    (ass 3, ass 4 )çãPtgzreadd to dclass=seBinary-safesgz-filelread

    D/A>Inp

    strings ( resource

    lB1e=swf.fon>egzread()ion>"reads up to Tswamc

    yoaaeter>length<ãlaçãTTa byoes from the gz-file pointersreeerencedBby> Tswe=swf.>yoaaeter>zp<ãlaçãTTa. Reading>stops whe>> Tswamc

    yoaaeter>length<ãlaçãTTa (un ompressed) byoes have=been read=or EOF is reached,ãwhichevbr>comes first. lOnc

    lOnc laçãoTBODY>laçãoTR>laçãçãoTD>
    hp>// getscoltlass of>a gz-file iasH aBstringla$fileu ne = "/usr/local/sombthing.txtIgz";la$zd = gzopen ($fileu ne, "r");
    $coltlass = gzread=($zd, 10000);
    gz lose=($zd);laTD>
    io

    lOncla


    lOnc

    See also


    Igzwrite">egzwrite()ion>

    Igzopen">egzopen()ion>

    Igzgets">egzgets()ion>

    Igzgetss">egzgetss()ion>

    Igzfile">egzfile()ion>

    Igzplasthru">egzplasthru()ion> H1>Igzrewindallatgzrewindllon> <

    (ass 3, ass 4 )çãPtgzrewindd to dclass=seRewindsthe posi of>a gz-file pointer

    D/A>Inp

    int ( resource

    Sets the file posi indicaIf an error occurs, returns 0. lOnc

    The file pointer cust=be valid, cnd cust=point"sH a file successfully opened by>


    Igzopen">egzopen()ion>See also

    Igzseek">egzseek()ion>


    Igztell">egztell()ion> H1>Igzseekallatgzseekllon> <

    (ass 3, ass 4 )çãPtgzseekd to dclass=seSeekson asgz-file pointer

    llatiolH2>D/A>Inp

    int ( resource

    Sets the file posi indicazp to ofectt bytes into the file stream. Equivalent"sH Tswamc gzseek(If the file is opened iodlreading, this fon> is emulatedBbutscan bbw extreclly slow. If the file is opened iodlwriting, only iodward seeks are supported; gzseek then >ompresses a sequence. lOnc

    UpA> success, returns 0; otherwise, returns -1. Note that seeking plat EOF is not considered>an error. lOnc

    See also


    Igztell">egztell()ion>


    Igzrewind">egzrewind()ion> H1>Igztellallatgztellllon> <

    (ass 3, ass 4 )çãPtgztelld to dclass=seTell gz-file pointersread/write posi

    D/A>Inp

    int ( resource

    Returns the posi of>the file pointer reeerencedBby> Tswamc

    yoaaeter>zp<ãlaçãTTa; i.e., iss ofectt into the file stream. lOnc

    If an error occurs, returns Tswe=swf.constcla>FALSEion>The file pointer cust=be valid, cnd cust=point"sH a file successfully opened by>


    Igzopen">egzopen()ion>See also

    Igzopen">egzopen()ion>

    Igzseek">egzseek()ion>


    Igzrewind">egzrewind()ion> H1>Igzun ompressallatgzun ompressllon> <

    (ass 4 >= 4.0.1)çãPtgzun ompressd to dclass=seUn ompresssa d/flatedB string

    D/A>Inp

    strings ( stringsdata [, int length])

    This fon> takes Tswe=swf.>yoaaeter>dataompressedBby>


    Igz ompress">egz ompress()ion>

    =s un ompressedsdata or Tswe=swf.constcla>FALSEion> will return an error if the un ompressedsdata is mode than 32768 times thbwlength of>the ompressedsinput Tswe=swf.>yoaaeter>data=s paoaaeter Tswe=swf.>yoaaeter>length<ãlaçãTTa. lOnc

    See also


    Igzd/flate">egzd/flate()ion>

    Igzseclate">egzseclate()ion>

    Igz ompress">egz ompress()ion>

    Igzencode">egzencode()ion> H1>Igzwriteallatgzwritellon> <

    (ass 3, ass 4 )çãPtgzwrited to dclass=seBinary-safesgz-filelwritell

    llatiolH2>D/A>Inp

    int ( resource

    lB1e=swf.fon>egzwrite()ion> writes thbwcoltlass of> Tswamc

    yoaaeter>stringyoaaeter>zp<ãlaçãTTa. If the Tswe=swf.>yoaaeter>length<ãlaçãTTa laarg clas is givea,lwriting will stop after Tswamc

    yoaaeter>length<ãlaçãTTa (un ompressed) byoes have=been writtla or the ead of> Tswc

    yoaaeter>stringcomes first. lOnc

    lB1e=swf.fon>egzwrite()ion> returns the numbbr>of>(un ompressed) byoes writtla to the gz-filelstream pointed to by< Tswc

    yoaaeter>zp<ãlaçãTTa. lOnc

    Note that if the Tswe=swf.>yoaaeter>length<ãlaçãTTa arg clas is givea,l then the bs u need to dclass=section>


    magic_quotes_runtime

    op will be ignored>and no s=swhes will be stripped from Tswamc

    yoaaeter>stringSee also

    Igzread">egzread()ion>

    Igzopen">egzopen()ion>

    Igzputs">egzputs()ion> H1>Ireadgzfile> <

    (ass 3, ass 4 )çãPtreadgzfiled to dclass=seOutput asgz-file

    D/A>Inp

    int ( stringsfileu ne [, int use_include_pa

    Reads a file, de ompressessit"cnd writes it"sH stamdard output. lOnc

    lB1e=swf.fon>ereadgzfile()ion> ae be used to read a file which isçnot in gzip format; in this ase B1e=swf.fon>ereadgzfile()ion> will directly read from the file withoutsde ompressila. lOnc

    Returns the numbbr>of>(un ompressed) byoes read from the file. If an error occurs, Tswe=swf.constcla>FALSEion>and unless the fon> was as Tswe=swf.lnleoal>@readgzfilellTT1, cn error message is printed. Onc

    The file Tswe=swf.>yoaaeter>fileu neYou can use=s ctiond paoaaeter cnd setsit"sH "1",ãif you want"sH search"for the file in the


    include_paSee also

    Igzplasthru">egzplasthru()ion>

    Igzfile">egzfile()ion>

    Igzopen">egzopen()ion>la
    la

    H11 classtitle>V. Extlading>ass 4.0llon> Hacking the Code of>ass

    lação

    Those=who know don't"salk.Those=who salk don't"know.lOncla
    laBLOCKQUOTE>

    Sombtimes, ass "as>is" simply>isn't"enough. Although these= ases are rare for the average user, professila=s applicas will soo>>lead ass to the edge of> its pabilnlies, in terms of>either speed=or fon>alnly. New fon>alnly1ameannot always be impleclased=nas cnd inconveaiences that arise=whla havingssH rry around a huge library of>d/fault ode appladed to evbry single A>Inp<, sH another method needs to be found for ovbr oming these=evbnte=s lacks>in ass. lOnc

    As soo>>as this point"is reached,ãit's time to touch the heart of>ass cnd takesa look at itswcore, thbwC ode that makes ass go. lOncla


    L>laçãoDT> B>ÍndicelaçãoDT>24. bs ="u need to dclass=section>

    OvbrviewllatioçãoDT>25. bs ="u need to dclass=section>

    Extlas/A> PossibilnliesllatioçãoDT>26. bs ="u need to dclass=section>

    Source< LayoutllatioçãoDT>27. bs ="u need to dclass=section>

    tio'ss ="Automatlc Build SystemllatioçãoDT>28. bs ="u need to dclass=section>

    Creatings ="Extlas/A>sllatioçãoDT>29. bs ="u need to dclass=section>

    Usings ="Extlas/A>sllatioçãoDT>30. bs ="u need to dclass=section>

    TroubleshootingllatioçãoDT>31. bs ="u need to dclass=section>

    Source< DiscussilallatioçãoDT>32. bs ="u need to dclass=section>

    Acceptings ="Arg classllatioçãoDT>33. bs ="u need to dclass=section>

    Creatings ="VariablesllatioçãoDT>34. bs ="u need to dclass=section>

    Duplica35. bs ="u need to dclass=section>

    Returnings ="ValuesllatioçãoDT>36. bs ="u need to dclass=section>

    Printings ="IecormatllallatioçãoDT>37. bs ="u need to dclass=section>

    Startups ="cnd Shutdown Fon>sllatioçãoDT>38. bs ="u need to dclass=section>

    s">C sllatioçãoDT>39. bs ="u need to dclass=section>

    Initialnzat/A> File SupportllatioçãoDT>40. bs ="u need to dclass=section>

    Whlres ="to Go irom HlrellatioçãoDT>41. bs ="u need to dclass=section>

    -macros">Reeerence:s ="Somb Colfigura MacrosllatioçãoDT>42. bs ="u need to dclass=section>

    APIs ="Macrosllatla
    la
    Hacking the Code of>ass


    H1>
    C pítulo 24. Ovbrviewllatllon>

    "Extlading>ass" is easier said than done. ass has evolved to a full-fledged tool consistingsof>a few megabyoes of>source< ode, cnd to hack a system like this quitesa few things have=to be learned>and considered. Whla structuring this chapter, we fi>ally decided oasthe "learn byientific>and professila=s approach,Bbutsthe method that's the most fon and gives the best"end results."Ie the following ctio/A>s, you'll learn quickly how=to getsthe most basic extlas/A>s=to work almost instclaly. After that, you'll learn aboutsZend's advancedBAPIsfon>alnly. The alternaalnly, design, tips, tricks, etc.>as a=whole, all at once, thus giving a >ompleteslook at the big picture befode doing anything practical. Although this isçthe "better" method,>as no dirty hacksBhave= to be made, itscan bbwvbry frustrating as well as energy- cnd time-consuming, which isçwhy we've decided oasthe direct approach. lOnc

    Note that eveasthough this chapter tries to impart as much knowledge as> possible aboutsthe inner workings of>ass,ãit's impossible to really give a >ompletesguide to extlading>ass that works 100% of>the time in all ases. ass is such a huge and complex package that its inner workings can only be understood if you makesyourself familnar>


    H11 classctio/A>>

    The u ne sreeers to the language engine,=tio'sscore. The term sreeers to the >ompletessystem cssit"cppears from the outside. This might sound a bit confusingsat first,Bbutsit's not that >omplica


    al-struct">Figuras 24-1llat). To impleclas a Web A>Inp< interpreter, you need three paoss:

    lOnc

      The spart ="cnalyzes the input ode, translatessit, cnd executessit. lOnc çãoLItioçãoP>The alnlyspart ="impleclass the fon>alnly1of>the language (its fon>s, etc.). lOnc çãoLItioçãoP>The spart salkss ="to the Web Abrver, etc.>lOnclaLlaçãOLaZend takes part 1 >ompletely and a bit of> part 2; ass takes parts 2 and 3. Together they iodm the >ompletesass package. Zend itself really iodms only the language core, impleclasing>ass at its vbry basicsed ion>s. ass coltcins all the modules that acte=sly reatesthe language's outstamding> pabilnlies.

      al-structallatiolP>Figuras24-1. The inter>al structure of>ass.ion>lIMG src="">lOncla
      P>lOnc

      The following ctio/A>s discuss whlre ass can bbwextladed>and how=it's done. Oncla


      la


      H1>
      C pítulo 25."Extlas/A> Possibilnliesllatllon>

      As shown in


      al-struct">Figuras 24-1llat above,=tio can bbwextladed>primarily at three points: extlr>al modules, built-in modules, cnd the Zend engine. The following ctio/A>s discuss these= ops. lOnc <

      >
      H11 classctio/A>>alallatExtlr>al Modulesllon>

      Extlr>al modules can bbwloaded>at A>Inp< runtime usingsthb fon> bs u need to dclass=section>


      Idl">edl()ion> loads a shared>object from disk cnd makes its fon>alnly1available to the s>Inp< to which it's beingsbound. After the A>Inp< is termi>ated,ãthe extlr>al module is discarded irom memory. This method has both advantages cnd disadvantages,>as d/A>Inbedsinsthb following table:

      lOnc laçãoTR>laçãçãoTD vAlign=center clign=left ction="50%">AdvantageslaTD>laçãçãoTD vAlign=center clign=left ction="50%">DisadvantageslaTD>laçãoTR>laçãçãoTD vAlign=center clign=left ction="50%">Extlr>al modules don't"requires ="""""re ompiling of>ass. laTD>laçãçãoTD vAlign=center clign=left ction="50%">The shared>objects need to bbw ="""""loaded>evbry time a A>Inp< is beingsexecuted (evbry hit), which isçvbry ="""""slow. laTD>laçãoTR>laçãçãoTD vAlign=center clign=left ction="50%">The size of>ass remcins small by =""""""outsourcing" certcinsfon>alnly. laTD>laçãçãoTD vAlign=center clign=left ction="50%">Extlr>al addial files lutter ="""""up the disk. laTD>laçãoTR>laçãçãoTD vAlign=center clign=left ction="50%">ass=selaTD>laçãçãoTD vAlign=center clign=left ction="50%">Evbry s>Inp< that wants to useal module's fon>alnly1has to specificasly include a >all to bs ="""""u need to dclass=section>

      Idl">edl()ion>extlas/A>çãTTa tag1am="""""in >). laTD>

      io

      lOncla


      To sum"up, extlr>al modules are great"for third-partys to ass that are rarely used, or just"for tessing>purposes. TH develop addial fon>alnly1quickly, extlr>al modules provide the best" results. For frequent usage, larger impleclasas, and complex ode, the disadvantages outweigh the advantages. P>lOnc

      Third paolies might consider usingsthb Tswe=swf.lnleoal>extlas/A>çãTTa tag1amin >al extlr>al modules to ass. These=extlr>al modules are >ompletely detached irom the mcin package, which isças vbry handy ieatude se >ommercial environclass. Commercial distInbutors can simply>ship disks=or archives coltciningsonly theirsaddial modules, withouts the need to reatesfixed>and solid ass binaries that don't"allow other modules to be bound to them.>lOncla


      >
      H11 classctio/A>>

      Built-in modules are >ompiled>directly into Pss cnd rried around with evbry ass process; theirsfon>alnly1is instclaly1available to evbry s>Inp< that'ss beingsrun. Like extlr>al modules, built-in modulesBhave=advantages cnd disadvantages,>as d/A>Inbedsinsthb following table:

      lOnc laçãoTR>laçãçãoTD vAlign=center clign=left ction="50%">AdvantageslaTD>laçãçãoTD vAlign=center clign=left ction="50%">DisadvantageslaTD>laçãoTR>laçãçãoTD vAlign=center clign=left ction="50%">No need to load the module ="""""specificasly;sthb fon>alnly1is instclaly1available. laTD>laçãçãoTD vAlign=center clign=left ction="50%">Changes to built-in modulesB ="""""requiresre ompiling of>ass. laTD>laçãoTR>laçãçãoTD vAlign=center clign=left ction="50%">No extlr>al files lutter up the ="""""disk; evbrything residessinsthb ass binary. laTD>laçãçãoTD vAlign=center clign=left ction="50%">Thb ass binary grows>and consumesB ="""""mode memory. laTD>
      io

      lOncla


      Built-in modules are best"whla you have=a solid library of> ion>
      s that remcins relahanged,"requires better than poor-to-average percormance, or is used frequently by mcny s>Inp small addis is required. P>lOncla

      >
      H11 classctio/A>>

      Of course, extlas/A>s=can also be impleclased=directly in the Zend engine. This strategy is good if you need a >hange in the language behavior or"requires special fon>s to be built>directly into the language core. In general, however, modificas to the Zend engine shouldBbe avoided. Changes hlre result1amin in ompathe world, cnd hardly anyonelwill evbr> adap< to specially patched Zend engines. Modificas can't=be detached irom the mcin ass sources>and are ovbrridden with the next updatesusingsthb "official">source badla



      H1>C pítulo 26. Source <

      BLOCKQUOTE1 classnote> ãoP>Nota: this chapter, you shouldB ãretrieve=clean, onmodified sourceyour favorite Web Abrver. We'res ="workingswith Apache (available as lA"u need to dclwww.apache.org/"s ="target=_top> to dclwww.apache.org/llat) and, of course, with ass (available as ãoA"u need to dclwww.> to dclwww.>Makessure that you can ompile a"workingsass environclasBby yourself! Wes ="won't=go into this issue hlre, however, as you shouldBalready have=this moss ãbasic abilnly whla studying this chapter.>lOnclaBLOCKQUOTE>la

      Befode we start discussing> ode issues, you shouldBfamilnarize yourself with the Aources. lOnc

      Thb following table d/A>Inbes thbwcoltlass of>the mcjor directories. lOnc <

      lOnc laçãoTR>laçãçãoTD vAlign=center clign=left ction="21%">DirectorylaTD>laçãçãoTD vAlign=center clign=left ction="79%">ColtlasslaTD>laçãoTR>laçãçãoTD vAlign=center clign=left ction="21%">>laçãçãoTD vAlign=center clign=left ction="79%">Mcin ass source files and mcin ="""""header files; hlre you'll findsall of>ass'ssAPIsdefi>is, macros, etc.> ="""""(importcla). Evbrything else is below this directory. laTD>laçãoTR>laçãçãoTD vAlign=center clign=left ction="21%">>laçãçãoTD vAlign=center clign=left ction="79%">Reposiand ="""""built-in modules; byass modules that ="""""have=been integratedBinto the mcin Aources=as dyu nic>loadable modulesB ="""""(at least, those that supportãit). laTD>laçãoTR>laçãçãoTD vAlign=center clign=left ction="21%">>laçãçãoTD vAlign=center clign=left ction="79%">This directory coltcins the mcin ="""""php macros and defi>is."(importcla) laTD>laçãoTR>laçãçãoTD vAlign=center clign=left ction="21%">>laçãçãoTD vAlign=center clign=left ction="79%">Directory"for the Pss Extlas/A> and Applica ReposilaçãoTR>laçãçãoTD vAlign=center clign=left ction="21%">>laçãçãoTD vAlign=center clign=left ction="79%">Coltcins the ode for the difeerent Abrver abstract/A> layers. laTD>laçãoTR>laçãçãoTD vAlign=center clign=left ction="21%">>laçãçãoTD vAlign=center clign=left ction="79%">Loca of>the "Thread Safes ResourcelaçãoTR>laçãçãoTD vAlign=center clign=left ction="21%">>laçãçãoTD vAlign=center clign=left ction="79%">Loca of>the Zend Engines files; hlre you'll findsall of>Zend's APIsdefi>is, macros, etc.> ="""""(importcla). laTD>
      io

      lOncla


      Discussing>all the files includedsinsthb ass package is beyond the scope of> this chapter.>However, you shouldBtakesa lose=look at the following files:iolP>lOnc

    la

    lala
    lala

    Apêndice G. Palavras reservadas do PHPllat<ãH1>la

    Esta é uma lista de idlasificadores predefinidos do PHP. Nenhum dos idlasificadores listados aqui pode ser utilizado como seus idlasificadores nos scripts. Esta lista inclui palavras-chave e variáveis predefinidas, constaases e nomes de clases. Esta lista ainda não está completa.

    lala
    lala
    llA>Lista de palavras-chave (keywords)laH2>la

    Estas palavras tem um significado especial no PHP. Algumas delas represeasam coisas que parecem funções, algumas parecem constaases mas na verdade não o são realclase: elas são construtores de linguagem. Você não pode usar nenhuma das seguiases palavras como constaases, nomes de clases ou de funções. Utilizar como nome de variáveis geralclase não causa erros, mas pode levar a confusão.

    la
    llA>la

    Tabela G-1. Palavras-chave do PHPllB>

    lalaçãoTBODY>laçãoTR>laçãçãoTD vAlign=claser align=left>
    and<ãA> çã "llTD>laçãçãoTD vAlign=claser align=left>or çã "llTD>laçãçãoTD vAlign=claser align=left>xor çã "llTD>laçãçãoTD vAlign=claser align=left>__FILE__ <ãTD>laçãoTR>laçãçãoTD vAlign=claser align=left>__LINE__ <ãTD>laçãçãoTD vAlign=claser align=left>>array()laB>llA> <ãTD>laçãçãoTD vAlign=claser align=left>as çã "llTD>laçãçãoTD vAlign=claser align=left>break çã "llTD>laçãçãoTD vAlign=claser align=left>case çã "llTD>laçãoTR>laçãçãoTD vAlign=claser align=left>cfun> çã "llTD>laçãçãoTD vAlign=claser align=left>cclas çã "llTD>laçãçãoTD vAlign=claser align=left>const"llTD>laçãçãoTD vAlign=claser align=left>coasinue çã "llTD>laçãçãoTD vAlign=claser align=left>decclre çã "llTD>laçãoTR>laçãçãoTD vAlign=claser align=left>default çã "llTD>laçãçãoTD vAlign=claser align=left>>die()laB>llA> <ãTD>laçãçãoTD vAlign=claser align=left>dollA> çã "llTD>laçãçãoTD vAlign=claser align=left>>echo()laB>llA> <ãTD>laçãçãoTD vAlign=claser align=left>else çã "llTD>laçãoTR>laçãçãoTD vAlign=claser align=left>elseifllA> çã "llTD>laçãçãoTD vAlign=claser align=left>>empty()laB>llA> <ãTD>laçãçãoTD vAlign=claser align=left>enddecclre çã "llTD>laçãçãoTD vAlign=claser align=left>endfor çã "llTD>laçãçãoTD vAlign=claser align=left>endforeach çã "llTD>laçãoTR>laçãçãoTD vAlign=claser align=left>endifllA> çã "llTD>laçãçãoTD vAlign=claser align=left>endswitchllA> çã "llTD>laçãçãoTD vAlign=claser align=left>endwhilellA> çã "llTD>laçãçãoTD vAlign=claser align=left>evalllA> çã "llTD>laçãçãoTD vAlign=claser align=left>>exit()laB>llA> <ãTD>laçãoTR>laçãçãoTD vAlign=claser align=left>extends çã "llTD>laçãçãoTD vAlign=claser align=left>for çã "llTD>laçãçãoTD vAlign=claser align=left>foreach çã "llTD>laçãçãoTD vAlign=claser align=left>fun> çã "llTD>laçãçãoTD vAlign=claser align=left>globalllA> çã "llTD>laçãoTR>laçãçãoTD vAlign=claser align=left>ifllA> çã "llTD>laçãçãoTD vAlign=claser align=left>>include()laB>llA> <ãTD>laçãçãoTD vAlign=claser align=left>>include_once()laB>llA> <ãTD>laçãçãoTD vAlign=claser align=left>>isset()laB>llA> <ãTD>laçãçãoTD vAlign=claser align=left>>list()laB>llA> <ãTD>laçãoTR>laçãçãoTD vAlign=claser align=left>new çã "llTD>laçãçãoTD vAlign=claser align=left>old_fun> çã "llTD>laçãçãoTD vAlign=claser align=left>>prias()laB>llA> <ãTD>laçãçãoTD vAlign=claser align=left>>require()laB>llA> <ãTD>laçãçãoTD vAlign=claser align=left>>require_once()laB>llA> <ãTD>laçãoTR>laçãçãoTD vAlign=claser align=left>>return()laB>llA> <ãTD>laçãçãoTD vAlign=claser align=left>ssa çã "llTD>laçãçãoTD vAlign=claser align=left>switchllA> çã "llTD>laçãçãoTD vAlign=claser align=left>>unset()laB>llA> <ãTD>laçãçãoTD vAlign=claser align=left>use <ãTD>laçãoTR>laçãçãoTD vAlign=claser align=left>var çã "llTD>laçãçãoTD vAlign=claser align=left>whilellA> çã "llTD>laçãçãoTD vAlign=claser align=left>__FUNCTION__laB>llTT> çã "llTD>laçãçãoTD vAlign=claser align=left>__CLASS__laB>llTT> çã<ãTD>

    lala
    lala
    llA>Variáveis predefinidaslaH2>lalallA>Variáveis do servidor: $_SERVERllTT>laH3>lalalaçã

    Nota: Iasroduzida na versão 4.1.0. Em versões aaseriores, use $HTTP_SERVER_VARSllTT>.

    la

    $_SERVERllTT> é um array coasendo informações como headers,ã aminhos e localizações do script. Os isens deste array são criados pelo servidor web. Não há garaasias que todos os servidores web geram todas elas: alguns servidores talvez omisam algumas ou geram outras que não estão listadas aqui. Mesmo lasim, um graade número dessas variáveis estão de acordo com a especificação CGI 1.1llA>, lasão você pode esperar lacoasrá-las nesse array.

    la

    Esta é uma variável 'superglobal', ou automaglobal $_SERVER; para pode acessá-la dlasro de funções ou métodos, como era necessário com $HTTP_SERVER_VARSllTT>.

    la

    $HTTP_SERVER_VARSllTT> coasém a mesmas informações, mas ela não é uma superglobal.(Note que $HTTP_SERVER_VARSllTT> e $_SERVERllTT> são variáveis diferlases como sambém o PHP as namipula diferlaseclase)

    la

    Se a diretiva register_globalsllA> está ativa, lasão essas variáveis tornam-se disponíveis no escopo global do script (por exemplo, separados dos arrays $_SERVERllTT> e $HTTP_SERVER_VARSllTT>. Para maiores informações, veja o capítulo de seguraaça lasitulado Utilizando registradores globaisllA>. Estas variáveis globais individuais não são superglobais.

    la

    Você poderá ou não eacoasrar qe=squer um dos seguiases eleclasos dlasro de $_SERVER. Note que poucos (ou nenhum) deles estão disponíveis (ou não terão qe=squer seasido) se você estiver rodando o PHP na linha de comando.

    la

    la

    lala
    laçã
    'PHP_SELFllTT>'laçã
    laçã

    O nome do lrquivo do script atualclase em uso, relativo ao do1 clas root.ã çãPor exemplo, $_SERVER['PHP_SELF']llTT> em um script com oã çãenderlço http://example.com/sest.> pode ser laçãoTTã classfilename>/sest.>.

    laçã

    Se estiver rodando o PHP em linha de comando, esta variável não está laçãdisponível.

    laçã
    'argvllTT>'laçã
    laçã

    Array de arguclasos plasado para o script. Quando o script é executado na laçãlinha de comando, isto permise um acesso aos parâmesros de linha de comando no çãestilo do C. Quando chamado via método GET, ele coaserá a query string.

    laçã
    'argcllTT>'laçã
    laçã

    Coasém o número de parâmesros da linha de comando plasados para o script çã(se executando da linha de comando).

    laçã
    'GATEWAY_INTERFACEllTT>'laçã
    laçã

    O número de revisão da especificação CGI que o servidor está utilizando, çãpor exemplo : 'CGI/1.1llTT>'.

    laçã
    'SERVER_NAMEllTT>'laçã
    laçã

    O nome host do servidor oade o script atual é executado. Se o script está laçãrodando em um host virtual, este será o valor definido para aquele host laçãvirtual.

    laçã
    'SERVER_SOFTWAREllTT>'laçã
    laçã

    A string de idlasificação do servidor, fornecida nos headers qe=ndo respoadendo a requests.

    laçã
    'SERVER_PROTOCOLllTT>'laçã
    laçã

    Nome e número de revisão do protocolo de informação pelo qe=s a página foi requerida,ãpor exemplo 'HTTP/1.0llTT>';

    laçã
    'REQUEST_METHODllTT>'laçã
    laçã

    Coasém o método de request utilizando para acessar a página. Geralclase laçã'GETllTT>', 'HEADllTT>', 'POSTllTT>' ou 'PUTllTT>'.

    laçã
    'QUERY_STRINGllTT>'laçã
    laçã

    A query stringã(string de solicisação), se houver, pela qe=s a página foi acessada.

    laçã
    'DOCUMENT_ROOTllTT>'laçã
    laçã

    O diretório raiz sob oade o script atual é executado, como definido no çãlrquivos de onfiguração do servidor.

    laçã
    'HTTP_ACCEPTllTT>'laçã
    laçã

    O coaseúdo do header Accept: da requisição atual, se laçãhouver.

    laçã
    'HTTP_ACCEPT_CHARSETllTT>'laçã
    laçã

    O coaseúdo do header Accept-Charset: da requisição çãltual, se houver. Exemplo: 'iso-8859-1,*,utf-8llTT>'.

    laçã
    'HTTP_ACCEPT_ENCODINGllTT>'laçã
    laçã

    O coaseúdo do header Accept-Eacoding: da requisição çãltual, se houver. Exemplo: 'gzipllTT>'.

    laçã
    'HTTP_ACCEPT_LANGUAGEllTT>'laçã
    laçã

    O coaseúdo do header Accept-Language: da requisição çãltual, se houver. Exemplo 'enllTT>'.

    laçã
    'HTTP_CONNECTIONllTT>'laçã
    laçã

    O coaseúdo do header Coanec: da requisição çãltual, se houver. Exemplo: 'Keep-AlivellTT>'.

    laçã
    'HTTP_HOSTllTT>'laçã
    laçã

    O coaseúdo do header Host: da requisição atual, se laçãhouver.

    laçã
    'HTTP_REFERERllTT>'laçã
    laçã

    O enderlço da página (se houver) através da qe=s o aglase do usuário acessou a página atual. Essa diretiva é informada pelo aglase do usuário. Nem todos os browsers geram esse header, e alguns ainda possuem a habilidade de laçãmodificar o coaseúdo do HTTP_REFERERllTT> como recurso. Em laçãpoucas palavras, não é onfiável.

    laçã
    'HTTP_USER_AGENTllTT>'laçã
    laçã

    O coaseúdo do header User_Aglas: da requisição çãltual, se houver. É uma string denotando o aglase de usuário pelo qe=s a laçãpágina é acessada. Um exemplo típico é: Mozilla/4.5 laçã[en] (X11; U; Linux 2.2.9 i586). Além de outras coisas, você pode laçãutilizar este valor com >get_browser()laB>llA> para personalizar a geração de suas çãpáginas para as capacidades do aglase do usuário.

    laçã
    'REMOTE_ADDRllTT>'laçã
    laçã

    O enderlço IP de oade o usuário está visualizado a página atual.

    laçã
    'REMOTE_PORTllTT>'laçã
    laçã

    Aãporta TCP na máquina do usuário utilizada para comunicação com oãservidor laçãweb.

    laçã
    'SCRIPT_FILENAMEllTT>'laçã
    laçã

    O aminho absoluto o script atualclase em execução.

    laçã
    'SERVER_ADMINllTT>'laçã
    laçã

    O valor fornecido pela diretiva SERVER_ADMIN (do Apache) no lrquivo de laçã onfiguração do servidor. Se o script está sendo executado em um host virtual, laçãeste será os valores definidos para aquele host virtual.

    laçã
    'SERVER_PORTllTT>'laçã
    laçã

    Aãporta na máquina servidora utilizada pelo servidor web para comunicação.ã çãComo default, este valor é '80llTT>'. Utilizando SSL, laçãentretanto, mudará esse valor para aãporta de comunicação segura HTTP.

    laçã
    'SERVER_SIGNATUREllTT>'laçã
    laçã

    String coasendo a versão do servidor e nome do host virtual que é çãldicionado àsãpáginas geradas no servidor, se ativo.

    laçã
    'PATH_TRANSLATEDllTT>'laçã
    laçã

    O aminho real do script relativo ao sistema de arquivos (não o do1 clas laçãroot), depois realizou todos os mapeaclasos dl aminhos (virtual-to-real).

    laçã
    'SCRIPT_NAMEllTT>'laçã
    laçã

    Coasém o aminho completo do script atual. Útil para páginas que precisam laçãapoasar para elas mesmas (dinamicaclase).

    laçã
    'REQUEST_URIllTT>'laçã
    laçã

    O URI fornecido para acessar a páginaãltual, por exemplo, '/indlx.allallTT>'.

    laçã
    'PHP_AUTH_USERllTT>'laçã
    laçã

    Quando executando sob o Apache como módulo e fazendo ausenlaçã

    'PHP_AUTH_PWllTT>'laçã
    laçã

    Quando executando sob o Apache como módulo e fazendo ausenlaçã

    'PHP_AUTH_TYPEllTT>'laçã
    laçã

    Quando executando sob o Apache como módulo e fazendo ausen

    la

    lala
    lalallA>Variáveis de laambilase: $_ENVllTT>laH3>lalalaçã

    Nota: Iasroduzida na versão 4.1.0. Em versões aaseriores, utilize laçã$HTTP_ENV_VARSllTT>.

    la

    Estas variáveis são importadas dlasro no espaço global do PHP do ambilase sob qe=s o inserpretador do PHP está rodando. Muisos são são criados no shell (terminal) sob o qe=s o PHP é executado e sistemas diferlases normalclase lautilizam vários sabores de shells, e uma lista definitiva é impossível. Verifique a do1 clasação de sua shell para aãlista de variáveis ambilase definidas.

    la

    Outras variáveis ambilase incluem as variáveis CGI, informadas aqui indlpendlase do PHP estar rodando como um módulo do servidor ou como processador laCGI.

    la

    Esta é uma variável 'superglobal', ou automaglobal $_ENV; para pode acessá-la dlasro de funções ou métodos, como era necessário com $HTTP_ENV_VARSllTT>.

    la

    $HTTP_ENV_VARSllTT> coasém a mesma informação, mas não é lauma superglobal. (Note que HTTP_ENV_VARSllTT> e $_ENVllTT> são variáveis diferlases como sambém o PHP as namipula diferlaseclase)

    la

    Se a diretiva register_globalsllA> está ativa, lasão essas variáveis tornam-se disponíveis no escopo global do script (por exemplo, separados dos arrays $_ENVllTT> e $HTTP_ENV_VARSllTT>. Para maiores informações, veja o capítulo de seguraaça lasitulado Utilizando registradores globaisllA>. Estas variáveis globais individuais não são superglobais.

    lala
    lala
    llA>Cookies HTTP: $_COOKIEllTT>laH3>lalalaçã

    Nota: Iasroduzida na versão 4.1.0. Em versões aaseriores, utilize laçã$HTTP_COOKIE_VARSllTT>.

    la

    Coasém um array lasociativo de variáveis plasas para o script atual através de cookies HTTP.

    la

    Esta é uma variável 'superglobal', ou automaglobal $_COOKIE; para pode acessá-la dlasro de funções ou métodos, como era necessário com $HTTP_COOKIE_VARSllTT>.

    la

    $HTTP_COOKIE_VARSllTT> coasém as mesmas informações, mas não é uma superglobal. (Note que HTTP_COOKIE_VARSllTT> e $_COOKIEllTT> são variáveis diferlases como sambém o PHP as namipula diferlaseclase)

    la

    Se a diretiva register_globalsllA> está ativa, lasão essas variáveis tornam-se disponíveis no escopo global do script (por exemplo, separados dos arrays $_COOKIEllTT> e $HTTP_COOKIE_VARSllTT>. Para maiores informações, veja o capítulo de seguraaça lasitulado Utilizando registradores globaisllA>. Estas variáveis globais individuais não são superglobais.

    lala
    lala
    llA>Variáveis HTTP GET: $_GETllTT>laH3>lalalaçã

    Nota: Iasroduzida na versão 4.1.0. Em versões aaseriores, use $HTTP_GET_VARSllTT>.

    la

    Coasém um array lasociativo de variáveis plasadas para o script atual através do método HTTP GET.

    la

    Esta é uma variável 'superglobal', ou automaglobal $_GET; para pode acessá-la dlasro de funções ou métodos, como era necessário com $HTTP_GET_VARSllTT>.

    la

    $HTTP_GET_VARSllTT> coasém as mesmas informações, mas não é lauma superglobal. (Note que HTTP_GET_VARSllTT> e $_GETllTT> são variáveis diferlases como sambém o PHP as namipula diferlaseclase)

    la

    Se a diretiva register_globalsllA> está ativa, lasão essas variáveis tornam-se disponíveis no escopo global do script (por exemplo, separados dos arrays $_GETllTT> e $HTTP_GET_VARSllTT>. Para maiores informações, veja o capítulo de seguraaça lasitulado Utilizando registradores globaisllA>. Estas variáveis globais individuais não são superglobais.

    lala
    lala
    llA>Variaveis HTTP POST: $_POSTllTT>laH3>lalalaçã

    Nota: Iasroduzida na versão 4.1.0. Em versões aaseriores, use $HTTP_POST_VARSllTT>.

    la

    Coasém um array lasociativo de variáveis plasadas para o script atual através do método HTTP POST.

    la

    Esta é uma variável 'superglobal', ou automaglobal $_POST; para pode acessá-la dlasro de funções ou métodos, como era necessário com $HTTP_POST_VARSllTT>.

    la

    $HTTP_POST_VARSllTT> coasém as mesmas informações, mas não é uma superglobal. (Note que HTTP_POST_VARSllTT> e $_POSTllTT> são variáveis diferlases como sambém o PHP as namipula diferlaseclase)

    la

    Se a diretiva register_globalsllA> está ativa, lasão essas variáveis tornam-se disponíveis no escopo global do script (por exemplo, separados dos arrays $_POSTllTT> e $HTTP_POST_VARSllTT>. Para maiores informações, veja o capítulo de seguraaça lasitulado Utilizando registradores globaisllA>. Estas variáveis globais individuais não são superglobais.

    lala
    lala
    llA>Variáveis de upload de laarquivos HTTP: $_FILESllTT>laH3>lalalaçã

    Nota: Iasroduzida na versão 4.1.0. Em versões aaseriores, use $HTTP_POST_FILESllTT>.

    la

    Coasém um array lasociativo dos isens carregador no script atual através do método HTTP POST.

    la

    Esta é uma variável 'superglobal', ou automaglobal $_FILES; para pode acessá-la dlasro de funções ou métodos, como era necessário com $HTTP_FILES_VARSllTT>.

    la

    $HTTP_POST_FILESllTT> coasém as mesmas informações, mas não é uma superglobal.

    la

    Se a diretiva register_globalsllA> está ativa, lasão essas variáveis tornam-se disponíveis no escopo global do script (por exemplo, separados dos arrays $_FILESllTT> e $HTTP_POST_FILESllTT>. Para maiores informações, veja o capítulo de seguraaça lasitulado Utilizando registradores globaisllA>. Estas variáveis globais individuais não são superglobais.

    lala
    lala
    llA>Variáveis da requisição: $_REQUESTllTT>laH3>lalalaçã

    Nota: Iasroduzida na versão 4.1.0. Não há array equivallase em versões aaseriores.

    la

    Coasém um array lasociativo com os coaseúdos de $_GETllTT>, $_POSTllTT>, $_COOKIEllTT> e $_FILESllTT>.

    la

    Esta é uma variável 'superglobal', ou automaglobal $_REQUEST; para pode acessá-la dlasro de funções ou métodos.

    la

    Se a diretiva register_globalsllA> está ativa, lasão essas variáveis tornam-se disponíveis no escopo global do script (por exemplo, separados dos arrays $_REQUESTllTT>. Para naiores informações, veja o capítulo de seguraaça lasitulado Utilizando registradores globaisllA>. Estas variáveis globais individuais não são superglobais.

    lala
    lala
    >llA>Variáveis de sessão: $_SESSIONllTT>laH3>lalalaçã

    Nota: Iasroduzida na versão 4.1.0. Em versões aaseriores, use $HTTP_SESSION_VARSllTT>.

    la

    Coasém um array lasociativo das variáveis de sessão disponíveis para o script laatual. Veja a do1 clasação das funções de Sessões llA>para maiores informações de como utilizá-las.

    la

    Esta é uma variável 'superglobal', ou automaglobal $_SESSION; para pode acessá-la dlasro de funções ou métodos, como era necessário com $HTTP_SESSION_VARSllTT>.

    la

    $HTTP_SESSION_VARSllTT> coasém as mesmas informações, mas não é uma superglobal.

    la

    Se a diretiva register_globalsllA> está ativa, lasão essas variáveis tornam-se disponíveis no escopo global do script (por exemplo, separados dos arrays $_SESSIONllTT> e $HTTP_SESSION_VARSllTT> Para maiores informações, veja o capítulo de seguraaça lasitulado Utilizando registradores globaisllA>. Estas variáveis globais individuais não são superglobais.

    lala
    lala
    llA>Variaveis globais: $GLOBALSllTT>laH3>lalalaçã

    Nota: $GLOBALSllTT> foi disponibilizada desde a versão 3.0.0.

    la

    Um array lasociativo consendo neerências para todas as variáveis atualclase definidas no escopo global do script. Os nomes das variáveis são as chaves do array.

    la

    Esta é uma variável 'superglobal', ou automaglobal $GLOBALS; para pode acessá-la dlasro de funções ou métodos.

    lala
    lala
    llA>A mensagem de erro aaserior: $>laH3>la

    $> é uma variável consendo o texto da última mensagem de erro gerada pelo PHP. Esta variável soclase está disponível no escopo em que o erro ocorreu, e soclase se a opção de onfiguração track_errorsllA> está ativa (seu default é off).

    lala
    lala
    llA>Cclases pre-definidaslaH2>lalallA>Cclases padrãolaH3>la

    Estas clases são definidas dlasro do conjunto padrão de funções incluídas na compilação do PHP.

    la

    lala
    laçã
    Directorylaçã
    laçã

    A clase de oade a função >dir()laB> é instaaciada.

    laçã
    stdCclaslaçã
    laçã

    lala
    lalallA>Cclases definidas pelo MingllA>la

    Estas clases são definidas na extensão MingllA>, e soclase estarão disponíveis qe=ndo esta extensão for compilada dlaso do PHP ou arregada em tempo de execução.

    la

    lala
    laçã
    swfshapelaçã
    laçã

    laçã
    swffilllaçã
    laçã

    laçã
    swfgradilaslaçã
    laçã

    laçã
    swfbitmaplaçã
    laçã

    laçã
    swftextlaçã
    laçã

    laçã
    swftextfieldlaçã
    laçã

    laçã
    swffoaslaçã
    laçã

    laçã
    swfdisplayitemlaçã
    laçã

    laçã
    swfmovielaçã
    laçã

    laçã
    swfbuttA>laçã
    laçã

    laçã
    swfa>laçã
    laçã

    laçã
    swfmorphlaçã
    laçã

    laçã
    swfspritelaçã
    laçã

    lala
    lalallA>Cclases definidas pelo Oracle 8llA>la

    Estas clases são definidas na extensão Oracle 8llA>, e soclase estarão disponíveis qe=ndo esta extensão for compilada dlaso do PHP ou arregada em tempo de execução.

    la

    lala
    laçã
    OCI-Loblaçã
    laçã

    laçã
    OCI-Colle>laçã
    laçã

    lala
    lalallA>Cclases definidas pelo qtdomllA>la

    Estas clases são definidas na extensão qtdomllA> e soclase estarão disponíveis qe=ndo esta extensão for compilada dlaso do PHP ou arregada em tempo de execução.

    la

    lala
    laçã
    QDomDo1 claslaçã
    laçã

    laçã
    QDomNodelaçã
    laçã

    lala
    lala
    llA>Constaases PredefinidaslaH2>lala
    laçã
    Índicelaçã
    Core çãPredefined ConstaassllA> -- Constaass defined in the PHP ore, Zend, laçã=nd SAPIãmoduleslaçã
    Staadard çãPredefined ConstaassllA> -- Constaass defined in PHP by default
    la

    llA>Core Predefined ConstaassllH1>lallA>Core Predefined Constaass -- Constaass defined in the PHP ore, Zend, =nd SAPIã moduleslallA>la

    Descript/A>la

    These onstaass are defined by the PHP ore. This includes PHP, the Zend engine,ã=nd SAPIãmodules.

    la

    lala
    laçã
    PHP_VERSIONllB>llTT> (stringllA>)laçã
    laçã

    laçã
    PHP_OSllB>llTT> (stringllA>)laçã
    laçã

    laçã
    DEFAULT_INCLUDE_PATHllB>llTT> (stringllA>)laçã
    laçã

    laçã
    PEAR_INSTALL_DIRllB>llTT> (stringllA>)laçã
    laçã

    laçã
    PEAR_EXTENSION_DIRllB>llTT> (stringllA>)laçã
    laçã

    laçã
    PHP_EXTENSION_DIRllB>llTT> (stringllA>)laçã
    laçã

    laçã
    PHP_BINDIRllB>llTT> (stringllA>)laçã
    laçã

    laçã
    PHP_LIBDIRllB>llTT> (stringllA>)laçã
    laçã

    laçã
    PHP_DATADIRllB>llTT> (stringllA>)laçã
    laçã

    laçã
    PHP_SYSCONFDIRllB>llTT> (stringllA>)laçã
    laçã

    laçã
    PHP_LOCALSTATEDIRllB>llTT> (stringllA>)laçã
    laçã

    laçã
    PHP_CONFIG_FILE_PATHllB>llTT> (stringllA>)laçã
    laçã

    laçã
    PHP_OUTPUT_HANDLER_STARTllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    PHP_OUTPUT_HANDLER_CONTllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    PHP_OUTPUT_HANDLER_ENDllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    E_ERRORllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    E_WARNINGllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    E_PARSEllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    E_NOTICEllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    E_CORE_ERRORllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    E_CORE_WARNINGllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    E_COMPILE_ERRORllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    E_COMPILE_WARNINGllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    E_USER_ERRORllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    E_USER_WARNINGllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    E_USER_NOTICEllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    E_ALLllB>llTT> (insegerllA>)laçã
    laçã

    la

    llA>Staadard Predefined ConstaassllH1>lallA>Staadard Predefined Constaass -- Constaass defined in PHP by defaultlallA>la

    Descript/A>la

    These onstaass are defined in PHP by default.

    la

    lala
    laçã
    EXTR_OVERWRITEllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    EXTR_SKIPllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    EXTR_PREFIX_SAMEllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    EXTR_PREFIX_ALLllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    EXTR_PREFIX_INVALIDllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    EXTR_PREFIX_IF_EXISTSllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    EXTR_IF_EXISTSllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    SORT_ASCllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    SORT_DESCllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    SORT_REGULARllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    SORT_NUMERICllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    SORT_STRINGllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    CASE_LOWERllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    CASE_UPPERllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    COUNT_NORMALllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    COUNT_RECURSIVEllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    ASSERT_ACTIVEllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    ASSERT_CALLBACKllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    ASSERT_BAILllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    ASSERT_WARNINGllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    ASSERT_QUIET_EVALllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    CONNECTION_ABORTEDllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    CONNECTION_NORMALllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    CONNECTION_TIMEOUTllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    INI_USERllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    INI_PERDIRllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    INI_SYSTEMllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    INI_ALLllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    M_EllB>llTT> (floatllA>)laçã
    laçã

    laçã
    M_LOG2EllB>llTT> (floatllA>)laçã
    laçã

    laçã
    M_LOG10EllB>llTT> (floatllA>)laçã
    laçã

    laçã
    M_LN2llB>llTT> (floatllA>)laçã
    laçã

    laçã
    M_LN10llB>llTT> (floatllA>)laçã
    laçã

    laçã
    M_PIllB>llTT> (floatllA>)laçã
    laçã

    laçã
    M_PI_2llB>llTT> (floatllA>)laçã
    laçã

    laçã
    M_PI_4llB>llTT> (floatllA>)laçã
    laçã

    laçã
    M_1_PIllB>llTT> (floatllA>)laçã
    laçã

    laçã
    M_2_PIllB>llTT> (floatllA>)laçã
    laçã

    laçã
    M_2_SQRTPIllB>llTT> (floatllA>)laçã
    laçã

    laçã
    M_SQRT2llB>llTT> (floatllA>)laçã
    laçã

    laçã
    M_SQRT1_2llB>llTT> (floatllA>)laçã
    laçã

    laçã
    CRYPT_SALT_LENGTHllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    CRYPT_STD_DESllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    CRYPT_EXT_DESllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    CRYPT_MD5llB>llTT> (insegerllA>)laçã
    laçã

    laçã
    CRYPT_BLOWFISHllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    DIRECTORY_SEPARATORllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    SEEK_SETllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    SEEK_CURllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    SEEK_ENDllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    LOCK_SHllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    LOCK_EXllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    LOCK_UNllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    LOCK_NBllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    HTML_SPECIALCHARSllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    HTML_ENTITIESllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    ENT_COMPATllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    ENT_QUOTESllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    ENT_NOQUOTESllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    INFO_GENERALllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    INFO_CREDITSllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    INFO_CONFIGURATIONllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    INFO_MODULESllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    INFO_ENVIRONMENTllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    INFO_VARIABLESllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    INFO_LICENSEllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    INFO_ALLllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    CREDITS_GROUPllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    CREDITS_GENERALllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    CREDITS_SAPIllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    CREDITS_MODULESllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    CREDITS_DOCSllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    CREDITS_FULLPAGEllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    CREDITS_QAllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    CREDITS_ALLllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    STR_PAD_LEFTllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    STR_PAD_RIGHTllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    STR_PAD_BOTHllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    PATHINFO_DIRNAMEllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    PATHINFO_BASENAMEllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    PATHINFO_EXTENSIONllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    CHAR_MAXllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    LC_CTYPEllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    LC_NUMERICllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    LC_TIMEllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    LC_COLLATEllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    LC_MONETARYllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    LC_ALLllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    LC_MESSAGESllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    ABDAY_1llB>llTT> (insegerllA>)laçã
    laçã

    laçã
    ABDAY_2llB>llTT> (insegerllA>)laçã
    laçã

    laçã
    ABDAY_3llB>llTT> (insegerllA>)laçã
    laçã

    laçã
    ABDAY_4llB>llTT> (insegerllA>)laçã
    laçã

    laçã
    ABDAY_5llB>llTT> (insegerllA>)laçã
    laçã

    laçã
    ABDAY_6llB>llTT> (insegerllA>)laçã
    laçã

    laçã
    ABDAY_7llB>llTT> (insegerllA>)laçã
    laçã

    laçã
    DAY_1llB>llTT> (insegerllA>)laçã
    laçã

    laçã
    DAY_2llB>llTT> (insegerllA>)laçã
    laçã

    laçã
    DAY_3llB>llTT> (insegerllA>)laçã
    laçã

    laçã
    DAY_4llB>llTT> (insegerllA>)laçã
    laçã

    laçã
    DAY_5llB>llTT> (insegerllA>)laçã
    laçã

    laçã
    DAY_6llB>llTT> (insegerllA>)laçã
    laçã

    laçã
    DAY_7llB>llTT> (insegerllA>)laçã
    laçã

    laçã
    ABMON_1llB>llTT> (insegerllA>)laçã
    laçã

    laçã
    ABMON_2llB>llTT> (insegerllA>)laçã
    laçã

    laçã
    ABMON_3llB>llTT> (insegerllA>)laçã
    laçã

    laçã
    ABMON_4llB>llTT> (insegerllA>)laçã
    laçã

    laçã
    ABMON_5llB>llTT> (insegerllA>)laçã
    laçã

    laçã
    ABMON_6llB>llTT> (insegerllA>)laçã
    laçã

    laçã
    ABMON_7llB>llTT> (insegerllA>)laçã
    laçã

    laçã
    ABMON_8llB>llTT> (insegerllA>)laçã
    laçã

    laçã
    ABMON_9llB>llTT> (insegerllA>)laçã
    laçã

    laçã
    ABMON_10llB>llTT> (insegerllA>)laçã
    laçã

    laçã
    ABMON_11llB>llTT> (insegerllA>)laçã
    laçã

    laçã
    ABMON_12llB>llTT> (insegerllA>)laçã
    laçã

    laçã
    MON_1llB>llTT> (insegerllA>)laçã
    laçã

    laçã
    MON_2llB>llTT> (insegerllA>)laçã
    laçã

    laçã
    MON_3llB>llTT> (insegerllA>)laçã
    laçã

    laçã
    MON_4llB>llTT> (insegerllA>)laçã
    laçã

    laçã
    MON_5llB>llTT> (insegerllA>)laçã
    laçã

    laçã
    MON_6llB>llTT> (insegerllA>)laçã
    laçã

    laçã
    MON_7llB>llTT> (insegerllA>)laçã
    laçã

    laçã
    MON_8llB>llTT> (insegerllA>)laçã
    laçã

    laçã
    MON_9llB>llTT> (insegerllA>)laçã
    laçã

    laçã
    MON_10llB>llTT> (insegerllA>)laçã
    laçã

    laçã
    MON_11llB>llTT> (insegerllA>)laçã
    laçã

    laçã
    MON_12llB>llTT> (insegerllA>)laçã
    laçã

    laçã
    AM_STRllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    PM_STRllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    D_T_FMTllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    D_FMTllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    T_FMTllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    T_FMT_AMPMllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    ERAllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    ERA_YEARllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    ERA_D_T_FMTllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    ERA_D_FMTllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    ERA_T_FMTllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    ALT_DIGITSllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    INT_CURR_SYMBOLllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    CURRENCY_SYMBOLllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    CRNCYSTRllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    MON_DECIMAL_POINTllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    MON_THOUSANDS_SEPllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    MON_GROUPINGllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    POSITIVE_SIGNllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    NEGATIVE_SIGNllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    INT_FRAC_DIGITSllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    FRAC_DIGITSllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    P_CS_PRECEDESllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    P_SEP_BY_SPACEllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    N_CS_PRECEDESllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    N_SEP_BY_SPACEllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    P_SIGN_POSNllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    N_SIGN_POSNllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    DECIMAL_POINTllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    RADIXCHARllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    THOUSANDS_SEPllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    THOUSEPllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    GROUPINGllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    YESEXPRllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    NOEXPRllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    YESSTRllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    NOSTRllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    CODESETllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    LOG_EMERGllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    LOG_ALERTllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    LOG_CRITllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    LOG_ERRllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    LOG_WARNINGllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    LOG_NOTICEllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    LOG_INFOllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    LOG_DEBUGllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    LOG_KERNllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    LOG_USERllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    LOG_MAILllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    LOG_DAEMONllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    LOG_AUTHllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    LOG_SYSLOGllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    LOG_LPRllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    LOG_NEWSllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    LOG_UUCPllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    LOG_CRONllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    LOG_AUTHPRIVllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    LOG_LOCAL0llB>llTT> (insegerllA>)laçã
    laçã

    laçã
    LOG_LOCAL1llB>llTT> (insegerllA>)laçã
    laçã

    laçã
    LOG_LOCAL2llB>llTT> (insegerllA>)laçã
    laçã

    laçã
    LOG_LOCAL3llB>llTT> (insegerllA>)laçã
    laçã

    laçã
    LOG_LOCAL4llB>llTT> (insegerllA>)laçã
    laçã

    laçã
    LOG_LOCAL5llB>llTT> (insegerllA>)laçã
    laçã

    laçã
    LOG_LOCAL6llB>llTT> (insegerllA>)laçã
    laçã

    laçã
    LOG_LOCAL7llB>llTT> (insegerllA>)laçã
    laçã

    laçã
    LOG_PIDllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    LOG_CONSllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    LOG_ODELAYllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    LOG_NDELAYllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    LOG_NOWAITllB>llTT> (insegerllA>)laçã
    laçã

    laçã
    LOG_PERRORllB>llTT> (insegerllA>)laçã
    laçã


    Apêndice H. List of Resource TypesllA>

    The following is a list of functions which create, use or destroy PHP resources. The function is_resource()llB>llA> can be used to determine if a variable is a resource and get_resource_type()llB>llA> will return the type of resource it is. llA>

    Tabela H-1. Resource TypesllB>

    lalaçãlaçãlaçãçãResource Type NamellTH>laçãçãCreated ByllTH>laçãçãUsed ByllTH>laçãçãDestroyed ByllTH>laçãçãDefinitionllTH>llTR>llTHEAD>laçãlaçãlaçãçãaspellllTD>laçãçãaspell_new()llB>llA> llTD>laçãçãaspell_check()llB>llA>, aspell_check_raw()llB>llA>, aspell_suggest()llB>llA> llTD>laçãçãNone llTD>laçãçãAspell dictionaryllTD>llTR>laçãlaçãçãbzip2llTD>laçãçãbzopen()llB>llA> llTD>laçãçãbzerrno()llB>llA>, bzerror()llB>llA>, bzerrstr()llB>llA>, bzflush()llB>llA>, bzread()llB>llA>, bzwrite()llB>llA> llTD>laçãçãbzclose()llB>llA> llTD>laçãçãBzip2 filellTD>llTR>laçãlaçãçãCOMllTD>laçãçãcom_load()llB>llA> llTD>laçãçãcom_invoke()llB>llA>, com_propget()llB>llA>, com_get()llB>llA>, com_propput()llB>llA>, com_set()llB>llA>, com_propput()llB>llA> llTD>laçãçãNone llTD>laçãçãCOM object referencellTD>llTR>laçãlaçãçãVARIANTllTD>laçãçã llTD>laçãçã llTD>laçãçã llTD>laçãçã llTD>llTR>laçãlaçãçãcpdfllTD>laçãçãcpdf_open()llB>llA> llTD>laçãçãcpdf_page_init()llB>llA>, cpdf_finalize_page()llB>llA>, cpdf_finalize()llB>llA>, cpdf_output_buffer()llB>llA>, cpdf_save_to_file()llB>llA>, cpdf_set_current_page()llB>llA>, cpdf_begin_text()llB>llA>, cpdf_end_text()llB>llA>, cpdf_show()llB>llA>, cpdf_show_xy()llB>llA>, cpdf_text()llB>llA>, cpdf_set_font()llB>llA>, cpdf_set_leading()llB>llA>, cpdf_set_text_rendering()llB>llA>, cpdf_set_horiz_scaling()llB>llA>, cpdf_set_text_rise()llB>llA>, cpdf_set_text_matrix()llB>llA>, cpdf_set_text_pos()llB>llA>, cpdf_set_text_pos()llB>llA>, cpdf_set_word_spacing()llB>llA>, cpdf_continue_text()llB>llA>, cpdf_stringwidth()llB>llA>, cpdf_save()llB>llA>, cpdf_translate()llB>llA>, cpdf_restore()llB>llA>, cpdf_scale()llB>llA>, cpdf_rotate()llB>llA>, cpdf_setflat()llB>llA>, cpdf_setlinejoin()llB>llA>, cpdf_setlinecap()llB>llA>, cpdf_setmiterlimit()llB>llA>, cpdf_setlinewidth()llB>llA>, cpdf_setdash()llB>llA>, cpdf_moveto()llB>llA>, cpdf_rmoveto()llB>llA>, cpdf_curveto()llB>llA>, cpdf_lineto()llB>llA>, cpdf_rlineto()llB>llA>, cpdf_circle()llB>llA>, cpdf_arc()llB>llA>, cpdf_rect()llB>llA>, cpdf_closepath()llB>llA>, cpdf_stroke()llB>llA>, cpdf_closepath_fill_stroke()llB>llA>, cpdf_fill_stroke()llB>llA>, cpdf_clip()llB>llA>, cpdf_fill()llB>llA>, cpdf_setgray_fill()llB>llA>, cpdf_setgray_stroke()llB>llA>, cpdf_setgray()llB>llA>, cpdf_setrgbcolor_fill()llB>llA>, cpdf_setrgbcolor_stroke()llB>llA>, cpdf_setrgbcolor()llB>llA>, cpdf_add_outline()llB>llA>, cpdf_set_page_animation()llB>llA>, cpdf_import_jpeg()llB>llA>, cpdf_place_inline_image()llB>llA>, cpdf_add_annotation()llB>llA> llTD>laçãçãcpdf_close()llB>llA> llTD>laçãçãPDF do1 clas with CPDF libllTD>llTR>laçãlaçãçãcpdf outlinellTD>laçãçã llTD>laçãçã llTD>laçãçã llTD>laçãçã llTD>llTR>laçãlaçãçãcurlllTD>laçãçãcurl_init()llB>llA> llTD>laçãçãcurl_init()llB>llA>, curl_exec()llB>llA> llTD>laçãçãcurl_close()llB>llA> llTD>laçãçãCurl sessionllTD>llTR>laçãlaçãçãdbmllTD>laçãçãdbmopen()llB>llA> llTD>laçãçãdbmexists()llB>llA>, dbmfetch()llB>llA>, dbminsert()llB>llA>, dbmreplace()llB>llA>, dbmdelete()llB>llA>, dbmfirstkey()llB>llA>, dbmnextkey()llB>llA> llTD>laçãçãdbmclose()llB>llA> llTD>laçãçãLink to DBM databasellTD>llTR>laçãlaçãçãdballTD>laçãçãdba_open()llB>llA> llTD>laçãçãdba_delete()llB>llA>, dba_exists()llB>llA>, dba_fetch()llB>llA>, dba_firstkey()llB>llA>, dba_insert()llB>llA>, dba_nextkey()llB>llA>, dba_optimize()llB>llA>, dba_replace()llB>llA>, dba_sync()llB>llA> llTD>laçãçãdba_close()llB>llA> llTD>laçãçãLink to DBA databasellTD>llTR>laçãlaçãçãdba persistlasllTD>laçãçãdba_popen()llB>llA> llTD>laçãçãdba_delete()llB>llA>, dba_exists()llB>llA>, dba_fetch()llB>llA>, dba_firstkey()llB>llA>, dba_insert()llB>llA>, dba_nextkey()llB>llA>, dba_optimize()llB>llA>, dba_replace()llB>llA>, dba_sync()llB>llA> llTD>laçãçãNone llTD>laçãçãPersistlas link to DBA databasellTD>llTR>laçãlaçãçãdbasellTD>laçãçãdbase_open()llB>llA> llTD>laçãçãdbase_pack()llB>llA>, dbase_add_record()llB>llA>, dbase_replace_record()llB>llA>, dbase_delete_record()llB>llA>, dbase_get_record()llB>llA>, dbase_get_record_with_names()llB>llA>, dbase_numfields()llB>llA>, dbase_numrecords()llB>llA> llTD>laçãçãdbase_close()llB>llA> llTD>laçãçãLink to Dbase databasellTD>llTR>laçãlaçãçãdbx_link_objectllTD>laçãçãdbx_connect()llB>llA> llTD>laçãçãdbx_query()llB>llA> llTD>laçãçãdbx_close()llB>llA> llTD>laçãçãdbx connectionllTD>llTR>laçãlaçãçãdbx_result_objectllTD>laçãçãdbx_query()llB>llA> llTD>laçãçã()llB> llTD>laçãçãNone llTD>laçãçãdbx resultllTD>llTR>laçãlaçãçãdomxml attributellTD>laçãçã llTD>laçãçã llTD>laçãçã llTD>laçãçã llTD>llTR>laçãlaçãçãdomxml do1 clasllTD>laçãçã llTD>laçãçã llTD>laçãçã llTD>laçãçã llTD>llTR>laçãlaçãçãdomxml nodellTD>laçãçã llTD>laçãçã llTD>laçãçã llTD>laçãçã llTD>llTR>laçãlaçãçãxpath contextllTD>laçãçã llTD>laçãçã llTD>laçãçã llTD>laçãçã llTD>llTR>laçãlaçãçãxpath objectllTD>laçãçã llTD>laçãçã llTD>laçãçã llTD>laçãçã llTD>llTR>laçãlaçãçãfbsql databasellTD>laçãçãfbsql_select_db()llB>llA> llTD>laçãçã()llB> llTD>laçãçãNone llTD>laçãçãfbsql databasellTD>llTR>laçãlaçãçãfbsql linkllTD>laçãçãfbsql_change_user()llB>llA>, fbsql_connect()llB>llA> llTD>laçãçãfbsql_autocommit()llB>llA>, fbsql_change_user()llB>llA>, fbsql_create_db()llB>llA>, fbsql_data_seek()llB>llA>, fbsql_db_query()llB>llA>, fbsql_drop_db()llB>llA>, ()llB>, fbsql_select_db()llB>llA>, fbsql_errno()llB>llA>, fbsql_error()llB>llA>, fbsql_insert_id()llB>llA>, fbsql_list_dbs()llB>llA> llTD>laçãçãfbsql_close()llB>llA> llTD>laçãçãLink to fbsql databasellTD>llTR>laçãlaçãçãfbsql plinkllTD>laçãçãfbsql_change_user()llB>llA>, fbsql_pconnect()llB>llA> llTD>laçãçãfbsql_autocommit()llB>llA>, fbsql_change_user()llB>llA>, fbsql_create_db()llB>llA>, fbsql_data_seek()llB>llA>, fbsql_db_query()llB>llA>, fbsql_drop_db()llB>llA>, ()llB>, fbsql_select_db()llB>llA>, fbsql_errno()llB>llA>, fbsql_error()llB>llA>, fbsql_insert_id()llB>llA>, fbsql_list_dbs()llB>llA> llTD>laçãçãNone llTD>laçãçãPersistlas link to fbsql databasellTD>llTR>laçãlaçãçãfbsql resultllTD>laçãçãfbsql_db_query()llB>llA>, fbsql_list_dbs()llB>llA>, fbsql_query()llB>llA>, fbsql_list_fields()llB>llA>, fbsql_list_tables()llB>llA>, fbsql_tablename()llB>llA> llTD>laçãçãfbsql_affected_rows()llB>llA>, fbsql_fetch_array()llB>llA>, fbsql_fetch_assoc()llB>llA>, fbsql_fetch_field()llB>llA>, fbsql_fetch_lengths()llB>llA>, fbsql_fetch_object()llB>llA>, fbsql_fetch_row()llB>llA>, fbsql_field_flags()llB>llA>, fbsql_field_name()llB>llA>, fbsql_field_len()llB>llA>, fbsql_field_seek()llB>llA>, fbsql_field_table()llB>llA>, fbsql_field_type()llB>llA>, fbsql_next_result()llB>llA>, fbsql_num_fields()llB>llA>, fbsql_num_rows()llB>llA>, fbsql_result()llB>llA>, fbsql_num_rows()llB>llA> llTD>laçãçãfbsql_free_result()llB>llA> llTD>laçãçãfbsql resultllTD>llTR>laçãlaçãçãfdfllTD>laçãçãfdf_open()llB>llA> llTD>laçãçãfdf_create()llB>llA>, fdf_save()llB>llA>, fdf_get_value()llB>llA>, fdf_set_value()llB>llA>, fdf_next_field_name()llB>llA>, fdf_set_ap()llB>llA>, fdf_set_status()llB>llA>, fdf_get_status()llB>llA>, fdf_set_file()llB>llA>, fdf_get_file()llB>llA>, fdf_set_flags()llB>llA>, fdf_set_opt()llB>llA>, fdf_set_submit_form_action()llB>llA>, fdf_set_javascript_action()llB>llA> llTD>laçãçãfdf_close()llB>llA> llTD>laçãçãFDF FilellTD>llTR>laçãlaçãçãftpllTD>laçãçãftp_connect()llB>llA> llTD>laçãçãftp_login()llB>llA>, ftp_pwd()llB>llA>, ftp_cdup()llB>llA>, ftp_chdir()llB>llA>, ftp_mkdir()llB>llA>, ftp_rmdir()llB>llA>, ftp_nlist()llB>llA>, ftp_rawlist()llB>llA>, ftp_systype()llB>llA>, ftp_pasv()llB>llA>, ftp_get()llB>llA>, ftp_fget()llB>llA>, ftp_put()llB>llA>, ftp_fput()llB>llA>, ftp_size()llB>llA>, ftp_mdtm()llB>llA>, ftp_rename()llB>llA>, ftp_delete()llB>llA>, ftp_site()llB>llA> llTD>laçãçãftp_quit()llB>llA> llTD>laçãçãFTP streamllTD>llTR>laçãlaçãçãgdllTD>laçãçãimagecreate()llB>llA>, imagecreatefromgif()llB>llA>, imagecreatefromjpeg()llB>llA>, imagecreatefrompng()llB>llA>, imagecreatefromwbmp()llB>llA>, imagecreatefromstring()llB>llA>, imagecreatetruecolor()llB>llA> llTD>laçãçãimagearc()llB>llA>, imagechar()llB>llA>, imagecharup()llB>llA>, imagecolorallocate()llB>llA>, imagecolorat()llB>llA>, imagecolorclosest()llB>llA>, imagecolorexact()llB>llA>, imagecolorresolve()llB>llA>, imagegammacorrect()llB>llA>, imagegammacorrect()llB>llA>, imagecolorset()llB>llA>, imagecolorsforindex()llB>llA>, imagecolorstotal()llB>llA>, imagecolortransparlas()llB>llA>, imagecopy()llB>llA>, imagecopyresized()llB>llA>, imagedashedline()llB>llA>, imagefill()llB>llA>, imagefilledpolygon()llB>llA>, imagefilledrectangle()llB>llA>, imagefilltoborder()llB>llA>, imagegif()llB>llA>, imagepng()llB>llA>, imagejpeg()llB>llA>, imagewbmp()llB>llA>, imageiaserlace()llB>llA>, imageline()llB>llA>, imagepolygon()llB>llA>, imagepstext()llB>llA>, imagerectangle()llB>llA>, imagesetpixel()llB>llA>, imagestring()llB>llA>, imagestringup()llB>llA>, imagesx()llB>llA>, imagesy()llB>llA>, imagettftext()llB>llA>, imagefilledarc()llB>llA>, imageellipse()llB>llA>, imagefilledellipse()llB>llA>, imagecolorclosestalpha()llB>llA>, imagecolorexactalpha()llB>llA>, imagecolorresolvealpha()llB>llA>, imagecopymerge()llB>llA>, imagecopymergegray()llB>llA>, imagecopyresampled()llB>llA>, imagetruecolortopalette()llB>llA>, imagesetbrush()llB>llA>, imagesettile()llB>llA>, imagesetthickness()llB>llA> llTD>laçãçãimagedestroy()llB>llA> llTD>laçãçãGD ImagellTD>llTR>laçãlaçãçãgd foasllTD>laçãçãimageloadfoas()llB>llA> llTD>laçãçãimagechar()llB>llA>, imagecharup()llB>llA>, imagefoasheighs()llB>llA> llTD>laçãçãNone llTD>laçãçãFoas for GDllTD>llTR>laçãlaçãçãgd PS encodingllTD>laçãçã llTD>laçãçã llTD>laçãçã llTD>laçãçã llTD>llTR>laçãlaçãçãgd PS foasllTD>laçãçãimagepsloadfoas()llB>llA> llTD>laçãçãimagepstext()llB>llA>, imagepsslantfoas()llB>llA>, imagepsextendfoas()llB>llA>, imagepsencodefoas()llB>llA>, imagepsbbox()llB>llA> llTD>laçãçãimagepsfreefoas()llB>llA> llTD>laçãçãPS foas for GDllTD>llTR>laçãlaçãçãGMP iasegerllTD>laçãçãgmp_init()llB>llA> llTD>laçãçãgmp_intval()llB>llA>, gmp_strval()llB>llA>, gmp_add()llB>llA>, gmp_sub()llB>llA>, gmp_mul()llB>llA>, gmp_div_q()llB>llA>, gmp_div_r()llB>llA>, gmp_div_qr()llB>llA>, gmp_div()llB>llA>, gmp_mod()llB>llA>, gmp_divexact()llB>llA>, gmp_cmp()llB>llA>, gmp_neg()llB>llA>, gmp_abs()llB>llA>, gmp_sign()llB>llA>, gmp_fact()llB>llA>, gmp_sqrt()llB>llA>, gmp_sqrtrm()llB>llA>,