29-01-2003
Copyright © 1997, 1998, 1999, 2000, 2001, 2002, 2003 PHP Documentation Group
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/).
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.
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?
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?.
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:
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.
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
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.
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.
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.
Create a file named hello.php and put it in your web servers root directory (DOCUMENT_ROOT) with the following content:
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.
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:
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:
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
A sample output of this script may be:
|
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
A sample output of this script may be:
|
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.
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:
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:
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.
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.
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.
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.
This section contains notes and hints specific to installing PHP on HP-UX systems.
Exemplo 3-1. Installation Instructions for HP-UX 10
|
This section contains notes and hints specific to installing PHP on Linux distributions.
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.
This section contains notes and hints specific to installing PHP on Mac OS X Server.
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.
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
|
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"
#AddType application/x-httpd-php .php #AddType application/x-httpd-php-source .phps |
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.
This section contains notes and hints specific to installing PHP on OpenBSD 3.2.
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
|
Read the packages(7) manual page for more information about binary packages on OpenBSD.
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 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.
This section contains notes and hints specific to installing PHP on Solaris systems.
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
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:
As an Apache module
As an fhttpd module
For use with AOLServer, NSAPI, phttpd, Pi3Web, Roxen, thttpd, or Zeus.
As a CGI executable
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)
|
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.
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.
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. |
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 |
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
Before getting started, it is worthwhile answering the question: "Why is building on Windows so hard?" Two reasons come to mind:
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.
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.
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...
..the win32 buildtools from the PHP site at http://www.php.net/extra/win32build.zip.
..the source code for the DNS name resolver used by PHP from http://www.php.net/extra/bindlib_w32.zip. This is a replacement for the resolv.lib library included in win32build.zip.
If you plan to compile PHP as a Apache module you will also need the Apache sources.
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.
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).
+--c:\work | | | +--bindlib_w32 | | | | | +--arpa | | | | | +--conf | | | | | +--... | | | +--php-4.x.x | | | | | +--build | | | | | +--... | | | | | +--win32 | | | | | +--... | | | +--win32build | | | | | +--bin | | | | | +--include | | | | | +--lib |
Nota: Cygwin users may omit the last step. A properly installed Cygwin environment provides the mandatory files bison.simple and bison.exe.
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
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"
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.
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:
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).
c:\windows\system for Windows 9x/Me c:\winnt\system32 for Windows NT/2000 c:\windows\system32 for Windows XP
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 |
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.
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.
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.
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
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.
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
|
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 |
Exemplos diferentes de compilação do PHP para apache estão a seguir:
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.
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().
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.
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:
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.
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"
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".
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.
The following versions of PHP are known to work with the most recent version of Apache 2.0:
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.
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)
|
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.
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:
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:
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. |
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
|
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.
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.
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.
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.
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.
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)
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
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
|
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
|
If you are running Netscape Enterprise 4.x, then you should use the following:
Exemplo 3-12. Configuration Example for Netscape Enterprise 4.x
|
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
This section contains notes and hints specific to OmniHTTPd.
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.
This section contains notes and hints specific to Oreilly Website Pro.
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).
This section contains notes and hints specific to the Sambar server for 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]:
(This line assumes that PHP was installed in c:\php.)Now restart the Sambar server for the changes to take effect.
This section contains notes and hints specific to Xitami.
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.
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.
Some problems are more common than others. The most common ones are listed in the PHP FAQ, part of this manual.
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.
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!
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.
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.
Include dbplus support.
Include Adabas D support. DIR is the Adabas base install directory, defaults to /usr/local.
Include SAP DB support. DIR is SAP DB base install directory, defaults to /usr/local.
Include Solid support. DIR is the Solid base install directory, defaults to /usr/local/solid.
Include IBM DB2 support. DIR is the DB2 base install directory, defaults to /home/db2inst1/sqllib.
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.
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.
Include Birdstep support. DIR is the Birdstep base install directory, defaults to /usr/local/birdstep.
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".
Include iODBC support. DIR is the iODBC base install directory, defaults to /usr/local.
Include Easysoft OOB support. DIR is the OOB base install directory, defaults to /usr/local/easysoft/oob/client.
Include unixODBC support. DIR is the unixODBC base install directory, defaults to /usr/local.
Include OpenLink ODBC support. DIR is the OpenLink base install directory, defaults to /usr/local. This is the same as iODBC.
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 support. Only applicable if iODBC, Adabas, Solid, Velocis or a custom ODBC interface is enabled. PHP 3 only!
Disable GD support. PHP 3 only!
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.
Include ming support.
Enable the security check for internal server redirects. You should use this if you are running the CGI version with Apache.
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.
Build PHP as FastCGI application.
Compile with debugging symbols.
Sets how installed files will be laid out. Type is one of PHP (default) or GNU.
Install PEAR in DIR (default PREFIX/lib/php).
Do not install PEAR.
Enable PHP's own SIGCHLD handler.
Disable passing additional runtime library search paths.
Enable explicitly linking against libgcc.
Include experimental php streams. Do not use unless you are testing the code!
Define the location of zlib install directory.
Include ASPELL support.
Include CCVS support.
Include CyberCash support. DIR is the CyberCash MCK install directory.
Include ICAP support.
Path to the ircg-config script.
Include ircg support.
Enable mailparse support.
Include muscat support.
Enable CORBA support via Satellite (EXPERIMENTAL) DIR is the base directory for ORBit.
Enable transparent session id propagation.
Use system regex library (deprecated).
Include vpopmail support.
Use POSIX threads (default).
Build shared libraries [default=yes].
Build static libraries [default=yes].
Optimize for fast installation [default=yes].
Assume the C compiler uses GNU ld [default=no].
Avoid locking (might break parallel builds).
Try to use only PIC/non-PIC objects [default=use both].
Compile with memory limit support.
Disable the URL-aware fopen wrapper that allows accessing files via HTTP or FTP.
Export only required symbols. See INSTALL for more information.
Include IMSp support (DIR is IMSP's include dir and libimsp.a dir). PHP 3 only!
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!
Include DAV support through Apache's mod_dav, DIR is mod_dav's installation directory (Apache module version only!) PHP 3 only!
Compile with remote debugging functions. PHP 3 only!
Take advantage of versioning and scoping provided by Solaris 2.x and Linux. PHP 3 only!
Enable make rules and dependencies not useful (and sometimes confusing) to the casual installer.
Sets the path in which to look for php.ini, defaults to PREFIX/lib.
Enable safe mode by default.
Only allow executables in DIR when in safe mode defaults to /usr/local/php/bin.
Enable magic quotes by default.
Disable the short-form <? start tag by default.
Specify path to the installed AOLserver.
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.
Build Apache module. DIR is the top-level Apache build directory, defaults to /usr/local/apache.
Enable transfer tables for mod_charset (Rus Apache).
Build shared Apache 2.0 module. FILE is the optional pathname to the Apache apxs tool; defaults to apxs.
Build fhttpd module. DIR is the fhttpd sources directory, defaults to /usr/local/src/fhttpd.
Build PHP as an ISAPI module for use with Zeus.
Specify path to the installed Netscape Server.
No information yet.
Build PHP as a module for use with Pi3Web.
Build PHP as a Pike module. DIR is the base Roxen directory, normally /usr/local/roxen/server.
Build the Roxen module using Zend Thread Safety.
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.
Build PHP as thttpd module.
Build PHP as a TUX module (Linux only).
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
|
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.
Isso define o valor da variável especificada.
Isto é usado para definir uma opção de configuração Booleana.
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.
Isto é usado para definir uma opção de configuração Booleana.
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
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().
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.
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.
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.
O número de dígitos significantes exibidos em números de ponto flutuante.
Força a especificação Ano 2002 (poderá causar problemas com browsers não compatíveis)
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.
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.
Descrição resumida das diretivas de configuração.
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.
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.
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.
O separador de parâmetros em URLs geradas pelo PHP.
Lista dos separador(es) utilizados pelo PHP para interpretar URLs em variáveis.
Nota: Cada caracter nesta diretiva é considerado como um separador!
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.
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 .
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.
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.
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.
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.
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.
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.
Sempre preenche a variável $HTTP_RAW_POST_DATA.
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.
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.
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.
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.
O caminho base do usado como diretório home do usuário para arquivos PHP, por exemplo public_html.
Diretório de onde o PHP poderá carregar dinamicamente as extensões. Veja também enable_dl e dl().
Que extensões dinamicamente carregáveis devem ser carregadas quando o PHP inicia.
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.
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 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.
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.
Permite ou não upload de arquivos HTTP. Veja também upload_max_filesize, upload_tmp_dir e post_max_size directives.
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.
O tamanho máximo de um arquivo para upload.
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.
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.
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.
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.
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).
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.
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.
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:
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.
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.
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-2. ... A filesystem attack
|
Only allow limited permissions to the PHP web user binary.
Check all variables which are submitted.
Exemplo 5-3. More secure file name checking
|
Exemplo 5-4. More secure file name checking
|
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.
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.
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.
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.
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
|
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)
|
// 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; |
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.
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.
// $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.
$query = "SELECT * FROM products WHERE id LIKE '%a%' exec master..xp_cmdshell 'net user test testpass /ADD'--"; $result = mssql_query($query); |
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.
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
|
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.
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:
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:
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.
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-16. Detecting simple variable poisoning
|
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
|
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?
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).
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:
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.
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
|
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:
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:
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.
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.
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.
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.
Para especificar um literal booleano, use as palavras chave TRUE ou FALSE. Ambas são insensitivas ao caso.
Usualmente você pode utilizar algum tipo de operador que retorne um valor booleano, e passá-lo para uma estrutura de controle.
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:
o booleano FALSE
o inteiro 0 (zero)
o ponto flutuante 0.0 (zero)
um array sem elementos
um objeto sem elementos
o tipo especial NULL (incluindo variáveis não definidas)
Atenção |
-1 é considerado TRUE, como qualquer valor não zero (negativos ou positivos)! |
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
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.
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.
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.
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. Para maiores informações, veja o alerta sobre a precisão de número flutuante.. |
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 (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; |
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. |
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.
Uma string literal pode ser especificada de três formas diferentes.
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 |
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.
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
|
Nota: O suporte a heredoc foi acrescentado no PHP 4.
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.
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.
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}}"; |
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
|
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.
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.
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.
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 |
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 |
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.
foreach existe especificamente para lidar com arrays. Ele provém uma maneira fácil de percorrer qualquer array.
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:
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:
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"; |
$error_descriptions[1] = "Um erro fatal ocorreu"; $error_descriptions[2] = "O PHP emitiu um alarme"; $error_descriptions[8] = "Apenas um aviso informal"; |
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.
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.
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()
|
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:
Este exemplo cria um array na base 1.
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.
Porque o valor de um array pode ser qualquer coisa, isto pode ser outro array. Isto pode criar arrays recursivos e multidimensionais.
Para inicializar um objeto, você usa a instrução new, criando uma instância do objeto em uma variável.
Para uma explicação completa, consulte a seção Classes e Objetos.
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
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.
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().
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.
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
|
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.
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.
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.
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:
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:
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':
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.
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
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.
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).
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).
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).
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).
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.
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).
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.
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.
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:
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:
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:
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:
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.
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:
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:
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:
produz a mesma saida que:
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. |
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:
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
|
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
|
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.
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:
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.
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()
|
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 */ ?> |
Nessa situação, é importante saber que o PHP automaticamente substituirá qualquer ponto nos nomes de variáveis recebidas com sublinhados.
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.
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.
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.
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.
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:
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:
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.
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 | |
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 |
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).
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:
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.
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, 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.
Esta expressão avalia para expr2 se expr1 é avaliada como TRUE, ou expr3 se expr1 é avaliada como FALSE.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. |
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).
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().
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"; ?> |
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.)
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.
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.
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:
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:
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:
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.
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:
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, 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.
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.
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:
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 é:
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:
Os exemplos a seguir são idênticos, e ambos imprimem números de 1 to 10:
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:
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'.
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 é:
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:
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.
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"; } |
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 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 é 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 " Meio<br>\n"; while (1) { echo " Dentro<br>\n"; continue 3; } echo "Isto nunca será exibido.<br>\n"; } echo "Nem isso.<br>\n"; } |
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.
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.
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.
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
|
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().
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.
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
|
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.
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
|
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
|
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
|
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.
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.
$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.
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().
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().
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.
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:
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:
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. |
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.
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.
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.
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. |
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().
Veja também: Variáveis variáveis e function_exists().
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
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.
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.
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(); |
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.
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.
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).
// 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 */ |
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.
Referências PHP permitem fazer duas variáveis se referirem ao mesmo conteúdo. Ou seja:
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):
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:
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.
Como dito anteriormente, referências não são ponteiros. Isto significa que o construtor seguinte não fará o que você espera:
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).
Você pode passar variáveis para funções por referência, então a função poderá modificar seus argumentos. A sintaxe é a seguinte:
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:
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:
Essas limitações valem para o PHP 4.0.4 em diante.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; |
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.
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:
não apaga $b, apenas $a.Novamente, é mais fácil pensar em analogia ao comando UNIX unlink.
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:
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
|
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
|
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.
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().
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:
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.
O nome original do arquivo no computador do usuário.
O tipo mime do arquivo, se o browser deu esta informação. Um exemplo pode ser "image/gif".
O tamanho, em bytes, do arquivo.
O nome temporário do arquivo, como foi guardado no servidor.
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.
|
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.
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'].
Valor: 0; não houve erro, o upload foi bem sucedido.
Valor 1; O arquivo no upload é maior do que o limite definido em upload_max_filesize no php.ini.
Valor: 2; O arquivo ultrapassa o limite de tamanho em MAX_FILE_SIZE que foi especificado no formulário html.
Valor: 3; o upload do arquivo foi feito parcialmente.
Valor: 4; Não foi feito o upload do arquivo.
Nota: Estas tornaram-se constantes no PHP 4.3.0
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.
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.
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.
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
|
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:
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:
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:
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.
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
|
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.)
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.
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().
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.
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 |
Here is a short explanation of the configuration directives.
Whether to enable PHP's safe mode. Read the Security and chapter for more information.
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.
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/"
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.
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!
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.
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.
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 |
<?php readfile('/etc/passwd'); ?> |
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> |
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 |
Warning: readfile() has been disabled for security reasons in /docroot/script.php on line 2 |
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 | ?? |
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
| |
STDOUT | Um stream já aberto para o stdout. Isto economiza ter de abrí-lo com
| |
STDERR | Um stream já aberto para o stderr. Isto economiza ter de abrí-lo com
|
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");' |
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 |
Utilizando a versão CLI SAPI:
$ pwd /tmp $ php -f outro_diretorio/test.php /tmp |
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:
Chamando o PHP para executar um arquivo determinado.
php my_script.php php -f my_script.php |
Passar o código PHP para execução diretamente a linha de comando.
php -r 'print_r(get_defined_constants());' |
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.
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 |
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); ?> |
$ chmod 755 teste $ ./test -h -- foo array(4) { [0]=> string(6) "./teste" [1]=> string(2) "-h" [2]=> string(2) "--" [3]=> string(3) "foo" } |
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.
| |||
-w |
Mostra o fonte sem comentários e espaços em branco.
| |||
-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:
| |||
-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:
| |||
-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:
Examples:
| |||
-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.
| |||
-m |
Utilizando essa opção, o PHP imprime os módulos PHP e Zend compilados (e carregados):
| |||
-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.
| |||
-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)
|
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:
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.
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.
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.
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.
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().
(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 elaIsto 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() é 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() 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().
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.
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().
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
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() é 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() é 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() é 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.
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.
Não há nenhuma instalação nescessária para utilizar estas funções, elas fazem parte do núcleo do PHP.
As constantes listadas abaixo estão sempre disponíveis como parte do núcleo do PHP.
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 é 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 é usada com array_multisort() para ordenar em ordem crescente.
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
(PHP 4 >= 4.2.0)
array_change_key_case -- Retorna um array com todas as chaves string em maiúsculo ou minúsculoarray_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.
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()
A saída deste programa será:
|
array_count_values() retorna um array utilizando os valores do array input como chaves e seus respectivos números de ocorrências como valores.
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().
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() 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.
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() 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.
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()
A saída deste programa seria:
|
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() 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.
(PHP 4 >= 4.3.0)
array_intersect_assoc -- Computes the intersection of arrays with additional index checkarray_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().
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() retorna um array contendo todos os valores de array1 que estão presentes nos outros argumentos. Note que as chaves são preservadas.
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() retorna TRUE se a chave key existe no array. key pode ser qualquer valor possível para uma chave de array.
Nota: O nome dessa função é key_exists() no PHP versão 4.0.6.
Veja também isset().
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()
A saída deste programa seria:
|
Nota: Essa função adicionada no PHP 4. Abaixo está uma implementação para aqueles que ainda usam PHP 3.
Veja também array_values().
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 2. array_map() - usando mais de um array
Resultará em:
|
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.
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() 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()
Neste caso $result será:
|
Veja também array_merge().
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()
Neste caso $result será:
|
Exemplo 2. Exemplo simples de array_merge()
Não esqueça que as chaves numéricas serão reordenadas!
Se você quer preservar os arrays e apenas concatená-los, o operador +:
|
Nota: Chaves coincidentes serão sobrescritas usando as regras de primeira ocorrência.
Veja também array_merge_recursive().
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.
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.
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() 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.
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.
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() 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; |
Retorna o novo número de elementos do array.
Veja também: array_pop(), array_shift(), e array_unshift().
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.
(PHP 4 >= 4.0.5)
array_reduce -- Reduz um array para um único valor através de um processo iterativo utilizando uma função.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.
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() 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()
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á:
|
Nota: O segundo argumento foi adicionado no PHP 4.0.3.
(PHP 4 >= 4.0.5)
array_search -- Procura por um valor em um array e retorna sua chave correspondente caso seja encontradoProcura 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() 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.
Veja também array_unshift(), array_push() e array_pop().
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()
|
Veja também array_splice().
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()
|
Veja também array_slice().
array_sum() retorna a soma dos valores de um array como inteiro ou real.
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() 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! |
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.
Veja também array_shift(), array_push() e array_pop().
array_values() retorna todos os valores do array input.
Nota: Essa função foi adicionada no PHP 4, abaixo segue uma implementação para aqueles que ainda usam PHP 3.
Veja também array_keys().
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()
A saída do programa acima seria:
|
Veja também array_map(), list(), foreach, each() e call_user_func_array().
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.
Esse exemplo cria um array com o índices a partir do 1.
Veja também array_pad(), list() e range().
(PHP 3, PHP 4 )
arsort -- Ordena um array em ordem descrescente mantendo a associação entre índices e valoresEsta 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()
A saída deste exemplo seria:
|
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().
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()
A saída desse programa seria:
|
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().
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.
Veja também extract().
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.
Veja também is_array(), isset() e strlen().
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(). |
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()
$bar agora contém os seguintes pares de chaves e valores:
$bar agora contém os seguintes pares de chaves e valores:
|
each() é tipicamente usada em conjunto com list() para percorrer um array; por exemplo, $_POST:
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() avança o ponteiro interno de array até o seu último elemento, e retorna esse elemento.
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:
Se houver uma colisão, sobrescreve a variável existente.
Se houver uma colisão, não sobrescreve a variável existente.
Se houver uma colisão, adiciona um prefixo ao nome da variável definido pelo argumento prefix.
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.
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.
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.
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.
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()
|
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().
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 3. Exemplo de in_array() passando um array para needle
A saída seria:
|
Veja também array_search().
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.
A saída deste programa seria:
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().
Ordena um array pelas chaves, mantendo a correlação entre as chaves e os valores. Essa função é bastante útil principalmente para arrays associativos.
O programa acima mostraria:
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.
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()
|
Exemplo 2. Exemplo de list()
|
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. |
array(3) { [2]=> string(8) "cafeína" [1]=> string(5) "marrom" [0]=> string(6) "café" } |
(PHP 4 )
natcasesort -- Ordena um array utilizando o algoritmo da "ordem natural" sem diferenciar maiúsculas e minúsculasEssa 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().
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:
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 ) |
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().
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(). |
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.
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.
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() retrocede o ponteiro interno de array para o primeiro elemento.
reset() retorna o valor do primeiro elemento do array.
Essa função ordena um array em ordem descrescente (do maior para o menor).
Esse exemplo mostraria:
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().
Essa função mistura de forma aleatória os elementos de um array. Você deve usar essa função em conjunto com srand().
Veja também arsort(), asort(), ksort(), rsort(), sort() e usort().
Essa função ordena um array. Os elementos serão ordenados do menor para o maior ao final da execução dessa função.
A saída desse programa seria:
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.
(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 valoresEssa 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().
(PHP 3>= 3.0.4, PHP 4 )
uksort -- Ordena um array pelas chaves utilizando uma função de comparação definida pelo usuário.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.
Esse exemplo mostraria:
Veja também usort(), uasort(), sort(), asort(), arsort(), ksort(), natsort() e rsort().
(PHP 3>= 3.0.3, PHP 4 )
usort -- Ordena um array pelos valores utilizando uma função de comparação definida pelo usuárioEssa 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.
Esse exemplo mostraria:
Nota: Obviamente que nesse caso trivial a função rsort() seria mais apropriada.
Exemplo 2. Exemplo de usort() usando um array multi-dimensional
|
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
|
Esse exemplo mostraria:
b c d |
Veja também uasort(), uksort(), sort(), asort(), arsort(),ksort(), natsort(), e rsort().
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.
(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]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.
aspell_check() checks the spelling of a word and returns TRUE if the spelling is correct, FALSE if not.
aspell_new() opens up a new dictionary and returns the dictionary link identifier for use in other aspell functions. Returns FALSE on error.
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.
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.
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.
O comportamento dessas funções podem ser modificado pelas configurações do php.ini.
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.
Número de casas decimais para todas as funções BC Math.
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().
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.
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().
Obter o módulo do operador_da_esquerda usando modulo.
Veja também bcdiv().
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().
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().
(PHP 5 CVS only)
bcpowmod -- Raise an arbitrary precision number to another, reduced by a specified modulus.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.
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.
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().
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().
As funções para bzip2 são usadas para ler e escrever, de forma transparente, arquivos compactados do tipo bzip2 (.bz2).
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.
Esta extensão define um tipo de recurso (resource): um ponteiro para arquivo que identifica o arquivo bzip2 que está sendo usado.
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
|
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() 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.
Veja também bzdecompress().
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.
Veja também bzcompress().
Retorna o número do erro de qualquer erro do bzip2 retornado pelo ponteiro de arquivo bz.
Veja também bzerror() e bzerrstr().
Retorna o número e string do erro, em um array associativo, de qualquer erro retornado pelo ponteiro de arquivo bz.
Veja também bzerrno() e bzerrstr().
Retorna a string de erro de qualquer erro retornado pelo ponteiro de arquivo 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.
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.
Veja também bzclose().
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.
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.
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.
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.
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.
The following constants are available since PHP 4.3.0 :
(PHP 4 >= 4.1.0)
cal_days_in_month -- Return the number of days in a month for a given year and calendarThis function will return the number of days in the month of year for the specified calendar.
See also jdtounix().
(PHP 4 >= 4.1.0)
cal_from_jd -- Converts from Julian Day Count to a supported calendar and return extended information
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
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).
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.
(PHP 3>= 3.0.9, PHP 4 )
easter_days -- Get number of days after March 21 on which Easter falls for a given yearReturns 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).
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().
(PHP 3, PHP 4 )
FrenchToJD -- Converts a date from the French Republican Calendar to a Julian Day CountConverts 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.
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.
Returns the day of the week. Can return a string or an integer depending on the 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 |
Converts a Julian Day Count to the French Republican Calendar.
Converts Julian Day Count to a string containing the Gregorian date in the format of "month/day/year".
Converts Julian Day Count to a string containing the Julian Calendar Date in the format of "month/day/year".
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().
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.
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. |
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().
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!
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.)
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.
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
(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
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
(4.0.2 - 4.2.3 only)
ccvs_count -- Find out how many transactions of a given type are stored in the system
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
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.
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.
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 |
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.
For further information on COM read the COM specification or perhaps take a look at Don Box's Yet Another COM Library (YACL)
The COM class provides a framework to integrate (D)COM components into your php scripts.
COM class constructor. Parameters:
name or class-id of the requested component.
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.
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)
|
Exemplo 2. COM example (2)
|
VARIANT class constructor. Parameters:
initial value. if omitted an VT_EMPTY object is created.
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.
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.
Returns the value of the property of the COM component referenced by com_object. Returns FALSE on error.
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.
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
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.
This function is an alias for com_get().
This function is an alias for com_set().
This function is an alias for com_set().
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).
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
|
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
|
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á:
(PHP 4 >= 4.0.5)
call_user_method_array -- Chama métodos de usuário dado uma matriz de parâmetros [obsoleto]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
(PHP 3>= 3.0.3, PHP 4 )
call_user_method -- Chama um método de usuário num objeto específico [obsoleto]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().
Esta função retorna TRUE se a classe dada por class_name foi definida, caso contrário retorna FALSE.
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:
Exemplo 1. Exemploget_class_methods()
|
Produzirá:
Veja também get_class_vars() e get_object_vars().
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()
|
Produzirá:
Veja também get_class_methods() e get_object_vars()
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().
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.
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()
|
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()!
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()
(PHP 4 >= 4.2.0)
is_a -- Retorna TRUE se o objeto é desta classe ou tem esta classe como uma de suas classes pai.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().
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().
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.
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.
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].
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.
Exemplo 1. Simple ClibPDF Example
|
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
|
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.
The cpdf_add_outline() function adds a bookmark with text text that points to the current page.
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().
The cpdf_begin_text() function starts a text section. It must be ended with cpdf_end_text().
See also cpdf_end_text().
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().
The cpdf_clip() function clips all drawing to the current path.
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().
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().
The cpdf_closepath_stroke() function is a combination of cpdf_closepath() and cpdf_stroke(). Then clears the path.
See also cpdf_closepath(), cpdf_stroke().
The cpdf_closepath() function closes the current path.
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().
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().
The cpdf_end_text() function ends a text section which was started with cpdf_begin_text().
See also cpdf_begin_text().
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().
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().
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().
The cpdf_finalize() function ends the document. You still have to call cpdf_close()
See also cpdf_close().
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().
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().
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().
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.
The cpdf_newpath() starts a new path on the document given by the pdf document parameter.
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().
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().
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().
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().
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.
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.
See also cpdf_save().
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().
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().
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
The cpdf_rotate() function set the rotation in degrees to angle.
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().
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().
The cpdf_scale() function set the scaling factor in both directions.
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
The cpdf_set_char_spacing() function sets the spacing between characters.
See also cpdf_set_word_spacing(), cpdf_set_leading().
The cpdf_set_creator() function sets the creator of a pdf document.
See also cpdf_set_subject(), cpdf_set_title(), cpdf_set_keywords().
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().
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
(PHP 4 >= 4.0.6)
cpdf_set_font_map_file -- Sets fontname to filename translation map when using external fonts
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
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.
The cpdf_set_horiz_scaling() function sets the horizontal scaling to scale percent.
The cpdf_set_keywords() function sets the keywords of a pdf document.
See also cpdf_set_title(), cpdf_set_creator(), cpdf_set_subject().
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().
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.
The cpdf_set_subject() function sets the subject of a pdf document.
See also cpdf_set_title(), cpdf_set_creator(), cpdf_set_keywords().
The cpdf_set_text_matrix() function sets a matrix which describes a transformation applied on the current text font.
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().
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.
The cpdf_set_text_rise() function sets the text rising to value units.
The cpdf_set_title() function sets the title of a pdf document.
See also cpdf_set_subject(), cpdf_set_creator(), cpdf_set_keywords().
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
The cpdf_set_word_spacing() function sets the spacing between words.
See also cpdf_set_char_spacing(), cpdf_set_leading().
The cpdf_setdash() function set the dash pattern white white units and black black units. If both are 0 a solid line is set.
The cpdf_setflat() function set the flatness to a value between 0 and 100.
The cpdf_setgray_fill() function sets the current gray value to fill a path.
See also cpdf_setrgbcolor_fill().
The cpdf_setgray_stroke() function sets the current drawing color to the given gray value.
See also cpdf_setrgbcolor_stroke().
The cpdf_setgray() function sets the current drawing and filling color to the given gray value.
See also cpdf_setrgbcolor_stroke(), cpdf_setrgbcolor_fill().
The cpdf_setlinecap() function set the linecap parameter between a value of 0 and 2. 0 = butt end, 1 = round, 2 = projecting square.
The cpdf_setlinejoin() function set the linejoin parameter between a value of 0 and 2. 0 = miter, 1 = round, 2 = bevel.
The cpdf_setlinewidth() function set the line width to width.
The cpdf_setmiterlimit() function set the miter limit to a value greater or equal than 1.
The cpdf_setrgbcolor_fill() function sets the current rgb color value to fill a path.
See also cpdf_setrgbcolor_stroke(), cpdf_setrgbcolor().
The cpdf_setrgbcolor_stroke() function sets the current drawing color to the given rgb color value.
See also cpdf_setrgbcolor_fill(), cpdf_setrgbcolor().
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().
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().
The cpdf_show() function outputs the string in text at the current position.
See also cpdf_text(), cpdf_begin_text(), cpdf_end_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().
The cpdf_stroke() function draws a line along current path.
See also cpdf_closepath(), cpdf_closepath_stroke().
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().
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.
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.
More information regarding CrackLib along with the library can be found at http://www.users.dircon.co.uk/~crypto/.
In order to use these functions, you must compile PHP with Crack support by using the --with-crack[=DIR] option.
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 |
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
|
Nota: If crack_check() returns TRUE, crack_getlastmessage() will return 'strong 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.
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.
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
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().
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.
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.
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)
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.
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:
This function closes a CURL session and frees all resources. The CURL handle, ch, is also deleted.
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
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).
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"
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.
See also: curl_close(), curl_setopt()
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.
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.
The function returns an associative array with the elements "errcode" and, if "errcode" is FALSE, "outbuff" (string), "outLth" (long) and "macbuff" (string).
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.
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.
cybermut_creerformulairecm() is used to generate the HTML form of request for payment.
Exemplo 1. First step of payment (equiv cgi1.c)
|
See also cybermut_testmac() and cybermut_creerreponsecm().
(4.0.5 - 4.2.3 only)
cybermut_creerreponsecm -- Generate the acknowledgement of delivery of the confirmation of paymentcybermut_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().
(4.0.5 - 4.2.3 only)
cybermut_testmac -- Make sure that there no was data diddling contained in the received message of confirmationcybermut_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)
|
See also cybermut_creerformulairecm() and cybermut_creerreponsecm().
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.
To enable Cyrus IMAP support and to use these functions you have to compile PHP with the --with-cyrus option.
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
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.
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.
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().
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().
Returns TRUE if every character in text has a special control function, FALSE otherwise. Control characters are e.g. line feed, tab, esc.
Returns TRUE if every character in text is a decimal digit, FALSE otherwise.
See also ctype_alnum() and ctype_xdigit().
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().
Returns TRUE if every character in text is a lowercase letter in the current locale.
See also ctype_alpha() and ctype_upper().
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().
(PHP 4 >= 4.0.4)
ctype_punct -- Check for any printable character which is not whitespace or an alphanumeric characterReturns 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().
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.
Returns TRUE if every character in text is a uppercase letter in the current locale.
See also ctype_alpha() and ctype_lower().
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().
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.)
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().
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].
|
db3 | To enable support for db3 add --with-db3[=DIR].
|
db4 | To enable support for db4 add --with-db4[=DIR].
|
cdb | To enable support for cdb add --with-cdb[=DIR].
|
flatfile | To enable support for flatfile add --with-flatfile.
|
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.
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.
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
|
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() 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() 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() 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() 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() 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() 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() returns an associative array with all open database files. This array is in the form: resourceid=>filename.
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() 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() 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() 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() 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() 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()
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.
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().
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.
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.
é possível usar date() e mktime() juntos para encontrar datas no futuro ou no passado.
Exemplo 3. date() e mktime() exemplo
|
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
|
Para formatar datas em outras línguas, você usaria as funções setlocale() e strftime() .
Veja também getlastmod(), gmdate(), mktime(), strftime() e time().
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"
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
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".
veja também date(), mktime(), gmmktime() e strftime().
Idêntico ao mktime() exceto que os parâmetros passados representam uma data GMT.
(PHP 3>= 3.0.12, PHP 4 )
gmstrftime -- Formata uma hora/data GMT/CUT de acordo com as configurações locaisMesmo 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".
Veja também strftime().
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
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
|
Veja também time().
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".
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".
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).
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.
Veja também setlocale() e mktime() e a Open Group specification de strftime().
(PHP 3>= 3.0.12, PHP 4 )
strtotime -- Analisa qualquer descrição em texto em inglês de data hora em timestamp UNIXA 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
|
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.)
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().
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.
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.
Closes the database associated with dbase_identifier.
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:
Boolean. These do not have a length or precision.
Memo. (Note that these aren't supported by PHP.) These do not have a length or precision.
Date (stored as YYYYMMDD). These do not have a length or precision.
Number. These have both a length and a precision (the number of digits after the decimal point).
String.
If the database is successfully created, a dbase_identifier is returned, otherwise FALSE is returned.
Exemplo 1. Creating a dBase database file
|
Marks record to be deleted from the database. To actually remove the record from the database, you must also call dbase_pack().
(PHP 3>= 3.0.4, PHP 4 )
dbase_get_record_with_names -- Gets a record from a dBase database as an associative arrayReturns 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
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
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).
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.
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.
Packs the specified database (permanently deleting all records marked for deletion using dbase_delete_record()).
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()).
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.
To use this functions you have to compile PHP with support for an underlying database. See the list of supported Databases.
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.
The function dbmopen() returns an database identifier which is used by the other dbm-functions.
Deletes the value for key in the database.
Returns FALSE if the key didn't exist in the database.
Returns TRUE if there is a value associated with the key.
Returns the value associated with key.
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.
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().)
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:
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.
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.
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:
FrontBase (available from PHP 4.1.0).
Sybase-CT (available from PHP 4.2.0).
Oracle (oci8) (available from PHP 4.3.0).
Documentation for adding additional database support to dbx can be found at http://www.guidance.nl/php/dbx/doc/.
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.
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 |
Nota: This ini-option is available available from PHP 4.3.0.
Here is a short explanation of the configuration directives.
Columns names can be returned "unchanged" or converted to "uppercase" or "lowercase". This directive can be overridden with a flag to dbx_query().
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.
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.
Retorna TRUE em caso de sucesso ou FALSE em falhas.
Nota: Always refer to the module-specific documentation as well.
See also: dbx_connect().
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
DBX_CMP_NATIVE - no type conversion
DBX_CMP_TEXT - compare items as strings
DBX_CMP_NUMBER - compare items numerically
Exemplo 1. dbx_compare() example
|
See also dbx_sort().
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:
It is the name of the currently selected database.
It is a valid handle for the connected database, and as such it can be used in module-specific functions (if required).
It is used internally by dbx only, and is actually the module number mentioned above.
Nota: Always refer to the module-specific documentation as well.
See also: dbx_close().
(PHP 4 >= 4.0.6)
dbx_error -- Report the error message of the latest function call in the module (not just in the connection)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.
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() returns the text, escaped where necessary (such as quotes, backslashes etc). It returns NULL on error.
Exemplo 1. dbx_escape_string() example
|
See also: dbx_query().
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
|
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.
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.
It provides info about columns, such as field names and field types.
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.
The case of the returned column names will not be changed.
The case of the returned column names will be changed to uppercase.
The case of the returned column names will be changed to lowercase.
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:
It is a valid handle for the connected database, and as such it can be used in module specific functions (if required).
These contain the number of columns (or fields) and rows (or records) respectively.
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.
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
|
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().
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
|
See also dbx_compare().
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. |
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.
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).
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.
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. 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 |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
(4.1.0 - 4.2.3 only)
dbplus_rcrtexact -- Creates an exact but empty copy of a relation including indicesAtenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
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.
One resource type is defined by this extension: a file descriptor returnded by dio_open().
The function dio_close() closes the file descriptor resource.
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.
(PHP 4 >= 4.2.0)
dio_open -- Opens a new filename with specified permissions of flags and creation permissions of modedio_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
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
(PHP 4 >= 4.2.0)
dio_read -- Reads n bytes from fd and returns them, if n is not specified, reads 1k blockThe 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.
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
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
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
|
Nota: This function was introduced in PHP 4.3.0.
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.
Não há nenhuma instalação nescessária para utilizar estas funções, elas fazem parte do núcleo do PHP.
Para funções relacionadas como dirname(), is_dir(), mkdir() e rmdir(), veja a seção Filesystem.
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().
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
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.
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.
Fecha o stream do diretório indicado por dir_handle. O stream deve ter sido previamente aberto por opendir().
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.
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 readdir() irá retornar o . e .. . Se você não quer estes simplesmente os retire:
Veja também is_dir().
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.
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.
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)
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(). |
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 |
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) |
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.
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
|
This function returns the name of the attribute.
See also domattribute_value().
(no version information, might be only in CVS)
DomAttribute->specified -- Checks if attribute is specifiedThis function returns the value of the attribute.
See also domattribute_name().
(no version information, might be only in CVS)
DomDocument->add_root [deprecated] -- Adds a root nodeAtenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
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().
(no version information, might be only in CVS)
DomDocument->create_cdata_section -- Create new cdata nodeThis 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().
(no version information, might be only in CVS)
DomDocument->create_comment -- Create new comment nodeThis 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().
(no version information, might be only in CVS)
DomDocument->create_element_ns -- Create new element node with an associated namespaceThis 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().
(no version information, might be only in CVS)
DomDocument->create_element -- Create new element nodeThis 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().
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().
(no version information, might be only in CVS)
DomDocument->create_processing_instruction -- Creates new PI nodeThis 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().
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().
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.
(no version information, might be only in CVS)
DomDocument->document_element -- Returns root element nodeThis 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.
(no version information, might be only in CVS)
DomDocument->dump_file -- Dumps the internal XML tree back into a fileCreates 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
|
See also domdocument_dump_mem() domdocument_html_dump_mem().
(no version information, might be only in CVS)
DomDocument->dump_mem -- Dumps the internal XML tree back into a stringAtenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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
|
Nota: The first parameter was added in PHP 4.3.0.
See also domdocument_dump_file(), domdocument_html_dump_mem().
(no version information, might be only in CVS)
DomDocument->get_element_by_id -- Searches for an element with a certain idThis 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()
See also domdocument_add_root()
(no version information, might be only in CVS)
DomDocument->html_dump_mem -- Dumps the internal XML tree back into a string as HTMLCreates 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
|
See also domdocument_dump_file(), domdocument_html_dump_mem().
(no version information, might be only in CVS)
DomDocument->xinclude -- Substitutes XIncludes in a DomDocument 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. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
(no version information, might be only in CVS)
DomDocumentType->internal_subset -- Returns internal subset
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
(no version information, might be only in CVS)
DomDocumentType->name -- Returns name of document typeThis function returns the name of the document type.
(no version information, might be only in CVS)
DomDocumentType->notations -- Returns list of notations
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
(no version information, might be only in CVS)
DomDocumentType->public_id -- Returns public id of document typeThis function returns the public id of the document type.
The following example echos nothing.
(no version information, might be only in CVS)
DomDocumentType->system_id -- Returns system id of document typeReturns the system id of the document type.
The following example echos '/share/sgml/Norman_Walsh/db3xml10/db3xml10.dtd'.
(no version information, might be only in CVS)
DomElement->get_attribute_node -- Returns value of attribute
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
(no version information, might be only in CVS)
DomElement->get_attribute -- Returns value of attributeReturns 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()
(no version information, might be only in CVS)
DomElement->get_elements_by_tagname -- Gets elements by tagname
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
(no version information, might be only in CVS)
DomElement->has_attribute -- Checks to see if attribute exists
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Sets an attribute with name name ot the given value. If the attribute does not exist, it will be created.
See also domelement_get_attribute()
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
(no version information, might be only in CVS)
DomNode->add_namespace -- Adds a namespace declaration to a node.See also domdocument_create_element_ns(), domnode_set_namespace()
(no version information, might be only in CVS)
DomNode->append_child -- Adds new child at the end of the childrenThis 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 3. Adding a child
|
See also domnode_insert_before(), domnode_clone_node().
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().
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.
Returns all children of the node.
See also domnode_next_sibling(), domnode_previous_sibling().
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
See also domdocument_dump_mem().
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().
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
(no version information, might be only in CVS)
DomNode->has_attributess -- Checks if node has attributesThis function checks if the node has attributes.
See also domnode_has_child_nodes().
(no version information, might be only in CVS)
DomNode->has_child_nodes -- Checks if node has childrenThis function checks if the node has children.
See also domnode_child_nodes().
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
|
See also domnode_append_child().
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
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().
(no version information, might be only in CVS)
DomNode->next_sibling -- Returns the next sibling of nodeThis 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
|
See also domnode_previous_sibling().
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 |
Returns the type of the node. All possible types are listed in the table in the introduction.
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 |
(no version information, might be only in CVS)
DomNode->owner_document -- Returns the document this node belongs toThis function returns the document the current node belongs to.
The following example will create two identical lists of children.
See also domnode_insert_before().
(no version information, might be only in CVS)
DomNode->parent_node -- Returns the parent of the nodeThis 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.
(no version information, might be only in CVS)
DomNode->previous_sibling -- Returns the previous sibling of nodeThis 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().
(no version information, might be only in CVS)
DomNode->remove_child -- Removes child from list of childrenThis 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
|
See also domnode_append_child().
(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()
(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()
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
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()
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
(no version information, might be only in CVS)
DomProcessingInstruction->data -- Returns data of pi node
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
(no version information, might be only in CVS)
DomProcessingInstruction->target -- Returns target of pi node
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
(no version information, might be only in CVS)
DomXsltStylesheet->process -- Applies the XSLT-Transformation on a DomDocument 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 domxml_xslt_stylesheet(), domxml_xslt_stylesheet_file(), domxml_xslt_stylesheet_doc()
(no version information, might be only in CVS)
DomXsltStylesheet->result_dump_file -- Dumps the result from a XSLT-Transformation into a fileAtenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
See also domxml_xslt_result_dump_mem(), domxml_xslt_process()
(no version information, might be only in CVS)
DomXsltStylesheet->result_dump_mem -- Dumps the result from a XSLT-Transformation back into a stringAtenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
See also domxml_xslt_result_dump_file(), domxml_xslt_process()
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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()
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.
See also domxml_open_mem(), domxml_new_doc().
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.
See also domxml_open_file(), domxml_new_doc().
This function returns the version of the XML library version currently used.
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
(PHP 4 >= 4.2.0)
domxml_xslt_stylesheet_doc -- Creates a DomXsltStylesheet Object from a DomDocument 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()
(PHP 4 >= 4.2.0)
domxml_xslt_stylesheet_file -- Creates a DomXsltStylesheet Object from a xsl document in a 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()
(PHP 4 >= 4.2.0)
domxml_xslt_stylesheet -- Creates a DomXsltStylesheet Object from a xml document in a 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. |
See also domxsltstylesheet->process(), domxml_xslt_stylesheet_file(), domxml_xslt_stylesheet_doc()
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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()
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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()
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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()
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
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.
Não há nenhuma instalação nescessária para utilizar estas funções, elas fazem parte do núcleo do PHP.
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?? |
Here is a short explanation of the configuration directives.
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.
This determines whether errors should be printed to the screen as part of the HTML output or not.
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.
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.
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.
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 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.
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
If enabled, the last error message will always be present in the variable $php_errormsg.
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.
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.
See docref_root.
Nota: The value of docref_ext must begin with a dot '.'.
String to output before an error message.
String to output after an error message.
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().
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 (.).
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.
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
|
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
|
See also trigger_error().
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
|
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
|
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().
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()
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()
|
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()
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:
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()
This is an alias for the function trigger_error().
See also error_reporting(), set_error_handler(), restore_error_handler(), and trigger_error()
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.
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/.
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.
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 |
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_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() 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()
(no version information, might be only in CVS)
fbsql_change_user -- Change logged in user of the active connectionfbsql_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.
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.
See also: fbsql_connect() and fbsql_pconnect().
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()
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().
See also fbsql_pconnect() and fbsql_close().
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
|
See also: fbsql_create_clob(), fbsql_read_blob(), fbsql_read_clob(), and fbsql_set_lob_mode().
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
|
See also: fbsql_create_blob(), fbsql_read_blob(), fbsql_read_clob(), and fbsql_set_lob_mode().
fbsql_create_db() attempts to create a new database on the server associated with the specified link identifier.
See also: fbsql_drop_db().
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
|
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
|
See also: fbsql_connect(), fbsql_pconnect() and fbsql_select_db().
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
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().
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().
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.
(PHP 4 >= 4.0.6)
fbsql_errno -- Returns the numerical value of the error message from previous FrontBase operationReturns 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().
(PHP 4 >= 4.0.6)
fbsql_error -- Returns the text of the error message from previous FrontBase operationReturns 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().
(PHP 4 >= 4.0.6)
fbsql_fetch_array -- Fetch a result row as an associative array, a numeric array, or bothReturns 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.
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
|
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().
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
|
See also fbsql_field_seek().
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().
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).
See also: fbsql_fetch_array() and fbsql_fetch_row().
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() 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() returns the length of the specified field.
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.
The above example would produce the following output:
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().
Returns the name of the table that the specified field is in.
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
|
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.
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
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() will return a result pointer containing the databases available from the current fbsql daemon. Use the fbsql_tablename() function to traverse this result pointer.
The above example would produce the following output:
Nota: The above code would just as easily work with fbsql_fetch_row() or other similar functions.
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.
The above example would produce the following output:
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.
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
|
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() 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().
See also: fbsql_affected_rows(), fbsql_connect(), fbsql_select_db(), and fbsql_query().
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
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() 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:
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:
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().
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
|
See also: fbsql_create_blob(), fbsql_read_blob(), fbsql_read_clob(), and fbsql_set_lob_mode().
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
|
See also: fbsql_create_blob(), fbsql_read_blob(), fbsql_read_clob(), and fbsql_set_lob_mode().
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().
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()
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().
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().
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Retorna TRUE em caso de sucesso ou FALSE em falhas.
fbsql_start_db()
See also: fbsql_db_status() and fbsql_stop_db().
Retorna TRUE em caso de sucesso ou FALSE em falhas.
fbsql_stop_db()
See also: fbsql_db_status() and fbsql_start_db().
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.
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
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/.
Returns the number of fields (columns) in the opened filePro database.
See also filepro().
Returns the name of the field corresponding to field_number.
Returns the edit type of the field corresponding to field_number.
Returns the width of the field corresponding to 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.
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().
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.
Não há nenhuma instalação nescessária para utilizar estas funções, elas fazem parte do núcleo do PHP.
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.
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. |
Define o user agent que o PHP irá enviar.
Timeout padrão (em segundos) para streams baseados em socket.
Nota: Esta opção de configuração foi incluida no PHP 4.3.
Define a senha do FTP anonimo (seu endereço de e-mail).
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.
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.
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 (/).
Nota: O parametro sufixo foi adicionado no PHP 4.1.0.
Veja também: dirname()
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.
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.
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().
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().
Faz uma cópia de um arquivo. Retorna TRUE se a copia é obtida com sucesso, caso contrário FALSE.
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.
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.
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 (/).
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().
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.
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.
Este é um sinônimo obsoleto para a função disk_free_space(). Ultilize aquela função ao invez.
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().
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().
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().
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().
(PHP 3>= 3.0.8, PHP 4 )
fgetcsv -- Le uma linha do ponteiro de arquivos e a interpreta por campos CSVSimilar à 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.
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:
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().
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().
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.
Veja também is_readable(), is_writable(), is_file() e file().
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().
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().
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.
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.
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.
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.
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().
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.
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.
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.
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().
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() 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.
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() 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.
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.
Veja também: Apêndice I, fclose(), fgets(), fsockopen(), file(), file_exists(), is_readable(), socket_set_timeout() e popen().
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() é 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() 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().
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.
Veja também fread(), fgets(), fgetss(), sscanf(), printf() e sprintf().
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.
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:
device
inode
número de links
user id do dono (owner)
group id (owner)
tipo de device se inode device *
tamanho em bytes
tempo do último acesso
tempo da última modificação(modification)
tempo da última mudança(change)
tamanho do bloco para o filesystem I/O *
número de blocos alocados
Os resultados desta função são guardados em cache. Veja clearstatcache() para mais detalhes.
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().
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() 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
|
Veja também fread(), fopen(), fsockopen(), popen() e fputs().
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.
Resultado possível do exemplo acima:
|
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).
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().
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.
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.
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.
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().
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.
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().
Esta é uma função sinônima (alias) para is_writable()
link() cria um hard link.
Veja também symlink() para criar soft links, e readlink() assim como linkinfo().
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().
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:
device
inode
inode protection mode
number of links
user id of owner
group id owner
device type if inode device *
size in bytes
time of last access
time of last modification
time of last change
blocksize for filesystem I/O *
number of blocks allocated
lstat() não pode ser utilizado em arquivos remotos.
Os resultados desta função são guardados em cache. Veja clearstatcache() para mais detalhes.
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().
Retorna TRUE em caso de sucesso ou FALSE em falhas.
Veja também rmdir().
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() 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. |
Irá produzir:
pathinfo() retorna um array associatico contendo informações sobre o path. O seguinte elementos do array são retornados: dirname, basename e extension.
Produzirá:
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().
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().
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().
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.
Veja também pclose(), fopen() e proc_open().
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() 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() 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.
Veja também: basename(), dirname() e pathinfo().
Tenta renomear nomeantigo para novonome.
Retorna TRUE em caso de sucesso ou FALSE em falhas.
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.
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.
Pegar estatísticas sobre o arquivo com o nome de nomedoarquivo.
Retorna um array com as estatísticas do arquivo com os seguintes elementos:
device
inode
inode protection mode
número de links
user id owner
group id owner
device type if inode device *
tamanho em bytes
time of last access
time of last modification
time of last change
blocksize for filesystem I/O *
number of blocks allocated
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() 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().
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.
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.
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.
Veja também tempnam().
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.
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.
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.
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..
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.
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)
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().
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.
The following examples shows just the evaluation of form data.
Exemplo 1. Evaluating a FDF document
|
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
will create a FDF like this:
|
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
The fdf_close() function closes the FDF document.
See also fdf_open().
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
|
See also fdf_close(), fdf_save(), fdf_open().
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() 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().
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.
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
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().
The fdf_set_file() returns the value of the /F key.
See also fdf_set_file().
The fdf_get_status() returns the value of the /STATUS key.
See also fdf_set_status().
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().
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().
This is a convenience function to set appropriate HTTP headers for FDF output. It sets the Content-type: to application/vnd.fdf.
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.
See also fdf_enum_fields() and fdf_get_value().
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.
See also fdf_open(), fdf_close(), fdf_create() and fdf_save_string().
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.
See also fdf_open_string(), fdf_close(), fdf_create() and fdf_save().
The fdf_save_string() function returns the FDF document as a string.
Exemplo 1. Retrieving FDF as a string
will output something like
|
See also fdf_save(), fdf_open_string(), fdf_create() and fdf_close().
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().
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() 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.
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
|
See also fdf_get_file() and fdf_set_target_frame().
The fdf_set_flags() sets certain flags of the given field fieldname.
See also fdf_set_opt().
fdf_set_javascript_action() sets a javascript action for the given field fieldname.
See also fdf_set_submit_form_action().
The fdf_set_opt() sets options of the given field fieldname.
See also fdf_set_flags().
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().
The fdf_set_submit_form_action() sets a submit form action for the given field fieldname.
See also fdf_set_javascript_action().
Sets the target frame to display a result PDF defined with fdf_save_file() in.
See also fdf_save_file().
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().
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().
FriBiDi is a free implementation of the Unicode Bidirectional Algorithm.
To enable FriBiDi support in PHP you must compile --with-fribidi[=DIR] where DIR is the FriBiDi install directory.
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
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.
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.
This extension uses one resource type, which is the link identifier of the FTP connection, returned by ftp_connect().
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.
The following constants were introduced in PHP 4.3.0.
See ftp_set_option() for information.
Automatically determine resume position and start position for GET and PUT requests (only works if FTP_AUTOSEEK is enabled)
Asynchronous transfer has failed
Asynchronous transfer has finished
Asynchronous transfer is still active
Exemplo 1. FTP example
|
Changes to the parent directory.
Retorna TRUE em caso de sucesso ou FALSE em falhas.
Changes to the specified directory.
Returns TRUE on success or FALSE on error.
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() 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()
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() deletes the file specified by path from the FTP server.
Retorna TRUE em caso de sucesso ou FALSE em falhas.
Sends a SITE EXEC command request to the FTP server. Returns the output of the command if successful; otherwise returns FALSE.
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() 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.
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. |
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().
Logs in to the given FTP stream.
Retorna TRUE em caso de sucesso ou FALSE em falhas.
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.
Creates the specified directory.
Returns the newly created directory name on success or FALSE on error.
Continues retrieving/sending a file nbronously
Returns FTP_FAILED or FTP_FINISHED or FTP_MOREDATA.
(PHP 4 >= 4.3.0)
ftp_nb_fget -- Retrieves a file from the FTP server and writes it to an open file (non-blocking)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() 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().
(PHP 4 >= 4.3.0)
ftp_nb_get -- Retrieves a file from the FTP server and writes it to a local file (non-blocking)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
|
Exemplo 2. Resuming a download with ftp_nb_get()
|
Exemplo 3. Resuming a download at position 100 to a new file with ftp_nb_get()
|
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() 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
|
Exemplo 2. Resuming an upload with ftp_nb_put()
|
See also ftp_nb_fput(), ftp_nb_continue(), ftp_put() and ftp_fput().
Returns an array of filenames from the specified directory on success or FALSE on error.
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() 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.
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() 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.
Removes the specified directory.
Retorna TRUE em caso de sucesso ou FALSE em falhas.
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. |
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() 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.
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()
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 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().
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()
|
Exemplo 2. Making a general processing function with create_function()
|
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%) |
Exemplo 3. Using anonymous functions as callback functions
|
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.
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.
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.
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"; } |
See also method_exists() and get_defined_functions().
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().
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().
Registers the function named by func to be executed when a tick is called.
De-registers the function named by function_name so it is no longer executed when a tick is called.
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.
To use these functions you must download and install the GNU gettext package from http://www.gnu.org/software/gettext/gettext.html
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
(PHP 4 >= 4.2.0)
bind_textdomain_codeset -- Specify the character encoding in which the messages from the DOMAIN message catalog will be returned
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
The bindtextdomain() function sets the path for a domain.
This function allows you to override the current domain for a single message lookup. It also allows you to specify a category.
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
The dgettext() function allows you to override the current domain for a single message lookup.
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
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
|
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
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.
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.
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.
In order to have these functions available, you must compile PHP with GMP support by using the --with-gmp option.
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.
More mathmatical functions can be found in the sections BCMath Arbitrary Precision Mathematics Functions and Mathematical Functions.
Add two GMP numbers. The result will be a GMP number representing the sum of the arguments.
Returns a positive value if a > b, zero if a = b and negative value if a < b.
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
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()
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.
See also gmp_div_q(), gmp_div_r().
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()
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.
Calculate greatest common divisor of a and b. The result is always positive even if either of, or both, input operands are negative.
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.
Returns the hamming distance between a and b. Both operands should be non-negative.
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.
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().
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(). |
Computes the inverse of a modulo b. Returns FALSE if an inverse does not exist.
Computes Jacobi symbol of a and p. p should be odd and must be positive.
Compute the Legendre symbol of a and p. p should be odd and must be positive.
Calculates n modulo d. The result is always non-negative, the sign of d is ignored.
Calculates logical inclusive OR of two GMP numbers.
Returns TRUE if a is a perfect square, FALSE otherwise.
See also: gmp_sqrt(), gmp_sqrtrm().
Raise base into power exp. The case of 0^0 yields 1. exp cannot be negative.
Calculate (base raised into power exp) modulo mod. If exp is negative, result is undefined.
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.
Generate a random number. The number will be between limiter and zero in value. If limiter is negative, negative numbers are generated.
Scans a, starting with bit start, towards more significant bits, until the first clear bit is found. Returns the index of the found bit.
Scans a, starting with bit start, towards more significant bits, until the first set bit is found. Returns the index of the found bit.
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.
Return sign of a - 1 if a is positive and -1 if it's negative.
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).
Convert GMP number to string representation in base base. The default base is 10. Allowed values for the base are from 2 to 36.
These functions let you manipulate the output sent back to the remote browser right down to the HTTP protocol level.
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:
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.
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.
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 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() 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()
|
See also ob_start(), trigger_error(), and header() for a more detailed discussion of the matters involved.
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:
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:
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.
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:
Number of object records with attribute PresentationHints set to Hidden.
Number of object records with attribute PresentationHints set to CollectionHead.
Number of object records with attribute PresentationHints set to FullCollectionHead.
Index in array of object records with attribute PresentationHints set to CollectionHead.
Index in array of object records with attribute PresentationHints set to FullCollectionHead.
Total: Number of object records.
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:
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: 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 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.
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 |
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.
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.
Converts an object_array into an object record. Multiple attributes like 'Title' in different languages are treated properly.
See also hw_objrec2array().
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
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.
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.
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.
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().
(PHP 3>= 3.0.3, PHP 4 )
hw_connection_info -- Prints information about the connection to Hyperwave server
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
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().
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().
Returns an th object id of the document to which anchorID belongs.
Returns an th object record of the document to which anchorID belongs.
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().
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.
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().
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().
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.
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
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().
Returns the last error number. If the return value is 0 no error has occurred. The error relates to the last command.
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.
Frees the memory occupied by the Hyperwave document.
Returns an array of object ids with anchors of the document with object ID objectID.
Returns an array of object records with anchors of the document with object ID 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().
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().
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().
Returns array of object ids for child documents of a collection.
See also hw_children(), and hw_getchildcoll().
Returns an array of object records for child documents of a collection.
See also hw_childrenobj(), and hw_getchildcollobj().
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().
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().
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().
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().
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().
Returns an indexed array of object ids. Each object id belongs to a parent of the object with ID 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.
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
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().
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().
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().
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().
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().
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.
Returns information about the current connection. The returned string has the following format: <Serverstring>, <Host>, <Port>, <Username>, <Port of Client>, <Byte swapping>
Inserts a new collection with attributes as in object_array into collection with object ID objectID.
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().
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
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().
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().
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
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().
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:
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.
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().
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().
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().
Prints the document without the BODY tag.
For backward compatibility, hw_outputdocument() is also accepted. This is deprecated, however.
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().
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().
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.
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Unlocks a document, so other users regain access.
See also hw_getandlock().
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.
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.
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.
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.
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 |
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
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().
(no version information, might be only in CVS)
hw_api_attribute->langdepvalue -- Returns value for a given languageReturns the value in the given language of the attribute.
See also hwapi_attribute_value().
(no version information, might be only in CVS)
hw_api_attribute->value -- Returns value of the attributeReturns the value of the attribute.
See also hwapi_attribute_key(), hwapi_attribute_values().
(no version information, might be only in CVS)
hw_api_attribute->values -- Returns all values of the attributeReturns all values of the attribute as an array of strings.
See also hwapi_attribute_value().
(no version information, might be only in CVS)
hw_api_attribute -- Creates instance of class hw_api_attributeCreates a new instance of hw_api_attribute with the given name and value.
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:
Checks in and commits the object. The object must be a document.
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.
Checks in an object even if it is not under version control.
Check if the new version is different from the last version. Unless this is the case the object will be checked in.
Keeps the time modified from the most recent object.
The object is not automatically commited on checkin.
See also hwapi_checkout().
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:
Checks out an object. The object must be a document.
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().
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().
Reads len bytes from the content into the given buffer.
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.
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().
(no version information, might be only in CVS)
hw_api->dbstat -- Returns statistics about database serverSee also hwapi_dcstat(), hwapi_hwstat(), hwapi_ftstat().
(no version information, might be only in CVS)
hw_api->dcstat -- Returns statistics about document cache serverSee also hwapi_hwstat(), hwapi_dbstat(), hwapi_ftstat().
(no version information, might be only in CVS)
hw_api->dstanchors -- Returns a list of all destination anchorsRetrieves 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().
(no version information, might be only in CVS)
hw_api->dstofsrcanchors -- Returns destination of a source anchorRetrieves 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().
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.
(no version information, might be only in CVS)
hw_api->ftstat -- Returns statistics about fulltext serverSee also hwapi_dcstat(), hwapi_dbstat(), hwapi_hwstat().
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().
(no version information, might be only in CVS)
hw_api->hwstat -- Returns statistics about Hyperwave serverSee also hwapi_dcstat(), hwapi_dbstat(), hwapi_ftstat().
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.
(no version information, might be only in CVS)
hw_api->info -- Returns information about server configurationSee also hwapi_dcstat(), hwapi_dbstat(), hwapi_ftstat(), hwapi_hwstat().
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:
The object in inserted into the server.
See also hwapi_replace().
(no version information, might be only in CVS)
hw_api->insertanchor -- Inserts a new object of type anchorThis 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().
(no version information, might be only in CVS)
hw_api->insertcollection -- Inserts a new object of type collectionThis 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().
(no version information, might be only in CVS)
hw_api->insertdocument -- Inserts a new object of type documentThis 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().
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().
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().
(no version information, might be only in CVS)
hw_api_content -- Create new instance of class hw_api_contentCreates a new content object from the string content. The mimetype is set to mimetype.
(no version information, might be only in CVS)
hw_api_object->attreditable -- Checks whether an attribute is editableAdds an attribute to the object. Returns TRUE on success and otherwise FALSE.
See also hwapi_object_remove().
(no version information, might be only in CVS)
hw_api_object -- Creates a new instance of class hw_api_objectRemoves the attribute with the given name. Returns TRUE on success and otherwise FALSE.
See also hwapi_object_insert().
Returns the value of the attribute with the given name or FALSE if an error occured.
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
|
See also hwapi_content().
(no version information, might be only in CVS)
hw_api->objectbyanchor -- Returns the object an anchor belongs toThis 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().
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().
(no version information, might be only in CVS)
hw_api_reason->description -- Returns description of reasonThis 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().
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:
The object on the server is replace with the object passed.
See also hwapi_insert().
(no version information, might be only in CVS)
hw_api->setcommitedversion -- Commits version other than last versionCommits 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().
(no version information, might be only in CVS)
hw_api->srcanchors -- Returns a list of all source anchorsRetrieves 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().
(no version information, might be only in CVS)
hw_api->srcsofdst -- Returns source of a destination objectRetrieves 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().
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().
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.
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/.
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
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 |
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.
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 |
Exemplo 1. iconv_get_encoding() example:
The printout of the above program will be:
|
See also: iconv_set_encoding() and ob_iconv_handler().
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 |
See also: iconv_get_encoding() and ob_iconv_handler().
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.
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.
See also: iconv_get_encoding(), iconv_set_encoding(), and output-control functions.
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.
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.
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. |
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 |
Here is a short explanation of the configuration directives.
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 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 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 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 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 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.
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.
Exemplo 1. PNG creation with PHP
|
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().
(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.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
The first call fails because the image has no header information.
|
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() 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
|
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().
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()
|
See also: imagepng(), imagejpeg(), imagegif(), imagewbmp(), and imagetypes().
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.
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:
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.
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.
(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_imagetypeThe image_type_to_mime_type() function will determine the Mime-Type for an IMAGETYPE constant.
Nota: This function does not require the GD image library.
See also getimagesize(), exif_imagetype(), exif_read_data() and exif_thumbnail().
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() 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() 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() 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() 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() 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.
Returns -1 if the allocation failed.
(no version information, might be only in CVS)
imagecolorallocatealpha -- Allocate a color for an imageimagecolorallocatealpha() 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.
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:
See also imagecolorset() and imagecolorsforindex().
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().
(PHP 4 >= 4.0.6)
imagecolorclosestalpha -- Get the index of the closest color to the specified color + alphaReturns 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
(PHP 4 >= 4.0.1)
imagecolorclosesthwb -- Get the index of the color which has the hue, white and blackness nearest to the given color
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
The imagecolordeallocate() function de-allocates a color previously allocated with the imagecolorallocate() function.
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().
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
(PHP 3>= 3.0.2, PHP 4 )
imagecolorresolve -- Get the index of the specified color or its closest possible alternativeThis function is guaranteed to return a color index for a requested color, either the exact color or the closest possible alternative.
See also imagecolorclosest().
(PHP 4 >= 4.0.6)
imagecolorresolvealpha -- Get the index of the specified color + alpha or its closest possible alternativeThis 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
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().
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().
This returns the number of colors in the specified image's palette.
See also imagecolorat() and imagecolorsforindex().
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.
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.
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() 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() 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() 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() 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.
|
See also imagecreatetruecolor().
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. |
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. |
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() 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)
|
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() 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 )
|
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() 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)
|
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() returns an image identifier representing the image obtained from the given string.
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)
|
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() 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() 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() 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.
This function is deprecated. Use combination of imagesetstyle() and imageline() instead.
imagedestroy() frees any memory associated with image image. image is the image identifier returned by the imagecreate() function.
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() performs a flood fill starting at coordinate x, y (top left is 0, 0) with color col in the image image.
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:
IMG_ARC_PIE
IMG_ARC_CHORD
IMG_ARC_NOFILL
IMG_ARC_EDGED
Nota: This function was added in PHP 4.0.6 and requires GD 2.0.1
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() 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() 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() 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.
Returns the pixel height of a character in the specified font.
See also imagefontwidth() and imageloadfont().
Returns the pixel width of a character in font.
See also imagefontheight() and imageloadfont().
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
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.
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.
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
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:
See also imagepng(), imagewbmp(), imagejpeg(), imagetypes().
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() 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() 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() 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() copies the palette from the source image to the destination image.
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.
See also imagegif(), imagewbmp(), imagejpeg(), imagetypes().
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().
(PHP 3>= 3.0.9, PHP 4 )
imagepsbbox -- Give the bounding box of a text rectangle using PostScript Type1 fontsSize 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().
(PHP 3>= 3.0.9, PHP 4 )
imagepscopyfont -- Make a copy of an already loaded font for further modificationUse 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().
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.
Extend or condense a font (font_index), if the value of the extend parameter is less than one you will be condensing the font.
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().
Slant a font given by the font_index parameter with a slant of the value of the slant parameter.
(PHP 3>= 3.0.9, PHP 4 )
imagepstext -- To draw a text string over an image using PostScript Type1 fontsSize 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() 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.
Rotates the src_im image using a given angle in degree. bgd_color specifies the color of the uncovered zone after the rotation.
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() draws a pixel at x, y (top left is 0, 0) in image image of color col.
See also imagecreate() and imagecolorallocate().
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
|
See also imagesetbrush(), imageline().
Nota: This function was added in PHP 4.0.6
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() 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() 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() 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() returns the width of the image identified by image.
See also imagecreate() and imagesy().
imagesy() returns the height of the image identified by image.
See also imagecreate() and imagesx().
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
This function calculates and returns the bounding box in pixels for a TrueType text.
The string to be measured.
The font size in pixels.
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 in degrees in which text will be measured.
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 |
This function requires both the GD library and the FreeType library.
See also imagettftext().
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: {) 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
|
This function requires both the GD library and the FreeType library.
See also imagettfbbox().
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:
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().
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
(PHP 3>= 3.0.6, PHP 4 )
iptcparse -- Parse a binary IPTC http://www.iptc.org/ block into single tags.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.
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().
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().
Nota: The read_exif_data() function is an alias for exif_read_data().
See also exif_thumbnail().
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.
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.
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.
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.
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).
Convert an 8bit string to a quoted-printable string (according to RFC2045, section 6.7).
Returns a quoted-printable string.
See also imap_qprint().
(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 resetThis 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.
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
|
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().
Convert an 8bit string to a base64 string (according to RFC2045, Section 6.8).
Returns a base64 string.
See also imap_base64().
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.
(PHP 3>= 3.0.4, PHP 4 )
imap_bodystruct -- Read the structure of a specified body section of a specific message
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
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
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:
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() 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
|
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
|
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.
(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.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() deletes all the messages marked for deletion by imap_delete(), imap_mail_move(), or imap_setflag_full().
Returns TRUE.
(PHP 3>= 3.0.4, PHP 4 )
imap_fetch_overview -- Read an overview of the information in the headers of the given messageThis 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
|
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().
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)
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 |
See also: imap_fetchbody().
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
|
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
|
See also imap_open(), imap_set_quota(), imap_get_quotaroot().
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
|
See also imap_open(), imap_set_quota(), imap_get_quota().
(PHP 3>= 3.0.12, PHP 4 )
imap_getmailboxes -- Read the list of mailboxes, returning detailed information on each oneReturns 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
|
See also imap_getsubscribed().
This function is identical to imap_getmailboxes(), except that it only returns mailboxes that the user is subscribed to.
This function is an alias to imap_headerinfo() and is identical to it in every way.
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)
Returns an array of string formatted with header info. One element per mail message.
(PHP 3>= 3.0.12, PHP 4 )
imap_last_error -- This function returns the last IMAP error (if any) that occurred during this page requestThis 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.
Returns an array containing the names of the mailboxes. See imap_getmailboxes() for a description of ref and pattern.
Exemplo 1. imap_list() example
|
This function is an alias to imap_list() and is identical to it in every way.
(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 mailboxReturns 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.
This function is an alias to imap_lsub() and is identical to it in every way.
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.
(PHP 3>= 3.0.5, PHP 4 )
imap_mail_compose -- Create a MIME message based on given envelope and body sections
Exemplo 1. imap_mail_compose() example
|
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
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
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.
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
|
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".
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.
(PHP 3>= 3.0.3, PHP 4 )
imap_msgno -- This function returns the message sequence number for the given UIDThis function returns the message sequence number for the given UID. It is the inverse of imap_uid().
Return the number of messages in the current mailbox.
See also: imap_num_recent() and imap_status().
Returns the number of recent messages in the current mailbox.
See also: imap_num_msg() and imap_status().
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:
To connect to a POP3 server on port 110 on the local server, use: To connect to an SSL IMAP or POP3 server, add /ssl after the protocol specification: To connect to an SSL IMAP or POP3 server with a self-signed certificate, add /ssl/novalidate-cert after the protocol specification: To connect to an NNTP server on port 119 on the local server, use: 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
|
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.)
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().
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.
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.
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
|
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.
(PHP 3>= 3.0.2, PHP 4 )
imap_rfc822_write_address -- Returns a properly formatted email address given the mailbox, host, and personal info.Returns a properly formatted email address as defined in RFC2822 given the mailbox, host, and personal info.
(PHP 3, PHP 4 )
imap_scanmailbox -- Read the list of mailboxes, takes a string to search for in the text of the mailboxThis function is an alias to imap_listscan() and is identical to it in every way.
(PHP 3>= 3.0.12, PHP 4 )
imap_search -- This function returns an array of messages matching the given search criteriaThis 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.
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.
See also imap_open(), imap_set_quota().
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
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:
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:
(PHP 3>= 3.0.4, PHP 4 )
imap_status -- This function returns status information on a mailbox other than the current oneThis 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
|
Subscribe to a new mailbox.
Returns TRUE on success and FALSE on error.
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
(PHP 3>= 3.0.3, PHP 4 )
imap_uid -- This function returns the UID for the given message sequence numberThis 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.
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.
Unsubscribe from a specified mailbox.
Returns TRUE on success and FALSE on error.
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).
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.
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.
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.
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.
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 |
Here is a short explanation of the configuration directives.
Whether to allow persistent Informix connections.
The maximum number of persistent Informix connections per process.
The maximum number of Informix connections per process, including persistent connections.
The default host to connect to when no host is specified in ifx_connect() or ifx_pconnect(). Doesn't apply in safe mode.
The default user id to use when none is specified in ifx_connect() or ifx_pconnect(). Doesn't apply in safe mode.
The default password to use when none is specified in ifx_connect() or ifx_pconnect(). Doesn't apply in safe mode.
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().
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().
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().
Set to TRUE if you want to trim trailing spaces from CHAR columns when fetching them.
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().
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
|
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.
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.
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().
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().
Duplicates the given blob object. bid is the ID of the blob object.
Returns FALSE on error otherwise the new blob object-id.
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.
Creates an char object. param should be the char content.
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().
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()
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()
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
|
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".
Returns an associative array with fieldnames as key and the SQL fieldtypes as data for query with result_id. Returns FALSE on error.
Deletes the blobobject for the given blob object-id bid. Retorna TRUE em caso de sucesso ou FALSE em falhas.
Deletes the charobject for the given char object-id bid. Retorna TRUE em caso de sucesso ou FALSE em falhas.
Releases resources for the query associated with result_id. Returns FALSE on error.
Returns the content of the blob object for the given blob object-id bid.
Returns the content of the char object for the given char object-id bid.
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
|
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
|
Sets the default return value of a NULL-value on a fetch row. Mode "0" returns "", and mode "1" returns "NULL".
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.
Gives the number of rows fetched so far for a query with result_id after a ifx_query() or ifx_do() query.
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().
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().
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
|
Exemplo 2. Insert some values into the "catalog" table
|
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.
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.
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.
Deletes the slob object on the given slob object-id bid. Retorna TRUE em caso de sucesso ou FALSE em falhas.
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.
Deletes the slob object. bid is the Id of the slob object. Retorna TRUE em caso de sucesso ou FALSE em falhas.
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.
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.
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.
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.
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!
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.
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 |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
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.
Commits transaction trans_number which was created with ibase_trans().
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
|
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().
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.
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().
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.
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"; } |
Free's a result set the has been created by ibase_query().
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() 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.
(PHP 3>= 3.0.6, PHP 4 )
ibase_prepare -- Prepare a query for later binding of parameter placeholders and executionPrepare a query for later binding of parameter placeholders and execution (via ibase_execute()).
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().
Rolls back transaction trans_number which was created with ibase_trans().
(PHP 3>= 3.0.6, PHP 4 )
ibase_timefmt -- Sets the format of timestamp, date and time type columns returned from queriesSets 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.
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. |
To compile PHP with Ingres support, you need the Open API library and header files included with Ingres II.
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.
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 |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
See also ingres_pconnect() and ingres_close().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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).
See also ingres_query(), ingres_num_fields(), ingres_field_name(), ingres_fetch_object(), and ingres_fetch_row().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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).
See also ingres_query(), ingres_num_fields(), ingres_field_name(), ingres_fetch_array(), and ingres_fetch_row().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
See also ingres_num_fields(), ingres_query(), ingres_fetch_array(), and ingres_fetch_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. |
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().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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:
close (see ingres_close())
commit (see ingres_commit())
connect (see ingres_connect())
disconnect (see ingres_close())
get dbevent
prepare to commit
rollback (see ingres_rollback())
savepoint
set autocommit (see ingres_autocommit())
all cursor related queries are unsupported
See also ingres_fetch_array(), ingres_fetch_object(), ingres_fetch_row(), ingres_commit(), ingres_rollback(), and ingres_autocommit().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
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
Detailed installation instructions can be found here. We urge you to use the provided installation script.
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() will close a connection to a server previously established with ircg_pconnect().
See also: ircg_pconnect().
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.
Function ircg_get_username() returns the username for the specified connection connection. Returns FALSE if connection died or is not valid.
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.
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().
This function removes user nick from the IRCG ignore list associated with connection.
See also: ircg_ignore_add().
ircg_is_conn_alive() returns TRUE if connection is still alive and working or FALSE, if the connection has died for some reason.
Join the channel channel on the server connected to by connection. IRCG will optionally pass the room key key.
Kick user nick from channel on server connected to by connection. reason should give a short message describing why this action was performed.
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() 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.
Change your nickname on the given connection to the one given in nick, if possible.
Will return TRUE on success and FALSE on failure.
Function ircg_nickname_escape() returns an encoded nickname specified by nick wich is IRC-compliant.
See also: ircg_nickname_unescape()
Function ircg_nickname_unescape() returns a decoded nickname, which is specified in nick.
See also: ircg_nickname_escape()
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.
Leave the channel channel on the server connected to by connection.
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().
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().
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().
Function ircg_set_file() specifies a logfile path in which all output from connection connection will be logged. Returns TRUE on success, otherwise FALSE.
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.
Change the topic for channel channel on the server connected to by connection to new_topic.
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. |
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)
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 |
Exemplo 1. Java Example
|
Exemplo 2. AWT Example
|
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.
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.
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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
|
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.
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.
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)
O comportamento dessas funções podem ser modificado pelas configurações do php.ini.
For further details and definition of the PHP_INI_* constants see ini_set().
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.
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
|
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"
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
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.
Exemplo 1. Complete example with authenticated bind
|
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
|
Exemplo 2. Using LDAP Bind Anonymously
|
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().
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
|
Atenção |
ldap_compare() can NOT be used to compare BINARY values! |
Nota: This function was added in 4.0.2.
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 2. Example of connecting securely to LDAP server.
|
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.
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() function is used to turn a DN, specified by dn, into a more user-friendly form, stripping off type names.
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().
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
|
See also ldap_err2str() and ldap_error().
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() 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.
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()
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().
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
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.
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
|
See also ldap_first_attribute() and ldap_next_attribute()
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.
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()
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
See also ldap_set_option().
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.
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
|
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
|
Nota: From 4.0.5 on it's also possible to do parallel searches. See ldap_search() for details.
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.
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.
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.
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().
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()
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()
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
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.
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.
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
|
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.
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 2. Set server controls
|
See also ldap_get_option().
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
A função mail() te permite enviar email
Não há nenhuma instalação nescessária para utilizar estas funções, elas fazem parte do núcleo do PHP.
Diretivas de configuração para Mail
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().
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.
O "From:" endereço de email seria usado no envio de PHP em Windows.
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.
ezmlm_hash() calcula valor do hash necessário quando mantendo listas de email EZMLM num banco de dados MySQL .
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. |
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).
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.
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.
|
Nota: Certifique-se que você não tem nenhum caractere novalinha em to ou subject, ou o email não será enviado corretamente.
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. |
(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-ableAtenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
(4.1.0 - 4.1.2 only)
mailparse_msg_extract_part_file -- Extracts/decodes a message section, decoding the transfer encodingAtenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
(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"Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
(4.1.0 - 4.1.2 only)
mailparse_msg_get_part_data -- Returns an associative array of info about the messageAtenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
(4.1.0 - 4.1.2 only)
mailparse_msg_get_structure -- Returns an array of mime section names in the supplied messageAtenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
(4.1.0 - 4.1.2 only)
mailparse_msg_parse_file -- Parse file and return a resource representing the structureAtenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
(4.1.0 - 4.1.2 only)
mailparse_rfc822_parse_addresses -- Parse addresses and returns a hash containing that dataAtenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
(4.1.0 - 4.1.2 only)
mailparse_stream_encode -- Streams data from source file pointer, apply encoding and write to destfpAtenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
(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 informationAtenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
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.
Não há nenhuma instalação nescessária para utilizar estas funções, elas fazem parte do núcleo do PHP.
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] |
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).
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().
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
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().
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
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).
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().
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
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.
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().
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.
cos() retorna o coseno de arg. O parametro arg deve estar em radianos.
Retorna o coseno hiperbólico de arg, definido por (exp(arg) + exp(-arg))/2.
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().
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().
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().
Esta função converte numero de graus ao equivalente em radianos.
Veja também rad2deg().
(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.Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
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.
(PHP 4 >= 4.2.0)
fmod -- Returns the floating point remainder (modulo) of the division of the argumentsReturns 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.
Retorna o valor máximo que pode ser gerado em uma chamada a função rand().
Veja também rand(), srand() e mt_getrandmax().
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.
Veja também dechex().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Retorna TRUE se val é número finito legal dentro dos limites permitidos para um número float PHP nesta plataforma.
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.
Retona TRUE se val 'não for um número', como o resultado de acos(1.01).
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.
(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.Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
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() 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().
Retorna o maior valor que pode ser obtido numa chamada a mt_rand().
Veja também mt_rand(), mt_srand() e getrandmax().
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().
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().
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().
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().
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.
Atenção |
No PHP 4.0.6 e posteriores, pow() sempre retornará um float, e não gerará avisos de erros. |
Esta função converte number de radianos para graus.
Veja também deg2rad().
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().
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.
sin() retorna o seno do parâmetro arg. O argumento arg deve estar em radianos.
Retorna o seno hiperbólico de arg, definido como (exp(arg) - exp(-arg))/2.
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().
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() retorna a tangente do parâmetro arg. O argumento arg deve estar em radianos.
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.
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.
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 |
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
|
Exemplo 2. php.ini setting for EUC-JP users
|
Exemplo 3. php.ini setting for SJIS users
|
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.
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.
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.
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.
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.
Tabela 2. Functions to be overloaded
value of mbstring.func_overload | original function | overloaded function |
---|---|---|
1 | mail() | mb_send_mail() |
2 | strlen() | mb_strlen() |
2 | strpos() | mb_strpos() |
2 | strrpos() | mb_strrpos() |
2 | substr() | mb_substr() |
2 | strtolower() | mb_strtolower() |
2 | strtoupper() | mb_strtoupper() |
2 | substr_count() | mb_substr_count() |
4 | ereg() | mb_ereg() |
4 | eregi() | mb_eregi() |
4 | ereg_replace() | mb_ereg_replace() |
4 | eregi_replace() | mb_eregi_replace() |
4 | split() | mb_split() |
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.
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
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
|
See also mb_strtolower(), mb_strtoupper(), strtolower(), strtoupper().
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
|
See also: mb_detect_order().
(PHP 4 >= 4.0.6)
mb_convert_kana -- Convert "kana" one from another ("zen-kaku" ,"han-kaku" and more)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" |
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.
mb_decode_mimeheader() decodes encoded-word string str in MIME header.
It returns decoded string in internal character encoding.
See also mb_encode_mimeheader().
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
|
See also: mb_encode_numericentity().
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
|
See also: mb_detect_order().
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 2. mb_detect_order() examples
|
See also mb_internal_encoding(), mb_http_input(), mb_http_output() mb_send_mail().
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
|
See also mb_decode_mimeheader().
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
|
Exemplo 2. mb_encode_numericentity() example
|
See also: mb_decode_numericentity().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
(4.2.0 - 4.3.0 only)
mb_ereg_search_getregs -- Retrive the result from the last multibyte regular expression matchAtenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
(4.2.0 - 4.3.0 only)
mb_ereg_search_init -- Setup string and regular expression for multibyte regular expression matchAtenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
(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 stringAtenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
(4.2.0 - 4.3.0 only)
mb_ereg_search -- Multibyte regular expression match for predefined multibyte stringAtenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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()
(4.2.0 - 4.3.0 only)
mb_eregi_replace -- Replace regular expression with multibyte support ignoring caseAtenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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() 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().
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() 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.
See also mb_http_input(), mb_http_output(), mb_detect_order().
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() 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
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() 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() returns MIME charset string for character encoding encoding. It returns charset 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_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()
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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() 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().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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() 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() 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.
See also: mb_strwidth(), mb_internal_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() 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() 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() 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 (Ä).
See also strtolower(), mb_strtoupper(), mb_convert_case().
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/.
See also strtoupper(), mb_strtolower(), mb_convert_case().
mb_strwidth() returns width of string str.
Multi-byte character usually twice of width compare to single byte character.
encoding is character encoding. If it is omitted, internal encoding is used.
See also: mb_strimwidth(), mb_internal_encoding().
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".
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.
See also substr_count(), mb_strpos(), mb_substr().
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().
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.
This extension requires the mcal library to be installed. Grab the latest version from http://mcal.chek.com/ and compile and install it.
After you installed the mcal library, to get these functions to work, you have to compile PHP -with-mcal[=DIR].
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_append_event() Stores the global event into an MCAL calendar for the given stream.
Returns the id of the newly inserted event.
Creates a new calendar named calendar.
mcal_date_compare() Compares the two given dates, returns <0, 0, >0 if a<b, a==b, a>b respectively.
(PHP 3>= 3.0.13, PHP 4 )
mcal_date_valid -- Returns TRUE if the given year, month, day is a valid datemcal_date_valid() Returns TRUE if the given year, month and day is a valid date, FALSE if not.
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() returns the day of the year of the given date.
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.
Deletes the calendar named calendar.
mcal_delete_event() deletes the calendar event specified by the event_id.
Returns TRUE.
(PHP 3>= 3.0.15, PHP 4 )
mcal_event_add_attribute -- Adds an attribute and a value to the streams global event structuremcal_event_add_attribute() adds an attribute to the stream's global event structure with the value given by "value".
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.
(PHP 3>= 3.0.13, PHP 4 )
mcal_event_set_alarm -- Sets the alarm of the streams global event structuremcal_event_set_alarm() sets the streams global event structure's alarm to the given minutes before the event.
Returns TRUE.
(PHP 3>= 3.0.13, PHP 4 )
mcal_event_set_category -- Sets the category of the streams global event structuremcal_event_set_category() sets the streams global event structure's category to the given string.
Returns TRUE.
(PHP 3>= 3.0.13, PHP 4 )
mcal_event_set_class -- Sets the class of the streams global event structuremcal_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.
(PHP 3>= 3.0.13, PHP 4 )
mcal_event_set_description -- Sets the description of the streams global event structuremcal_event_set_description() sets the streams global event structure's description to the given string.
Returns TRUE.
(PHP 3>= 3.0.13, PHP 4 )
mcal_event_set_end -- Sets the end date and time of the streams global event structuremcal_event_set_end() sets the streams global event structure's end date and time to the given values.
Returns TRUE.
(PHP 3>= 3.0.13, PHP 4 )
mcal_event_set_recur_daily -- Sets the recurrence of the streams global event structuremcal_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.
(PHP 3>= 3.0.13, PHP 4 )
mcal_event_set_recur_monthly_mday -- Sets the recurrence of the streams global event structuremcal_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.
(PHP 3>= 3.0.13, PHP 4 )
mcal_event_set_recur_monthly_wday -- Sets the recurrence of the streams global event structuremcal_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.
(PHP 3>= 3.0.15, PHP 4 )
mcal_event_set_recur_none -- Sets the recurrence of the streams global event structuremcal_event_set_recur_none() sets the streams global event structure to not recur (event->recur_type is set to MCAL_RECUR_NONE).
(PHP 3>= 3.0.13, PHP 4 )
mcal_event_set_recur_weekly -- Sets the recurrence of the streams global event structuremcal_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.
(PHP 3>= 3.0.13, PHP 4 )
mcal_event_set_recur_yearly -- Sets the recurrence of the streams global event structuremcal_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.
(PHP 3>= 3.0.13, PHP 4 )
mcal_event_set_start -- Sets the start date and time of the streams global event structuremcal_event_set_start() sets the streams global event structure's start date and time to the given values.
Returns TRUE.
(PHP 3>= 3.0.13, PHP 4 )
mcal_event_set_title -- Sets the title of the streams global event structuremcal_event_set_title() sets the streams global event structure's title to the given string.
Returns TRUE.
(no version information, might be only in CVS)
mcal_expunge -- Deletes all events marked for being expunged.mcal_expunge() Deletes all events which have been previously marked for deletion.
(PHP 3>= 3.0.13, PHP 4 )
mcal_fetch_current_stream_event -- Returns an object containing the current streams event structuremcal_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
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() 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
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
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() returns 1 if the given year is a leap year, 0 if not.
(PHP 3>= 3.0.13, PHP 4 )
mcal_list_alarms -- Return a list of events that has an alarm triggered at the given datetimeReturns 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.
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() 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.
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.
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.
Renames the calendar old_name to new_name.
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() turns off an alarm for a calendar event specified by the id.
Returns TRUE.
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.
(PHP 3>= 3.0.13, PHP 4 )
mcal_time_valid -- Returns TRUE if the given year, month, day is a valid timemcal_time_valid() Returns TRUE if the given hour, minutes and seconds is a valid time, FALSE if not.
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".
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.
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.
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 |
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:
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).
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.
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
|
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.
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.
(PHP 3>= 3.0.8, PHP 4 )
mcrypt_create_iv -- Create an initialization vector (IV) from a random sourcemcrypt_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.
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() 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'.
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.
This function returns the name of the algorithm.
Exemplo 1. mcrypt_enc_get_algorithms_name() example
|
This function returns the block size of the algorithm specified by the encryption descriptor td in bytes.
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.
This function returns the maximum supported key size of the algorithm specified by the encryption descriptor td in bytes.
This function returns the name of the mode.
(PHP 4 >= 4.0.2)
mcrypt_enc_get_supported_key_sizes -- Returns an array with the supported keysizes of the opened algorithmReturns 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.
(PHP 4 >= 4.0.2)
mcrypt_enc_is_block_algorithm_mode -- Checks whether the encryption of the opened mode works on blocksThis 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).
(PHP 4 >= 4.0.2)
mcrypt_enc_is_block_algorithm -- Checks whether the algorithm of the opened mode is a block algorithmThis function returns TRUE if the algorithm is a block algorithm, or FALSE if it is a stream algorithm.
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).
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() 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
The above example will print out:
|
See also mcrypt_module_open() for a more advanced API and an example.
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().
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.
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().
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().
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.
See also: mcrypt_get_key_size() and mcrypt_encrypt().
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.
(PHP 4 >= 4.0.2)
mcrypt_get_iv_size -- Returns the size of the IV belonging to a specific cipher/mode combinationThe 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
|
See also: mcrypt_create_iv()
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
|
See also: mcrypt_get_block_size() and mcrypt_encrypt().
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.
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
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). |
This function closes the specified encryption handle.
See mcrypt_module_open() for an example.
(PHP 4 >= 4.0.2)
mcrypt_module_get_algo_block_size -- Returns the blocksize of the specified algorithmThis 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.
(PHP 4 >= 4.0.2)
mcrypt_module_get_algo_key_size -- Returns the maximum supported keysize of the opened modeThis 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.
(PHP 4 >= 4.0.2)
mcrypt_module_get_supported_key_sizes -- Returns an array with the supported keysizes of the opened algorithmReturns 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.
(PHP 4 >= 4.0.2)
mcrypt_module_is_block_algorithm_mode -- This function returns if the the specified module is a block algorithm or notThis 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.
(PHP 4 >= 4.0.2)
mcrypt_module_is_block_algorithm -- This function checks whether the specified algorithm is a block algorithmThis 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.
(PHP 4 >= 4.0.2)
mcrypt_module_is_block_mode -- This function returns if the the specified mode outputs blocks or notThis 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.
(PHP 4 >= 4.0.2)
mcrypt_module_open -- This function opens the module of the algorithm and the mode to be usedThis 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).
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
|
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().
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.
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.
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
|
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().
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.
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/.
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.
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
(PHP 4 >= 4.2.0)
mcve_completeauthorizations -- Number of complete authorizations in queue, returning an array of their identifiers
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
(PHP 4 >= 4.2.0)
mcve_getcellbynum -- Get a specific cell from a comma delimited response by column number
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
(PHP 4 >= 4.3.0)
mcve_maxconntimeout -- The maximum amount of time the API will attempt a connection to MCVE
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
(PHP 4 >= 4.2.0)
mcve_parsecommadelimited -- Parse the comma delimited response so mcve_getcell, etc will work
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
(PHP 4 >= 4.2.0)
mcve_transactionauth -- Get the authorization number returned for the transaction (alpha-numeric)
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
(PHP 4 >= 4.2.0)
mcve_transactionitem -- Get the ITEM number in the associated batch for this transaction
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
(PHP 4 >= 4.2.0)
mcve_transactiontext -- Get verbiage (text) return from MCVE or processing institution
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
(PHP 4 >= 4.3.0)
mcve_verifyconnection -- Set whether or not to PING upon connect to verify connection
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
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.
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.
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.
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
Exemplo 1. Calcular o MD5 digest e hmac e imprimir como hex
Este código irá produzir:
|
mhash_count() retorna a mais alta hash id disponível. As hashes são numeradas de 0 até esta hash id.
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() é 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.
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() 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.
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.
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.
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 |
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.
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.
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 |
(PHP 4 >= 4.1.0)
mssql_bind -- Adiciona um parâmetro a um stored procedure ou a um remote stored procedure
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
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().
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().
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().
(PHP 4 >= 4.1.0)
mssql_execute -- Executa uma stored procedure num banco de dados de um servidor MS SQL
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
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().
(PHP 4 >= 4.2.0)
mssql_fetch_assoc -- Retorna uma matriz associativa da linha atual do conjunto de resultados especificado por result_id
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
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().
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().
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().
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
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_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() 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()
(PHP 3, PHP 4 )
mssql_get_last_message -- Retorna a ultima mensagem do servidor (sobre min_message_severity?)
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
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()
|
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() retorna o número de linhas em um conjunto de resultados.
Veja também: mssql_db_query(), mssql_query(), e mssql_fetch_row().
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'.
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() 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().
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
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()
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. |
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.
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.
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.
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.
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.
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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:
Returns the number of milliseconds (?) elapsed since the movie started.
Returns a pseudo-random number in the range 0-seed.
Returns the length of the given expression.
Returns the given number rounded down to the nearest integer.
Returns the concatenation of the given expressions.
Returns the ASCII code for the given character
Returns the character for the given ASCII code
Returns the substring of length length at location location of the given string string.
Additionally, the following commands may be used:
Duplicate the named movie clip (aka sprite). The new movie clip has name name and is at depth depth.
Removes the named movie clip.
Write the given expression to the trace log. Doubtful that the browser plugin does anything with this.
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.
Stop dragging my heart around. And this movie clip, too.
Call the named frame as a function.
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.
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).
Go to the next frame.
Go to the last (or, rather, previous) frame.
Start playing the movie.
Stop playing the movie.
Toggle between high and low quality.
Stop playing all sounds.
Go to frame number num. Frame numbers start at 0.
Go to the frame named name. Which does a lot of good, since I haven't added frame labels yet.
Sets the context for action. Or so they say- I really have no idea what this does.
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 - (???)
This simple example will move the red square across the window.
Exemplo 1. swfaction() example
|
This simple example tracks down your mouse on the screen.
Exemplo 2. swfaction() example
|
Same as above, but with nice colored balls...
Exemplo 3. swfaction() example
|
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
|
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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
|
And you can put an alpha mask on a jpeg fill.
Exemplo 2. swfbitmap() example
|
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
(no version information, might be only in CVS)
SWFbutton->setdown -- Alias for addShape(shape, SWFBUTTON_DOWN))Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
(no version information, might be only in CVS)
SWFbutton->setHit -- Alias for addShape(shape, SWFBUTTON_HIT)Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
(no version information, might be only in CVS)
SWFbutton->setOver -- Alias for addShape(shape, SWFBUTTON_OVER)Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
(no version information, might be only in CVS)
SWFbutton->setUp -- Alias for addShape(shape, SWFBUTTON_UP)Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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
|
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
|
(no version information, might be only in CVS)
SWFDisplayItem->addColor -- Adds the given color to this item's color transform.Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
(no version information, might be only in CVS)
SWFDisplayItem->move -- Moves object in relative coordinates.Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
(no version information, might be only in CVS)
SWFDisplayItem->moveTo -- Moves object in global coordinates.Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
(no version information, might be only in CVS)
SWFDisplayItem->multColor -- Multiplies the item's color transform.Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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
|
(no version information, might be only in CVS)
SWFDisplayItem->remove -- Removes the object from the movieAtenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
(no version information, might be only in CVS)
SWFDisplayItem->Rotate -- Rotates in relative coordinates.Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
(no version information, might be only in CVS)
SWFDisplayItem->rotateTo -- Rotates the object in global coordinates.Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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
|
See also swfdisplayitem->rotate().
(no version information, might be only in CVS)
SWFDisplayItem->scale -- Scales the object in relative coordinates.Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
(no version information, might be only in CVS)
SWFDisplayItem->scaleTo -- Scales the object in global coordinates.Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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
|
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
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().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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"); ?> |
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().
(no version information, might be only in CVS)
SWFGradient->addEntry -- Adds an entry to the gradient list.Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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
|
(no version information, might be only in CVS)
SWFMorph->getshape1 -- Gets a handle to the starting shapeAtenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
(no version information, might be only in CVS)
SWFMorph->getshape2 -- Gets a handle to the ending shapeAtenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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
|
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
(no version information, might be only in CVS)
SWFMovie->nextframe -- Moves to the next frame of the animation.Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
(no version information, might be only in CVS)
SWFMovie->output -- Dumps your lovingly prepared movie out.Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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'); ?> |
See also swfmovie->save().
See examples in : swfmovie->streammp3(), swfdisplayitem->rotateto(), swfaction()... Any example will use this method.
(no version information, might be only in CVS)
SWFMovie->remove -- Removes the object instance from the display list.Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.)
(no version information, might be only in CVS)
SWFMovie->setdimension -- Sets the movie's width and 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.
(no version information, might be only in CVS)
SWFMovie->setframes -- Sets the total number of frames in the animation.Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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 é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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 é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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
|
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
(no version information, might be only in CVS)
SWFShape->movePen -- Moves the shape's pen (relative).Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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 é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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
|
(no version information, might be only in CVS)
SWFShape->setRightFill -- Sets right rasterizing color.Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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 é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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]));.
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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
|
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
(no version information, might be only in CVS)
SWFSprite->nextframe -- Moves to the next frame of the animation.Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
(no version information, might be only in CVS)
SWFSprite->setframes -- Sets the total number of frames in the animation.Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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
|
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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
|
(no version information, might be only in CVS)
SWFTextField->addstring -- Concatenates the given string to the text fieldAtenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
(no version information, might be only in CVS)
SWFTextField->setbounds -- Sets the text field width and heightAtenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
(no version information, might be only in CVS)
SWFTextField->setcolor -- Sets the color of the text field.Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
(no version information, might be only in CVS)
SWFTextField->setHeight -- Sets the font height of this text field 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->setheight() sets the font height of this text field font to the given height height. Default is 240.
(no version information, might be only in CVS)
SWFTextField->setindentation -- Sets the indentation of the first line.Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
(no version information, might be only in CVS)
SWFTextField->setLeftMargin -- Sets the left margin width of the text field.Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
(no version information, might be only in CVS)
SWFTextField->setLineSpacing -- Sets the line spacing of the text field.Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
(no version information, might be only in CVS)
SWFTextField->setMargins -- Sets the margins width of the text field.Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
(no version information, might be only in CVS)
SWFTextField->setrightMargin -- Sets the right margin width of the text field.Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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
<?php $t = newSWFTextField(SWFTEXTFIELD_PASSWORD | SWFTEXTFIELD_NOEDIT); ?> |
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().
Não há nenhuma instalação nescessária para utilizar estas funções, elas fazem parte do núcleo do PHP.
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 |
Aqui esta uma pequena explicação das diretivas de configuração.
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().
Cores para o modo de destaque da sintaxe. Qualquer coisa aceitável em <font color="??????"> deve funcionar.
Nome (ex: browscap.ini)e localização do arquivo com as capacidades do browser. Veja também get_browser().
Retorna TRUE se o cliente desconectou. Veja a descrição de Connection Handling no capitulo Features para uma explicação completa.
Retorna o estado da conexão. Veja a descrição de Connection Handling no capitulo Features para uma explicação completa.
(PHP 3>= 3.0.7, PHP 4 <= 4.0.4)
connection_timeout -- Retorna TRUE se o script ultrapassou o limite de tempoRetorna 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.
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.
Veja também define(), defined() e a seção sobre Constantes.
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.
Retorna TRUE em caso de sucesso ou FALSE em falhas.
Vejá também defined(), constant()e a seção sobre Constantes.
Retorna TRUE se a constante dada pelo parâmetro name já foi definida, em outro caso FALSE.
Veja também define(), constant(), get_defined_constants()e a seção sobre Constants.
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.
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).
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().
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.
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.
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:
E então faça um arquivo chamado "source" e coloque-o no seu diretório raiz do servidor web.
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.
|
Veja também highlight_string(), show_source().
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().
(PHP 3>= 3.0.7, PHP 4 )
ignore_user_abort -- Estabelece se acontecerá o enceramento do script quando o usuário abortar a conexãoEsta 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 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
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.
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().
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() 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() 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 /.
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.
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.
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.
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.
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.
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_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() 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() 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:
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
...
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'
|
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
udm_clear_search_limits() resets defined search limitations and returns TRUE.
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
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() 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() 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() 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() 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() 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() 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() 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() 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() 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:
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:
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
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.
These functions allow you to access mSQL database servers. More information about mSQL can be found at http://www.hughes.com.au/.
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)
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 |
Here is a short explanation of the configuration directives.
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().
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().
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() attempts to create a new database on the server associated with the specified link identifier.
See also: msql_drop_db().
Identical to msql_create_db().
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() 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.
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().
Errors coming back from the mSQL database backend no longer issue warnings. Instead, use these functions to retrieve the error string.
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().
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().
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().
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().
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() 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() returns the length of the specified 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.
Returns the name of the table field was fetched from.
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() 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_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() 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() 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_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() returns the number of rows in a result set.
See also: msql(), msql_query(), and msql_fetch_row().
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() 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()
|
See also: msql(), msql_select_db(), and msql_connect().
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().
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_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.
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()).
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/.
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. |
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 |
Aqui esta uma pequena explicação das diretivas de configuração.
Quando permitir conexões persistentes para o MySQL.
O número máximo de conexões persistentes com o MySQL por processo.
O número maximo de conexões com o MYSQL por processo, incluindo conexões persistentes.
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.
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.
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.
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.
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.
Limite de tempo da conexão em segundos. No Linux este limite é também usado para a espera da primeira resposta do servidor.
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.
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. |
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 3, PHP 4 )
mysql_affected_rows -- Devolve o número de linhas afetadas na operação anterior com o MySQLmysql_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
O exemplo acima deve produzir a seguinte saída:
|
Exemplo 2. Update-Query
O exemplo acima deve produzir a seguinte saída:
|
Veja também: mysql_num_rows(), mysql_info().
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.
A função mysql_client_encoding() retorna o conjunto de caracteres padrão para a conexão atual.
Exemplo 1. Exemplo mysql_client_encoding()
O exemplo acima deve produzir a seguinte saida:
|
Veja também: mysql_real_escape_string()
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().
Veja também: mysql_connect(), e mysql_pconnect().
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().
Veja também mysql_pconnect() e mysql_close().
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
|
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().
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
|
Veja também: mysql_query() e mysql_num_rows().
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.
Para compatibilidade com versões anteriores, mysql_dbname() também é aceito. Seu uso está obsoleto.
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().
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().
(PHP 3, PHP 4 )
mysql_errno -- Retorna o valor numérico da mensagem de erro da operação anterior do MySQLRetorna 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
O exemplo acima deve produzir a seguinte saida:
|
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()
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
O exemplo acima deve produzir a seguinte saida:
|
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()
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.
Veja também: mysql_real_escape_string(), addslashes(), e a diretiva magic_quotes_gpc.
(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.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).
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
|
Exemplo 3. mysql_fetch_array com MYSQL_ASSOC
|
Exemplo 4. mysql_fetch_array com MYSQL_BOTH
|
Para maiores detalhes, veja também mysql_fetch_row() e mysql_fetch_assoc().
(PHP 4 >= 4.0.3)
mysql_fetch_assoc -- Busca o resultado de uma linha e o coloca numa matriz associativaRetorna 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()
|
Para maiores detalhes, veja também mysql_fetch_row(), mysql_fetch_array() e mysql_query().
(PHP 3, PHP 4 )
mysql_fetch_field -- Retorna informação sobre uma coluna de um resultado como um objetoRetorna 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()
|
Veja também mysql_field_seek().
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().
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).
Veja também: mysql_fetch_array() e mysql_fetch_row().
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() 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() 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() 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()
O exemplo acima deve produzir a seguinte saída:
|
Para compatibilidade com versões anteriores mysql_fieldname() também pode ser usada. Esta função está depreciada.
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().
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() é 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
A tabela acima irá produzir a seguinte saída:
|
Para compatibilidade com versões anteriores mysql_fieldtype() também pode ser usada. Esta função está depreciada.
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() retorna uma string que representa a versão da biblioteca do cliente.
Veja também: mysql_get_host_info(), mysql_get_proto_info() e mysql_get_server_info().
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
O exemplo acima deve produzir a seguinte saída:
|
Veja também: mysql_get_client_info(), mysql_get_proto_info() e mysql_get_server_info().
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.
Veja também: mysql_get_client_info(), mysql_get_host_info() and mysql_get_server_info().
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
O exemplo acima deve produzir a seguinte saída:
|
Veja também: mysql_get_client_info(), mysql_get_host_info() e mysql_get_proto_info().
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
|
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() 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
|
Veja também: mysql_query().
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()
O exemplo acima deve produzir a seguinte saída:
|
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() 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()
O exemplo acima deve produzir a seguinte saída:
|
Para compatibilidade com versões anteriores mysql_listfields() também pode ser usada. Esta função esta depreciada.
mysql_list_processes() retorna um ponteiro de resultado descrevendo as threads atuais do servidor.
Exemplo 1. Exemplo mysql_list_processes()
O exemplo acima deve produzir a seguinte saída:
|
Veja também: mysql_thread_id()
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
|
Veja também: mysql_list_dbs(), e mysql_tablename().
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() 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().
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.
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() 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() 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:
A seguinte query é semanticamente invalida se my_col não é uma coluna da tabela my_tbl, assim mysql_query() falha e retorna FALSE:
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().
(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.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()
O exemplo acima deve produzir a seguinte saída:
|
Veja também: mysql_escape_string(), mysql_character_set_name().
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().
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() 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()
O exemplo acima deve produzir a seguinte saída:
|
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.
Veja também: mysql_list_tables().
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.
Veja também: mysql_ping(), mysql_list_processes().
(PHP 4 >= 4.0.6)
mysql_unbuffered_query -- Envia uma query para o MySQL, sem retornar e colocar em buffer as linhas do resultadomysql_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().
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.
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Returns an associative array of value, session for all sessions with a variable named name.
Used for searching sessions with common attributes.
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
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. |
(4.0.5 - 4.2.3 only)
muscat_close -- Shuts down the muscat session and releases any memory back to PHP.Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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!]
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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
Não há nenhuma instalação nescessária para utilizar estas funções, elas fazem parte do núcleo do PHP.
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 |
Here is a short explanation of the configuration directives.
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().
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. |
(PHP 3, PHP 4 )
checkdnsrr -- Check DNS records corresponding to a given Internet host name or IP addressSearches 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
See also getmxrr(), gethostbyaddr(), gethostbyname(), gethostbynamel(), and the named(8) manual page.
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().
Disables the internal PHP debugger. This function is only available in PHP 3.
For more information see the appendix on Debugging PHP.
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.
Initializes all constants used in the syslog functions.
See also openlog(), syslog() and closelog().
Check DNS records corresponding to a given Internet host name or IP address
Get MX records corresponding to a given Internet host name.
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()
|
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
|
See also dns_get_mx(), and dns_check_record()
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().
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.
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().
Returns the IP address of the Internet host specified by hostname or a string containing the unmodified hostname on failure.
See also gethostbyaddr().
(PHP 3, PHP 4 )
gethostbynamel -- Get a list of IP addresses corresponding to a given Internet host nameReturns 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.
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.
See also checkdnsrr(), gethostbyname(), gethostbynamel(), gethostbyaddr(), and the named(8) manual page.
getprotobyname() returns the protocol number associated with the protocol name as per /etc/protocols.
See also: getprotobynumber().
getprotobynumber() returns the protocol name associated with protocol number as per /etc/protocols.
See also: getprotobyname().
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() 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().
(PHP 4 )
ip2long -- Converts a string containing an (IPv4) Internet Protocol dotted address into a proper address.The function ip2long() generates an IPv4 Internet network address from its Internet standard format (dotted string) representation.
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.
See also: long2ip()
(PHP 4 )
long2ip -- Converts an (IPv4) Internet network address into a string in Internet standard dotted formatThe function long2ip() generates an Internet address in dotted format (i.e.: aaa.bbb.ccc.ddd) from the proper address representation.
See also: ip2long()
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 |
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().
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().
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()
|
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().
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
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.
To get these functions to work, you have to compile the CGI or CLI version of PHP with --with-ncurses[=DIR].
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 |
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. 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 |
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 | |
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 |
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 |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
(PHP 4 >= 4.2.0)
ncurses_addchnstr -- Add attributed string with specified length at current positionAtenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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()
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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()
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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()
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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()
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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()
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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()
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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()
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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()
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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()
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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()
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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()
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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()
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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
See also: ncurses_ungetmouse()
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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()
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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()
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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()
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
(PHP 4 >= 4.2.0)
ncurses_hline -- Draw a horizontal line at current position using an attributed character and max. n characters longAtenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
(PHP 4 >= 4.1.0)
ncurses_insch -- Insert character moving rest of line including character at current positionAtenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
(PHP 4 >= 4.1.0)
ncurses_insdelln -- Insert lines before current line scrolling down (negative numbers delete and scroll up)Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
(PHP 4 >= 4.1.0)
ncurses_isendwin -- Ncurses is in endwin mode, normal screen output may be performedAtenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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()()
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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()
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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()
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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()
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
(PHP 4 >= 4.2.0)
ncurses_mvaddchnstr -- Move position and add attrributed string with specified lengthAtenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
(PHP 4 >= 4.2.0)
ncurses_mvhline -- Set new position and draw a horizontal line using an attributed character and max. n characters longAtenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
(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 longAtenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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()
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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()
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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()
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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()
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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()
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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()
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
(PHP 4 >= 4.1.0)
ncurses_termattrs -- Returns a logical OR of all attribute flags supported by terminalAtenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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()
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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()
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
(PHP 4 >= 4.1.0)
ncurses_use_extended_names -- Control use of extended names in terminfo descriptionsAtenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
(PHP 4 >= 4.2.0)
ncurses_vline -- Draw a vertical line at current position using an attributed character and max. n characters longAtenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
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. |
(PHP 4 >= 4.0.5)
notes_body -- Open the message msg_number in the specified mailbox on the specified server (leave servAtenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
(PHP 4 >= 4.0.5)
notes_find_note -- Returns a note id found in database_name. Specify the name of the note. Leaving type blaAtenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
(PHP 4 >= 4.0.5)
notes_header_info -- Open the message msg_number in the specified mailbox on the specified server (leave servAtenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
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/.
To access any of the supported databases you need to have the required libraries installed.
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.
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.
Here is a short explanation of the configuration directives.
ODBC data source to use if none is specified in odbc_connect() or odbc_pconnect().
User name to use if none is specified in odbc_connect() or odbc_pconnect().
Password to use if none is specified in odbc_connect() or odbc_pconnect().
Whether to allow persistent ODBC connections.
Check that a connection is still valid before reuse.
The maximum number of persistent ODBC connections per process.
The maximum number of ODBC connections per process, including persistent connections.
Handling of LONG fields. Specifies the number of bytes returned to variables.
Handling of binary data.
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.
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 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() 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() 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.
(PHP 4 )
odbc_columnprivileges -- Returns a result identifier that can be used to fetch a list of columns and associated privilegesLists 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).
(PHP 4 )
odbc_columns -- Lists the column names in specified tables. Returns a result identifier containing the information.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() commits all pending transactions on the connection_id connexion. Retorna TRUE em caso de sucesso ou FALSE em falhas.
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 will return a cursorname for the given result_id.
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() will execute a query on the given connection.
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().
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().
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.
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()).
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
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.
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
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() 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() 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() 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() 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_precision() will return the scale of the field referecend by number in the given ODBC result identifier.
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.
(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 tableodbc_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.
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.
(PHP 4 )
odbc_gettypeinfo -- Returns a result identifier containing information about data types supported by the data source.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 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().
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
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() 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.
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.
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().
(PHP 4 )
odbc_primarykeys -- Returns a result identifier that can be used to fetch the column names that comprise the primary key for a tableReturns 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
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).
(PHP 4 )
odbc_procedures -- Get the list of procedures stored in a specific data source. Returns a result identifier containing the information.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).
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.
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:
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().
Rolls back all pending statements on connection_id. Returns TRUE on success, FALSE on failure.
(PHP 3>= 3.0.6, PHP 4 )
odbc_setoption -- Adjust ODBC settings. Returns FALSE if an error occurs, otherwise TRUE.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
|
(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 transactionWhen 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.
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.
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).
(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.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.
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. |
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
|
Exemplo 2. Object association
|
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.
We define 3 classes, each implementing a different storage method:
Exemplo 3. storage_classes.inc
|
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
|
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.
(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.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()
|
Will produce the output
Array ( [dicer] => Array ( [methods] => Array ( [0] => dice_it [1] => rotate ) [properties] => Array ( [0] => rotation_angle ) ) ) |
See also aggregate(), aggregate_methods(), aggregate_methods_by_list(), aggregate_methods_by_regexp(), aggregate_properties(), aggregate_properties_by_list(), aggregate_properties_by_regexp(), deaggregate()
(PHP 4 >= 4.2.0)
aggregate_methods_by_list -- selective dynamic class methods aggregation to an objectAggregates 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()
(PHP 4 >= 4.2.0)
aggregate_methods_by_regexp -- selective class methods aggregation to an object using a regular expressionAggregates 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()
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()
(PHP 4 >= 4.2.0)
aggregate_properties_by_list -- selective dynamic class properties aggregation to an objectAggregates 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()
(PHP 4 >= 4.2.0)
aggregate_properties_by_regexp -- selective class properties aggregation to an object using a regular expressionAggregates 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()
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()
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()
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.
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()
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.
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:
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.
You have to compile PHP with the option --with-oci8[=DIR], where DIR defaults to your environmment variable ORACLE_HOME.
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.
Exemplo 1. OCI Hints
|
You can easily access stored procedures in the same way as you would from the commands line.
Exemplo 2. Using Stored Procedures
|
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
|
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. |
If you do not want read more data from a cursor, then call OCICancel().
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
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() returns the name of the column corresponding to the column number (1-based) that is passed in.
Exemplo 1. OCIColumnName
|
See also OCINumCols(), OCIColumnType(), and OCIColumnSize().
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
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
|
See also OCINumCols(), OCIColumnName(), and OCIColumnSize().
OCIColumnType() returns the data type of the column corresponding to the column number (1-based) that is passed in.
Exemplo 1. OCIColumnType
|
See also OCINumCols(), OCIColumnName(), and OCIColumnSize().
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
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
|
See also OCIRollback().
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
|
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() 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() fetches the next row (for SELECT statements) into the internal result-buffer.
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. |
See also OCIFetch() and OCIExecute().
OCIFetchStatement() fetches all the rows from a result into a user-defined array. OCIFetchStatement() returns the number of rows fetched.
Exemplo 1. OCIFetchStatement
|
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
OCIFreeCursor() returns TRUE if successful, or FALSE if unsuccessful.
OCIFreeDesc() returns TRUE if successful, or FALSE if unsuccessful.
OCIFreeStatement() returns TRUE if successful, or FALSE if unsuccessful.
OCIInternalDebug() enables internal debug output. Set onoff to 0 to turn debug output off, 1 to turn it on.
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
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() 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
|
See also OCIPLogon() and OCINLogon().
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
OCINewCursor() allocates a new statement handle on the specified connection.
Exemplo 1. Using a REF CURSOR from a stored procedure
|
Exemplo 2. Using a REF CURSOR in a select statement
|
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
|
Exemplo 2. OCINewDescriptor
|
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
|
See also OCILogon() and OCIPLogon().
OCINumCols() returns the number of columns in a statement.
Exemplo 1. OCINumCols
|
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() 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() 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() rolls back all outstanding statements for Oracle connection connection. OCIRollback() returns TRUE on success and FALSE otherwise.
See also OCICommit().
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
|
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Sets the number of top level rows to be prefetched. The default value is 1 row.
OCIStatementType() returns one of the following values:
"SELECT"
"UPDATE"
"DELETE"
"INSERT"
"CREATE"
"DROP"
"ALTER"
"BEGIN"
"DECLARE"
"UNKNOWN"
Exemplo 1. OCIStatementType() examples
|
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.
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.
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.
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
An X.509 resource returned from openssl_x509_read()
A string having the format file://path/to/cert.pem; the named file must contain a PEM encoded certificate
A string containing the content of a certificate, PEM encoded
Public/Private Keys
A key resource returned from openssl_get_publickey() or openssl_get_privatekey()
For public keys only: an X.509 resource
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)
A string containing the content of a certificate/key, PEM encoded
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
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.
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.
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.
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() 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() 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
|
(PHP 4 >= 4.2.0)
openssl_csr_sign -- Sign a CSR with another certificate (or itself) and generate a certificateopenssl_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)
|
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.
Nota: This function was added in 4.0.6.
openssl_free_key() frees the key associated with the specified key_identifier from memory.
This is an alias for openssl_pkey_get_private().
This is an alias for openssl_pkey_get_public().
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
|
See also openssl_seal().
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
|
Nota: This function was added in 4.0.6.
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
|
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
|
Nota: This function was added in 4.0.6.
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.
(PHP 4 >= 4.2.0)
openssl_pkey_export_to_file -- Gets an exportable representation of a key into a fileopenssl_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() 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.
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:
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).
A PEM formatted private key.
The optional parameter passphrase must be used if the specified key is encrypted (protected by a passphrase).
(PHP 4 >= 4.2.0)
openssl_pkey_get_public -- Extract public key from certificate and prepare it for useReturns 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:
an X.509 certificate resource
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).
A PEM formatted private key.
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() 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.
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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 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
|
See also openssl_open().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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
|
See also openssl_verify().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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
|
See also openssl_sign().
(PHP 4 >= 4.2.0)
openssl_x509_check_private_key -- Checks if a private key corresponds to a certificateopenssl_x509_check_private_key() returns TRUE if key is the private key that corresponds to cert, or FALSE otherwise.
(PHP 4 >= 4.0.6)
openssl_x509_checkpurpose -- Verifies if a certificate can be used for a particular purposeReturns 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? |
Nota: This function was added in 4.0.6.
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() 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() frees the certificate associated with the specified x509cert resource from memory.
Nota: This function was added in 4.0.6.
(PHP 4 >= 4.0.6)
openssl_x509_parse -- Parse an X509 certificate and return the information as an arrayAtenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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.
This extension adds support for Oracle database server access. See also the OCI8 extension.
You have to compile PHP with the option --with-oracle[=DIR], where DIR defaults to your environmment variable ORACLE_HOME.
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"; ?> |
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().
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.
Returns the size of the Oracle column column on the cursor cursor. Column 0 is the first 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" |
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.
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().
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.
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().
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
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.
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().
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.
See also ora_parse(),ora_exec(), ora_fetch(), and ora_do().
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().
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.
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().
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:
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() 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().
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.
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().
Establishes a persistent connection between PHP and an Oracle database with the given username and password.
See also ora_logon().
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.
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.
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.
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.
Exemplo 1. Connect to Ovrimos SQL Server and select from a system table
|
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() is used to commit the transaction.
ovrimos_commit() commits the transaction.
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
|
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() 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() 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() 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
|
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
|
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() 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() 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() 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() is used to free the result_id.
ovrimos_free_result() frees the specified result_id result_id. Returns TRUE.
(PHP 4 >= 4.0.3)
ovrimos_longreadlen -- Specifies how many bytes are to be retrieved from long datatypesovrimos_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() 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() 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() 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
|
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
|
Exemplo 2. Ovrimos_result_all with meta-information
|
Exemplo 3. ovrimos_result_all example
|
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.
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.
Não há nenhuma instalação nescessária para utilizar estas funções, elas fazem parte do núcleo do PHP.
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 |
Here is a short explanation of the configuration directives.
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).
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.
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().
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.
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.
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().
This function discards the contents of the output buffer and turns off output buffering.
See also ob_start(), ob_clean() and ob_end_flush().
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().
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().
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().
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().
This will return the level of nested output buffering handlers.
See also ob_start() and ob_get_contents().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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().
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().
See also ob_start() and ob_end_flush().
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().
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
|
Would produce:
See also ob_get_contents(), ob_end_flush(), ob_end_clean(), ob_implicit_flush() and ob_gzhandler().
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. |
Para poder utilizar essas funções, você precisa compilar o PHP com a opção --enable-overload.
Alguns exemplos simples da utilização da função overload():
Exemplo 1. Sobrecarga de uma classe no PHP
|
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. |
(4.2.0 - 4.3.0 only)
overload -- Ativa a chamada sobrecarregada de propriedades e métodos para uma classeA 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.
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.
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.
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.
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. |
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
The script getpdf.php just returns the pdf document. |
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
|
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.
Add a launch annotation (to a target of arbitrary file type).
Add a link annotation to a target within the current PDF file.
Add a note annotation. icon is one of of "comment, "insert", "note", "paragraph", "newparagraph", "key", or "help".
Add a file link annotation (to a PDF target).
Add an existing image as thumbnail for the current page.
Add a weblink annotation to a target URL on the Web.
Draw a counterclockwise circular arc from alpha to beta degrees
See also: pdf_arcn()
Draw a clockwise circular arc from alpha to beta degrees
See also: pdf_arc()
Add a file attachment annotation. icon is one of "graph, "paperclip", "pushpin", or "tag".
Add a new page to the document. The width and height are specified in points, which are 1/72 of an inch.
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.
Start a new template definition.
Draw a circle with center (x, y) and radius r.
Close an image retrieved with one of the pdf_open_image*() functions.
Close the page handle, and free all page-related resources.
Close all open page handles, and close the input PDF document.
Close the generated PDF file, and free all document-related resources.
Concatenate a matrix to the CTM.
Print text at the next line. The spacing between lines is determined by the leading parameter.
Draw a Bezier curve from the current point, using 3 more control points.
Delete the PDF object, and free all internal resources.
Fill and stroke the path with the current fill and stroke color.
Fill the interior of the path with the current fill color.
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.
Get the contents of the PDF output buffer. The result must be used by the client before calling any other PDFlib function.
pdf_get_image_height() is deprecated, use pdf_get_value() instead.
The pdf_get_image_width() is deprecated, use pdf_get_value() instead.
Get the contents of some PDFlib parameter with string type.
Get the contents of some PDI document parameter with string type.
Get the contents of some PDI document parameter with numerical type.
Get the contents of some PDFlib parameter with float type.
Reset all implicit color and graphics state parameters to their defaults.
Draw a line from the current point to (x, y).
Make a named spot color from the current color.
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.
Create a new PDF object, using default error handling and memory management.
Open a raw CCITT image.
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
|
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.
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".
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.
See also pdf_close_image(), pdf_place_image().
Prepare a page for later use with pdf_place_image()
Open an existing PDF document for later use.
Deprecated.
See also pdf_open_image(),
pdf_open() is deprecated, use pdf_new() plus pdf_open_file() instead.
See also pdf_new(), pdf_open_file().
Place an image with the lower left corner at (x, y), and scale it.
Place a PDF page with the lower left corner at (x, y), and scale it.
Draw a rectangle at lower left (x, y) with width and height.
Rotate the coordinate system by phi degrees.
Scale the coordinate system.
Set the border color for all kinds of annotations.
Set the border dash style for all kinds of annotations. See pdf_setdash().
Set the border style for all kinds of annotations. style is "solid" or "dashed".
Deprecated. You should use pdf_findfont() plus pdf_setfont() instead.
See pdf_findfont(), pdf_setfont().
Deprecated.
See also pdf_set_value(),
This function is deprecate, use pdf_set_info() instead.
This function is deprecate, use pdf_set_info() instead.
This function is deprecate, use pdf_set_info() instead.
This function is deprecate, use pdf_set_info() instead.
This function is deprecate, use pdf_set_info() instead.
Fill document information field key with value. key is one of "Subject", "Title", "Creator", "Author", "Keywords", or a user-defined key.
Set some PDFlib parameter with string type.
Set the value of some PDFlib parameter with float type.
Set the current color space and color. The parameter type can be "fill", "stroke", or "both" to specify that the color is set for filling, stroking or both filling and stroking. The parameter colorspace can be gray, rgb, cmyk, spot or pattern. The parameters c1, c2, c3 and c4 represent the color components for the color space specified by colorspace. Except as otherwise noted, the color components are floating-point values that range from 0 to 1.
For gray only c1 is used.
For rgb parameters c1, c2, and c3 specify the red, green and blue values respectively.
For cmyk, parameters c1, c2, c3, and c4 are the cyan, magenta, yellow and black values, respectively.
For spot, c1 should be a spot color handles returned by pdf_makespotcolor() and c2 is a tint value between 0 and 1.
For pattern, c1 should be a pattern handle returned by pdf_begin_pattern().
Set the current dash pattern to b black and w white units.
Set the flatness to a value between 0 and 100 inclusive.
Set the current font in the given size, using a font handle returned by pdf_findfont()
See Also: pdf_findfont().
Set the current fill color to a gray value between 0 and 1 inclusive.
Nota: PDFlib V4.0: Deprecated, use pdf_setcolor() instead.
Set the current stroke color to a gray value between 0 and 1 inclusive
Nota: PDFlib V4.0: Deprecated, use pdf_setcolor() instead.
Set the current fill and stroke color.
Nota: PDFlib V4.0: Deprecated, use pdf_setcolor() instead.
Set the linecap parameter to a value between 0 and 2 inclusive.
Set the line join parameter to a value between 0 and 2 inclusive.
Explicitly set the current transformation matrix.
Set the miter limit to a value greater than or equal to 1.
Set a more complicated dash pattern defined by an array.
Set the current fill color to the supplied RGB values.
Nota: PDFlib V4.0: Deprecated, use pdf_setcolor() instead.
Set the current stroke color to the supplied RGB values.
Nota: PDFlib V4.0: Deprecated, use pdf_setcolor() instead.
Set the current fill and stroke color to the supplied RGB values.
Nota: PDFlib V4.0: Deprecated, use pdf_setcolor() instead.
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.
Print text in the current font at (x, y).
Print text in the current font and size at the current position.
Skew the coordinate system in x and y direction by alpha and beta degrees.
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().
Stroke the path with the current color and line width, and clear it.
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.
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.
These functions are only available if PHP has been compiled with the --with-pfpro[=DIR] option.
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 |
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() 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().
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
|
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
|
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.
Não há nenhuma instalação nescessária para utilizar estas funções, elas fazem parte do núcleo do PHP.
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 |
Here is a short explanation of the configuration directives.
Enable assert() evaluation.
Terminate script execution on failed assertions.
Issue a PHP warning for each failed assertion.
user function to call on failed assertions
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()
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().
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.
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()
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.
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. |
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() 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
|
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)
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().
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().
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().
Returns the name of the owner of the current PHP script.
See also getmyuid(), getmygid(), getmypid(), getmyinode(), and getlastmod().
(PHP 4 >= 4.1.0)
get_defined_constants -- Returns an associative array with the names of all the constants and their valuesThis 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
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().
This function returns the names of all the functions defined in the module indicated by module_name.
For example the lines below
will print a list of the functions in the modules xml and gd respectively.See also: get_loaded_extensions()
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.
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().
This function returns the names of all the modules compiled and loaded in the PHP interpreter.
For example the line below
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().
(PHP 3>= 3.0.6, PHP 4 )
get_magic_quotes_gpc -- Gets the current active configuration setting of magic quotes gpcReturns 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().
(PHP 3>= 3.0.6, PHP 4 )
get_magic_quotes_runtime -- Gets the current active configuration setting of magic_quotes_runtimeReturns 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().
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().
Returns the value of the environment variable varname, or FALSE on an error.
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().
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.
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().
Returns the group ID of the current script, or FALSE on error.
See also getmyuid(), getmypid(), get_current_user(), getmyinode(), and getlastmod().
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
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().
Returns the user ID of the current script, or FALSE on error.
See also getmygid(), getmypid(), get_current_user(), getmyinode(), and getlastmod().
Returns an associative array of option / argument pairs based on the options format specified in options, or FALSE on an error.
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
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.
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()
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()
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()
Restores a given configuration option to its original value.
See also: ini_alter(), ini_get(), ini_get_all(), and ini_set()
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 4 >= 4.3.0)
php_ini_scanned_files -- Return a list of .ini files parsed from the additional ini dirphp_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.
Nota: This functionality was added in PHP 4.0.0.
See also: phpinfo(), phpversion(), and phpcredits().
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.
php_uname() returns a string with a description of the operating system PHP is built on.
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:
And if you want to print the core developers and the documentation group, in a page of its own, you will use: 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().
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. |
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.
Returns a string containing the version of the currently running PHP parser.
Nota: This information is also available in the predefined constant PHP_VERSION.
See also version_compare(), phpinfo(), phpcredits(), php_logo_guid(), and zend_version().
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! |
See also getenv().
(PHP 3>= 3.0.6, PHP 4 )
set_magic_quotes_runtime -- Sets the current active configuration setting of magic_quotes_runtimeSet 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 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() 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.
Returns a string containing the version of the currently running PHP parser.
See also phpinfo(), phpcredits(), php_logo_guid(), and phpversion().
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.
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
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.
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.
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.
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
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.
Returns the login name of the user owning the current process. See posix_getpwnam() for information how to get more information about this user.
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.
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.
Return the process identifier of the parent process of the current process.
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. |
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. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
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.
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.
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
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() 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.
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.
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().
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.
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.
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.
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().
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.
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
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.
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.
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/.
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().
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 |
Aqui está uma pequena explicação sobre as diretivas de configuração.
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
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.
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.
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)
|
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.
Nota: Esta função costumava ser chamada de pg_cmdtuples().
Veja também pg_query() e pg_num_rows().
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() 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() 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() 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
|
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() 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() 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() 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().
(PHP 4 >= 4.3.0)
pg_convert -- Converte os valores de um array associativo em uma declaração SQL apropriada.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() 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() 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() 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() 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.
Nota: Esta função é experimental.
Veja também pg_convert()
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() 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() 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() 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
|
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
|
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() 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
|
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
|
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() 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() 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
|
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() 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() 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() 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() 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() 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() 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() 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() 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
|
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()
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() 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() 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.
Nota: Esta função é experimental.
Veja também pg_convert()
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() 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() é 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() 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() 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().
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().
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() 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().
(PHP 4 >= 4.2.0)
pg_lo_read_all -- Lê um objeto grande (large object) inteiro e o envia diretamente para o navegadorpg_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() 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() 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() retorna a posição atual (deslocamento a partir do início do objeto grande).
Veja também pg_lo_seek().
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() 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() 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() 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() 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() retornará uma string contendo as opções especificadas no recurso (resource) de conexão PostgreSQL connection.
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() 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().
pg_port() retorna o número da porta a qual o recurso de conexão PostgreSQL connection está conectado.
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
|
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() 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()
(PHP 4 >= 4.3.0)
pg_result_seek -- Altera a posição do ponteiro interno de um recurso (resource) de resultadopg_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() 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() 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.
Nota: Esta função é experimental.
Veja também pg_convert()
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() 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() 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() retorna o nome da tty que a saída do lado do servidor é enviada no recurso (resource) de conexão connection.
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()
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() 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
|
Nota: Esta função é experimental.
Veja também pg_convert()
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.
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).
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.
This example forks off a daemon process with a signal handler.
Exemplo 1. Process Control Example
|
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
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.
See also pcntl_waitpid() and pcntl_signal().
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
|
See also pcntl_fork() and pcntl_waitpid().
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().
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().
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().
(PHP 4 >= 4.1.0)
pcntl_wifsignaled -- Returns TRUE if status code represents a termination due to a signalReturns 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().
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().
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().
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().
Those functions provides means to executes commands on the system itself, and means secure such commands.
Não há nenhuma instalação nescessária para utilizar estas funções, elas fazem parte do núcleo do PHP.
These functions are also closely related to the backtick operator. Also, while in Safe Mode you must consider the safe_mode_exec_dir directive.
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:
See also exec(), popen(), system(), and the backtick operator.
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() 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.
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.
(PHP 4 >= 4.3.0)
proc_close -- Close a process opened by proc_open and return the exit code of that 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() 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.
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.
These functions are only available under Windows 9.x, ME, NT4 and 2000. They have been added in PHP 4.0.4.
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 |
This function deletes the printers spool file.
handle must be a valid handle to a printer.
This function closes the printer connection. printer_close() also closes the active device context.
handle must be a valid handle to a printer.
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.
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
|
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().
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.
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.
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.
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.
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.
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.
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
|
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
|
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
|
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
|
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
|
(no version information, might be only in CVS)
printer_draw_roundrect -- Draw a rectangle with rounded cornersThe 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
|
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
|
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.
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.
(no version information, might be only in CVS)
printer_get_option -- Retrieve printer configuration dataThe 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.
(no version information, might be only in CVS)
printer_list -- Return an array of printers attached to the serverThe 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.
The function calculates the logical font height of height. handle must be a valid handle to a printer.
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.
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
|
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
|
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
|
(no version information, might be only in CVS)
printer_set_option -- Configure the printer connectionThe 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.
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.
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.
These functions allow you to check the spelling of a word and offer suggestions.
Nota: This extension is not available on Windows platforms.
To compile PHP with pspell support, you need the aspell and pspell libraries, available from http://aspell.sourceforge.net/ and http://aspell.net/ respectively.
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.
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() checks the spelling of a word and returns TRUE if the spelling is correct, FALSE if not.
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_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/.
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.
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)
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.
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_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.
(PHP 4 >= 4.0.2)
pspell_config_save_repl -- Determine whether to save a replacement pairs list along with the wordlistpspell_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() 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.
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.
For more information and examples, check out inline manual pspell website:http://aspell.net/.
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.
For more information and examples, check out inline manual pspell website:http://aspell.net/.
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_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()
|
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.
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.
This function adds a line to the command line history.
This function clears the entire command line history.
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.
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.
This function returns an array of the entire command line history. The elements are indexed by integers starting at zero.
This function reads a command history from a file.
This function writes the command history to a file.
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().
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.
You must have GNU Recode 3.5 or higher installed on your system. You can download the package from here.
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. |
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.
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.
Nota: This is an alias for recode_string(). It has been added in PHP 4.
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..
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/.
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.
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(). |
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.
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.
The differences described here are with respect to Perl 5.005.
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.
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.
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.
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.
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.
The Perl \G assertion is not supported as it is not relevant to single pattern matches.
Fairly obviously, PCRE does not support the (?{code}) construction.
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.
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.
PCRE provides some extensions to the Perl regular expression facilities:
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.
If PCRE_DOLLAR_ENDONLY is set and PCRE_MULTILINE is not set, the $ meta- character matches only at the very end of the string.
If PCRE_EXTRA is set, a backslash followed by a letter with no special meaning is faulted.
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.
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.
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
general escape character
negate the class, but only if the first character
indicates character range
terminates the character class
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:
alarm, that is, the BEL character (hex 07)
"control-x", where x is any character
escape (hex 1B)
formfeed (hex 0C)
newline (hex 0A)
carriage return (hex 0D)
tab (hex 09)
character with hex code hh
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:
is another way of writing a space
is the same, provided there are fewer than 40 previous capturing subpatterns
is always a back reference
might be a back reference, or another way of writing a tab
is always a tab
is a tab followed by the character "3"
is the character with octal code 113 (since there can be no more than 99 back references)
is a byte consisting entirely of 1 bits
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:
any decimal digit
any character that is not a decimal digit
any whitespace character
any character that is not a whitespace character
any "word" character
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
word boundary
not a word boundary
start of subject (independent of multiline mode)
end of subject or newline at end (independent of multiline mode)
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.
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.
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.
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 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.
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 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 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".
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.
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.
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.
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.
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.
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.
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() 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.
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):
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 |
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 example will produce: 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.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 2. Find matching HTML tags (greedy)
|
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().
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:
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 .
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 2. find the word "web"
|
Exemplo 3. Getting the domain name out of a URL
This example will produce:
|
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 2. Italicizing a word within some text
|
(PHP 4 >= 4.0.5)
preg_replace_callback -- Perform a regular expression search and replace using a callbackThe 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().
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.
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()
|
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().
$startDate = 5/27/1999 |
Exemplo 5. Convert HTML to text
|
Nota: Parameter limit was added after PHP 4.0.1pl2.
See also preg_match(), preg_match_all(), and preg_split().
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):
If this flag is set, only non-empty pieces will be returned by preg_split().
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.
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 3. Splitting a string into matches and their offsets.
will yield
|
See also spliti(), split(), implode(), preg_match(), preg_match_all(), and preg_replace().
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.
(PHP 4 >= 4.0.5)
qdom_error -- Returns the error string from the last QDOM operation or FALSE if no errors occuredAtenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
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.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.
Exemplo 1. Regular Expression Examples
|
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().
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:
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
|
See also ereg(), eregi(), eregi_replace(), str_replace(), and preg_match().
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:
See also eregi(), ereg_replace(), eregi_replace(), and preg_match().
This function is identical to ereg_replace() except that this ignores case distinction when matching alphabetic characters.
See also ereg(), eregi(), and ereg_replace().
This function is identical to ereg() except that this ignores case distinction when matching alphabetic characters.
See also ereg(), ereg_replace(), and eregi_replace().
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:
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:
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().
This function is identical to split() except that this ignores case distinction when matching alphabetic characters.
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.
[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.
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.
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.
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 |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
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() 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() 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() 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() 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() 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).
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().
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.
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.
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() 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() 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() 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.
Inserts or updates a variable with a given variable_key. All variable-types are supported.
Nota: This function does not work on Windows systems.
Removes a variable with a given variable_key and frees the occupied memory.
Nota: This function does not work on Windows systems.
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.
O comportamento dessas funções podem ser modificado pelas configurações do php.ini.
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.
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):
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.
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_configfile | Name of SESAM application configuration file.
Required for using SESAM functions.
Example: It will usually contain a configuration like (see SESAM reference manual): |
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: |
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.
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.
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) |
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.
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.
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.
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 |
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:
When retrieving a result row, "multiple columns" are accessed like "inlined" additional columns. In the example above, "pkey" will have the index 0, and the three "multi(1..3)" columns will be accessible as indices 1 through 3.
For specific SESAM details, please refer to the SESAM/SQL-Server documentation (english) or the SESAM/SQL-Server documentation (german), both available online, or use the respective manuals.
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()
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().
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().
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
|
See also: sesam_errormsg() for simple access to the error string only
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().
Returns the SESAM error message associated with the most recent SESAM error.
See also: sesam_diagnostic() for the full set of SESAM SQL status information
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"); |
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.
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:
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
|
See also: sesam_fetch_row() which returns an indexed array.
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. |
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().
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. |
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
|
See also: sesam_fetch_array() which returns an associative array, and sesam_fetch_result() which returns many rows per invocation.
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
|
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.
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".
Releases resources for the query associated with result_id. Returns FALSE on error.
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.
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
|
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
|
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.
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.
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.
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.
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.
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.
Constant containing the session name and session ID in the form of "name=ID".
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
|
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.
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
|
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)
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
|
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.
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).
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() 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).
session_decode() decifra dado de sessão em data, definindo variáveis guardadas na sessão.
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
|
Exemplo 2. Destruindo uma sessão com $_SESSION
|
session_encode() retorna uma string com o conteúdo da sessão corrente codificado em seu interior.
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() 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() 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() retorna o nome do módulo da sessão atual. Se module está especificado, o nome será trocado.
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).
(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çãoLer 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() 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ú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ç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() 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.
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() 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
|
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() 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(). |
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();
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.
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.
To use shmop you will need to compile PHP with the --enable-shmop parameter in your configure line.
Exemplo 1. Shared Memory Operations Overview
|
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().
This example will close shared memory block identified by $shm_id.
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.
This example will delete shared memory block identified by $shm_id.
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.
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.
This example opened a shared memory block with a system id of 0x0fff.
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.
This example will read 50 bytes from shared memory block and place the data inside $shm_data.
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.
This example will put the size of shared memory block identified by $shm_id into $shm_size.
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.
This example will write data inside $my_string into shared memory block, $shm_bytes_written will contain the number of bytes written.
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.
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.
Once you have libswf all you need to do is to configure --with-swf[=DIR] where DIR is a location containing the directories include and lib. The include directory has to contain the swf.h file and the lib directory has to contain the libswf.a file. If you unpack the libswf distribution the two files will be in one directory. Consequently you will have to copy the files to the proper location manually.
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.
Once you've successfully installed PHP with Shockwave Flash support you can then go about creating Shockwave files from PHP. You would be surprised at what you can do, take the following code:
Exemplo 1. SWF example
|
The swf_actionGetUrl() function gets the URL specified by the parameter url with the target target.
The swf_actionGotoFrame() function will go to the frame specified by framenumber, play it, and then stop.
The swf_actionGotoLabel() function displays the frame with the label given by the label parameter and then stops.
The swf_actionSetTarget() function sets the context for all actions. You can use this to control other flash movies that are currently playing.
Toggle the flash movie between high and low quality.
The swf_actionWaitForFrame() function will check to see if the frame, specified by the framenumber parameter has been loaded, if not it will skip the number of actions specified by the skipcount parameter. This can be useful for "Loading..." type animations.
The swf_addbuttonrecord() function allows you to define the specifics of using a button. The first parameter, states, defines what states the button can have, these can be any or all of the following constants: BSHitTest, BSDown, BSOver or BSUp. The second parameter, the shapeid is the look of the button, this is usually the object id of the shape of the button. The depth parameter is the placement of the button in the current frame.
Exemplo 1. swf_addbuttonrecord() function example
|
The swf_addcolor() function sets the global add color to the rgba color specified. This color is then used (implicitly) by the swf_placeobject(), swf_modifyobject() and the swf_addbuttonrecord() functions. The color of the object will be add by the rgba values when the object is written to the screen.
Nota: The rgba values can be either positive or negative.
Close a file that was opened by the swf_openfile() function. If the return_file parameter is set then the contents of the SWF file are returned from the function.
Exemplo 1. Creating a simple flash file based on user input and outputting it and saving it in a database
|
The swf_definebitmap() function defines a bitmap given a GIF, JPEG, RGB or FI image. The image will be converted into a Flash JPEG or Flash color map format.
The swf_definefont() function defines a font given by the fontname parameter and gives it the id specified by the fontid parameter. It then sets the font given by fontname to the current font.
The swf_defineline() defines a line starting from the x coordinate given by x1 and the y coordinate given by y1 parameter. Up to the x coordinate given by the x2 parameter and the y coordinate given by the y2 parameter. It will have a width defined by the width parameter.
The swf_definepoly() function defines a polygon given an array of x, y coordinates (the coordinates are defined in the parameter coords). The parameter npoints is the number of overall points that are contained in the array given by coords. The width is the width of the polygon's border, if set to 0.0 the polygon is filled.
The swf_definerect() defines a rectangle with an upper left hand coordinate given by the x, x1, and the y, y1. And a lower right hand coordinate given by the x coordinate, x2, and the y coordinate, y2 . Width of the rectangles border is given by the width parameter, if the width is 0.0 then the rectangle is filled.
Define a text string (the str parameter) using the current font and font size. The docenter is where the word is centered, if docenter is 1, then the word is centered in x.
The swf_endButton() function ends the definition of the current button.
Ends the current action started by the swf_startdoaction() function.
The swf_endshape() completes the definition of the current shape.
The swf_endsymbol() function ends the definition of a symbol that was started by the swf_startsymbol() function.
The swf_fontsize() function changes the font size to the value given by the size parameter.
Set the current font slant to the angle indicated by the slant parameter. Positive values create a foward slant, negative values create a negative slant.
Set the font tracking to the value specified by the tracking parameter. This function is used to increase the spacing between letters and text, positive values increase the space and negative values decrease the space between letters.
The swf_getbitmapinfo() function returns an array of information about a bitmap given by the bitmapid parameter. The returned array has the following elements:
"size" - The size in bytes of the bitmap.
"width" - The width in pixels of the bitmap.
"height" - The height in pixels of the bitmap.
The swf_getfontinfo() function returns an associative array with the following parameters:
Aheight - The height in pixels of a capital A.
xheight - The height in pixels of a lowercase x.
The swf_getframe() function gets the number of the current frame.
Label the current frame with the name given by the name parameter.
The swf_lookat() function defines a viewing transformation by giving the viewing position (the parameters view_x, view_y, and view_z) and the coordinates of a reference point in the scene, the reference point is defined by the reference_x, reference_y , and reference_z parameters. The twist controls the rotation along with viewer's z axis.
Updates the position and/or color of the object at the specified depth, depth. The parameter how determines what is updated. how can either be the constant MOD_MATRIX or MOD_COLOR or it can be a combination of both (MOD_MATRIX|MOD_COLOR).
MOD_COLOR uses the current mulcolor (specified by the function swf_mulcolor()) and addcolor (specified by the function swf_addcolor()) to color the object. MOD_MATRIX uses the current matrix to position the object.
The swf_mulcolor() function sets the global multiply color to the rgba color specified. This color is then used (implicitly) by the swf_placeobject(), swf_modifyobject() and the swf_addbuttonrecord() functions. The color of the object will be multiplied by the rgba values when the object is written to the screen.
Nota: The rgba values can be either positive or negative.
The swf_onCondition() function describes a transition that will trigger an action list. There are several types of possible transitions, the following are for buttons defined as TYPE_MENUBUTTON:
IdletoOverUp
OverUptoIdle
OverUptoOverDown
OverDowntoOverUp
IdletoOverDown
OutDowntoIdle
MenuEnter (IdletoOverUp|IdletoOverDown)
MenuExit (OverUptoIdle|OverDowntoIdle)
IdletoOverUp
OverUptoIdle
OverUptoOverDown
OverDowntoOverUp
OverDowntoOutDown
OutDowntoOverDown
OutDowntoIdle
ButtonEnter (IdletoOverUp|OutDowntoOverDown)
ButtonExit (OverUptoIdle|OverDowntoOutDown)
The swf_openfile() function opens a new file named filename with a width of width and a height of height a frame rate of framerate and background with a red color of r a green color of g and a blue color of b.
The swf_openfile() must be the first function you call, otherwise your script will cause a segfault. If you want to send your output to the screen make the filename: "php://stdout" (support for this is in 4.0.1 and up).
The swf_ortho2() function defines a two dimensional orthographic mapping of user coordinates onto the current viewport, this defaults to one to one mapping of the area of the Flash movie. If a perspective transformation is desired, the swf_perspective () function can be used.
(PHP 4 >= 4.0.1)
swf_ortho -- Defines an orthographic mapping of user coordinates onto the current viewportThe swf_ortho() function defines a orthographic mapping of user coordinates onto the current viewport.
The swf_perspective() function defines a perspective projection transformation. The fovy parameter is field-of-view angle in the y direction. The aspect parameter should be set to the aspect ratio of the viewport that is being drawn onto. The near parameter is the near clipping plane and the far parameter is the far clipping plane.
Nota: Various distortion artifacts may appear when performing a perspective projection, this is because Flash players only have a two dimensional matrix. Some are not to pretty.
Places the object specified by objid in the current frame at a depth of depth. The objid parameter and the depth must be between 1 and 65535.
This uses the current mulcolor (specified by swf_mulcolor()) and the current addcolor (specified by swf_addcolor()) to color the object and it uses the current matrix to position the object.
Nota: Full RGBA colors are supported.
The swf_polarview() function defines the viewer's position in polar coordinates. The dist parameter gives the distance between the viewpoint to the world space origin. The azimuth parameter defines the azimuthal angle in the x,y coordinate plane, measured in distance from the y axis. The incidence parameter defines the angle of incidence in the y,z plane, measured in distance from the z axis. The incidence angle is defined as the angle of the viewport relative to the z axis. Finally the twist specifies the amount that the viewpoint is to be rotated about the line of sight using the right hand rule.
The swf_popmatrix() function pushes the current transformation matrix back onto the stack.
(PHP 4 )
swf_posround -- Enables or Disables the rounding of the translation when objects are placed or movedThe swf_posround() function enables or disables the rounding of the translation when objects are placed or moved, there are times when text becomes more readable because rounding has been enabled. The round is whether to enable rounding or not, if set to the value of 1, then rounding is enabled, if set to 0 then rounding is disabled.
The swf_pushmatrix() function pushes the current transformation matrix back onto the stack.
The swf_rotate() rotates the current transformation by the angle given by the angle parameter around the axis given by the axis parameter. Valid values for the axis are 'x' (the x axis), 'y' (the y axis) or 'z' (the z axis).
The swf_scale() scales the x coordinate of the curve by the value of the x parameter, the y coordinate of the curve by the value of the y parameter, and the z coordinate of the curve by the value of the z parameter.
The swf_setfont() sets the current font to the value given by the fontid parameter.
The swf_setframe() changes the active frame to the frame specified by framenumber.
The swf_shapeArc() function draws a circular arc from angle A given by the ang1 parameter to angle B given by the ang2 parameter. The center of the circle has an x coordinate given by the x parameter and a y coordinate given by the y, the radius of the circle is given by the r parameter.
Draw a cubic bezier curve using the x,y coordinate pairs x1, y1 and x2,y2 as off curve control points and the x,y coordinate x3, y3 as an endpoint. The current position is then set to the x,y coordinate pair given by x3,y3.
The swf_shapecurveto() function draws a quadratic bezier curve from the current location, though the x coordinate given by x1 and the y coordinate given by y1 to the x coordinate given by x2 and the y coordinate given by y2. The current position is then set to the x,y coordinates given by the x2 and y2 parameters
Sets the fill to bitmap clipped, empty spaces will be filled by the bitmap given by the bitmapid parameter.
Sets the fill to bitmap tile, empty spaces will be filled by the bitmap given by the bitmapid parameter (tiled).
The swf_shapeFillOff() function turns off filling for the current shape.
The swf_shapeFillSolid() function sets the current fill style to solid, and then sets the fill color to the values of the rgba parameters.
The swf_shapeLineSolid() function sets the current line style to the color of the rgba parameters and width to the width parameter. If 0.0 is given as a width then no lines are drawn.
The swf_shapeLineTo() draws a line to the x,y coordinates given by the x parameter & the y parameter. The current position is then set to the x,y parameters.
The swf_shapeMoveTo() function moves the current position to the x coordinate given by the x parameter and the y position given by the y parameter.
The swf_startbutton() function starts off the definition of a button. The type parameter can either be TYPE_MENUBUTTON or TYPE_PUSHBUTTON. The TYPE_MENUBUTTON constant allows the focus to travel from the button when the mouse is down, TYPE_PUSHBUTTON does not allow the focus to travel when the mouse is down.
The swf_startdoaction() function starts the description of an action list for the current frame. This must be called before actions are defined for the current frame.
The swf_startshape() function starts a complex shape, with an object id given by the objid parameter.
Define an object id as a symbol. Symbols are tiny flash movies that can be played simultaneously. The objid parameter is the object id you want to define as a symbol.
The swf_textwidth() function gives the width of the string, str, in pixels, using the current font and font size.
The swf_translate() function translates the current transformation by the x, y, and z values given.
In order to use the SNMP functions on Unix you need to install the UCD SNMP package. On Windows these functions are only available on NT and not on Win95/98.
Important: In order to use the UCD SNMP package, you need to define NO_ZEROLENGTH_COMMUNITY to 1 before compiling it. After configuring UCD SNMP, edit config.h and search for NO_ZEROLENGTH_COMMUNITY. Uncomment the #define line. It should look like this afterwards:
#define NO_ZEROLENGTH_COMMUNITY 1 |
If you see strange segmentation faults in combination with SNMP commands, you did not follow the above instructions. If you do not want to recompile UCD SNMP, you can compile PHP with the --enable-ucd-snmp-hack switch which will work around the misfeature.
The Windows distribution contains support files for SNMP in the mibs directory. This directory should be moved to DRIVE:\usr\mibs, where DRIVE must be replaced with the driveletter where PHP is installed on, e.g.: c:\usr\mibs.
(PHP 3>= 3.0.8, PHP 4 )
snmp_get_quick_print -- Fetch the current value of the UCD library's quick_print settingReturns the current value stored in the UCD Library for quick_print. quick_print is off by default.
Above function call would return FALSE if quick_print is off, and TRUE if quick_print is on.
snmp_get_quick_print() is only available when using the UCD SNMP library. This function is not available when using the Windows SNMP library.
See: snmp_set_quick_print() for a full description of what quick_print does.
(PHP 3>= 3.0.8, PHP 4 )
snmp_set_quick_print -- Set the value of quick_print within the UCD SNMP librarySets the value of quick_print within the UCD SNMP library. When this is set (1), the SNMP library will return 'quick printed' values. This means that just the value will be printed. When quick_print is not enabled (default) the UCD SNMP library prints extra information including the type of the value (i.e. IpAddress or OID). Additionally, if quick_print is not enabled, the library prints additional hex values for all strings of three characters or less.
Setting quick_print is often used when using the information returned rather then displaying it.
snmp_set_quick_print(0); $a = snmpget("127.0.0.1", "public", ".1.3.6.1.2.1.2.2.1.9.1"); echo "$a<BR>\n"; snmp_set_quick_print(1); $a = snmpget("127.0.0.1", "public", ".1.3.6.1.2.1.2.2.1.9.1"); echo "$a<BR>\n"; |
The first value printed might be: 'Timeticks: (0) 0:00:00.00', whereas with quick_print enabled, just '0:00:00.00' would be printed.
By default the UCD SNMP library returns verbose values, quick_print is used to return only the value.
Currently strings are still returned with extra quotes, this will be corrected in a later release.
snmp_set_quick_print() is only available when using the UCD SNMP library. This function is not available when using the Windows SNMP library.
Returns SNMP object value on success and FALSE on error.
The snmpget() function is used to read the value of an SNMP object specified by the object_id. SNMP agent is specified by the hostname and the read community is specified by the community parameter.
(PHP 3>= 3.0.8, PHP 4 )
snmprealwalk -- Return all objects including their respective object ID within the specified one
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Sets the specified SNMP object value, returning TRUE on success and FALSE on error.
The snmpset() function is used to set the value of an SNMP object specified by the object_id. SNMP agent is specified by the hostname and the read community is specified by the community parameter.
Returns an array of SNMP object values starting from the object_id as root and FALSE on error.
snmpwalk() function is used to read all the values from an SNMP agent specified by the hostname. Community specifies the read community for that agent. A NULL object_id is taken as the root of the SNMP objects tree and all objects under that tree are returned as an array. If object_id is specified, all the SNMP objects below that object_id are returned.
Above function call would return all the SNMP objects from the SNMP agent running on localhost. One can step through the values with a loop
Returns an associative array with object ids and their respective object value starting from the object_id as root and FALSE on error.
snmpwalkoid() function is used to read all object ids and their respective values from an SNMP agent specified by the hostname. Community specifies the read community for that agent. A NULL object_id is taken as the root of the SNMP objects tree and all objects under that tree are returned as an array. If object_id is specified, all the SNMP objects below that object_id are returned.
The existence of snmpwalkoid() and snmpwalk() has historical reasons. Both functions are provided for backward compatibility.
Above function call would return all the SNMP objects from the SNMP agent running on localhost. One can step through the values with a loop
The socket extension implements a low-level interface to the socket communication functions based on the popular BSD sockets, providing the possibility to act as a socket server as well as a client.
For a more generic client-side socket interface, see fsockopen() and pfsockopen().
When using these functions, it is important to remember that while many of them have identical names to their C counterparts, they often have different declarations. Please be sure to read the descriptions to avoid confusion.
Those unfamiliar with socket programming can find a lot of useful material in the appropriate Unix man pages, and there is a great deal of tutorial information on socket programming in C on the web, much of which can be applied, with slight modifications, to socket programming in PHP. The UNIX Socket FAQ might be a good start.
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 socket functions described here are part of an extension to PHP which must be enabled at compile time by giving the --enable-sockets option to configure.
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.
The socket extension was written to provide a useable interface to the powerful BSD sockets. Care has been taken that the functions work equally well on Win32 and Unix implementations. Almost all of the sockets functions may fail under certain conditions and therefore emit an E_WARNING message describing the error. Sometimes this doesn't happen to the desire of the developer. For example the function socket_read() may suddenly emit an E_WARNING message because the connection broke unexpectedly. It's common to suppress the warning with the @-operator and catch the error code within the application with the socket_last_error() function. You may call the socket_strerror() function with this error code to retrieve a string describing the error. See their description for more information.
Nota: The E_WARNING messages generated by the socket extension are in english though the retrieved error message will appear depending on the current locale (LC_MESSAGES):
Warning - socket_bind() unable to bind address [98]: Die Adresse wird bereits verwendet
Exemplo 1. Socket example: Simple TCP/IP server This example shows a simple talkback server. Change the address and port variables to suit your setup and execute. You may then connect to the server with a command similar to: telnet 192.168.1.53 10000 (where the address and port match your setup). Anything you type will then be output on the server side, and echoed back to you. To disconnect, enter 'quit'.
|
Exemplo 2. Socket example: Simple TCP/IP client This example shows a simple, one-shot HTTP client. It simply connects to a page, submits a HEAD request, echoes the reply, and exits.
|
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco. |
After the socket socket has been created using socket_create(), bound to a name with socket_bind(), and told to listen for connections with socket_listen(), this function will accept incoming connections on that socket. Once a successful connection is made, a new socket resource is returned, which may be used for communication. If there are multiple connections queued on the socket, the first will be used. If there are no pending connections, socket_accept() will block until a connection becomes present. If socket has been made non-blocking using socket_set_blocking() or socket_set_nonblock(), FALSE will be returned.
The socket resource returned by socket_accept() may not be used to accept new connections. The original listening socket socket, however, remains open and may be reused.
Returns a new socket resource on success, or FALSE on error. The actual error code can be retrieved by calling socket_last_error(). This error code may be passed to socket_strerror() to get a textual explanation of the error.
See also socket_bind(), socket_connect(), socket_listen(), socket_create(), and socket_strerror().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco. |
socket_bind() binds the name given in address to the socket described by socket, which must be a valid socket resource created with socket_create().
The address parameter is either an IP address in dotted-quad notation (e.g. 127.0.0.1), if the socket is of the AF_INET family; or the pathname of a Unix-domain socket, if the socket family is AF_UNIX.
The port parameter is only used when connecting to an AF_INET socket, and designates the port on the remote host to which a connection should be made.
Retorna TRUE em caso de sucesso ou FALSE em falhas. The error code can be retrieved with socket_last_error(). This code may be passed to socket_strerror() to get a textual explanation of the error.
See also socket_connect(), socket_listen(), socket_create(), socket_last_error() and socket_strerror().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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 clears the error code on the given socket or the global last socket error.
This function allows explicitely resetting the error code value either of a socket or of the extension global last error code. This may be useful to detect within a part of the application if an error occured or not.
See also socket_last_error() and socket_strerror().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco. |
socket_close() closes the socket resource given by socket.
Nota: socket_close() can't be used on PHP file resources created with fopen(), popen(), fsockopen(), or pfsockopen(); it is meant for sockets created with socket_create() or socket_accept().
See also socket_bind(), socket_listen(), socket_create() and socket_strerror().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco. |
Initiates a connection using the socket resource socket, which must be a valid socket resource created with socket_create().
The address parameter is either an IP address in dotted-quad notation (e.g. 127.0.0.1), if the socket is of the AF_INET family; or the pathname of a Unix-domain socket, if the socket family is AF_UNIX.
The port parameter is only used when connecting to an AF_INET socket, and designates the port on the remote host to which a connection should be made.
Retorna TRUE em caso de sucesso ou FALSE em falhas. The error code can be retrieved with socket_last_error(). This code may be passed to socket_strerror() to get a textual explanation of the error.
See also socket_bind(), socket_listen(), socket_create(), socket_last_error() and socket_strerror().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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 meant to ease the task of creating a new socket which only listens to accept new connections.
socket_create_listen() create a new socket resource of type AF_INET listening on all local interfaces on the given port waiting for new connections.
The backlog parameter defines the maximum length the queue of pending connections may grow to. SOMAXCONN may be passed as backlog parameter, see socket_listen() for more information.
socket_create_listen() returns a new socket resource on success or FALSE on error. The error code can be retrieved with socket_last_error(). This code may be passed to socket_strerror() to get a textual explanation of the error.
Nota: If you want to create a socket which only listens on a certain interfaces you need to use socket_create(), socket_bind() and socket_listen().
See also socket_create(), socket_bind(), socket_listen(), socket_last_error() and socket_strerror().
(PHP 4 >= 4.1.0)
socket_create_pair -- Creates a pair of indistinguishable sockets and stores them in fds.Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Creates and returns a socket resource, also referred to as an endpoint of communication. A typical network connection is made up of 2 sockets, one performing the role of the client, and another performing the role of the server.
The domain parameter specifies the protocol family to be used by the socket.
Tabela 1. Available address/protocol families
Domain | Description |
---|---|
AF_INET | IPv4 Internet based protocols. TCP and UDP are common protocols of this protocol family. |
AF_UNIX | Local communication protocol family. High efficiency and low overhead make it a great form of IPC (Interprocess Communication). |
The type parameter selects the type of communication to be used by the socket.
Tabela 2. Available socket types
Type | Description |
---|---|
SOCK_STREAM | Provides sequenced, reliable, full-duplex, connection-based byte streams. An out-of-band data transmission mechanism may be supported. The TCP protocol is based on this socket type. |
SOCK_DGRAM | Supports datagrams (connectionless, unreliable messages of a fixed maximum length). The UDP protocol is based on this socket type. |
SOCK_SEQPACKET | Provides a sequenced, reliable, two-way connection-based data transmission path for datagrams of fixed maximum length; a consumer is required to read an entire packet with each read call. |
SOCK_RAW | Provides raw network protocol access. This special type of socket can be used to manually construct any type of protocol. A common use for this socket type is to perform ICMP requests (like ping, traceroute, etc). |
SOCK_RDM | Provides a reliable datagram layer that does not guarantee ordering. This is most likely not implemented on your operating system. |
The protocol parameter sets the specific protocol within the specified domain to be used when communicating on the returned socket. The proper value can be retrieved by name by using getprotobyname(). If the desired protocol is TCP, or UDP the corresponding constants SOL_TCP, and SOL_UDP can also be used.
Tabela 3. Common protocols
Name | Description |
---|---|
icmp | The Internet Control Message Protocol is used primarily by gateways and hosts to report errors in datagram communication. The "ping" command (present in most modern operating systems) is an example application of ICMP. |
udp | The User Datagram Protocol is a connectionless, unreliable, protocol with fixed record lengths. Due to these aspects, UDP requires a minimum amount of protocol overhead. |
tcp | The Transmission Control Protocol is a reliable, connection based, stream oriented, full duplex protocol. TCP guarantees that all data packets will be received in the order in which they were sent. If any packet is somehow lost during communication, TCP will automatically retransmit the packet until the destination host acknowledges that packet. For reliability and performance reasons, the TCP implementation itself decides the appropriate octet boundaries of the underlying datagram communication layer. Therefore, TCP applications must allow for the possibility of partial record transmission. |
socket_create() Returns a socket resource on success, or FALSE on error. The actual error code can be retrieved by calling socket_last_error(). This error code may be passed to socket_strerror() to get a textual explanation of the error.
Nota: If an invalid domain or type is given, socket_create() defaults to AF_INET and SOCK_STREAM respectively and additionally emits an E_WARNING message.
See also socket_accept(), socket_bind(), socket_connect(), socket_listen(), socket_last_error(), and socket_strerror().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Nota: This function used to be called socket_getopt() prior to PHP 4.3.0
(PHP 4 >= 4.1.0)
socket_getpeername -- Queries the remote side of the given socket which may either result in host/port or in a UNIX filesystem path, dependent on its type.Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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 the given socket is of type AF_INET, socket_getpeername() will return the peers (remote) IP address in dotted-quad notation (e.g. 127.0.0.1) in the address parameter and, if the optional port parameter is present, also the associated port.
If the given socket is of type AF_UNIX, socket_getpeername() will return the UNIX filesystem path (e.g. /var/run/daemon.sock) in the address parameter.
Retorna TRUE em caso de sucesso ou FALSE em falhas. socket_getpeername() may also return FALSE if the socket type is not any of AF_INET or AF_UNIX, in which case the last socket error code is not updated.
See also socket_getpeername(), socket_last_error() and socket_strerror().
(PHP 4 >= 4.1.0)
socket_getsockname -- Queries the local side of the given socket which may either result in host/port or in a UNIX filesystem path, dependent on its type.Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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 the given socket is of type AF_INET, socket_getsockname() will return the local IP address in dotted-quad notation (e.g. 127.0.0.1) in the address parameter and, if the optional port parameter is present, also the associated port.
If the given socket is of type AF_UNIX, socket_getsockname() will return the UNIX filesystem path (e.g. /var/run/daemon.sock) in the address parameter.
Retorna TRUE em caso de sucesso ou FALSE em falhas. socket_getsockname() may also return FALSE if the socket type is not any of AF_INET or AF_UNIX, in which case the last socket error code is not updated.
See also socket_getpeername(), socket_last_error() and socket_strerror().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
(PHP 4 >= 4.1.0)
socket_iovec_alloc -- ...]) Builds a 'struct iovec' for use with sendmsg, recvmsg, writev, and readvAtenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
(PHP 4 >= 4.1.0)
socket_iovec_fetch -- Returns the data held in the iovec specified by iovec_id[iovec_position]Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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 returns a socket error code.
If a socket resource is passed to this function, the last error which occured on this particular socket is returned. If the socket resource is ommited, the error code of the last failed socket function is returned. The latter is in particular helpful for functions like socket_create() which don't return a socket on failure and socket_select() which can fail for reasons not directly tied to a particular socket. The error code is suitable to be fed to socket_strerror() which returns a string describing the given error code.
if (false == ($socket = @socket_create(AF_INET, SOCK_STREAM, SOL_TCP))) { die("Couldn't create socket, error code is: " . socket_last_error() . ",error message is: " . socket_strerror(socket_last_error())); } |
Nota: socket_last_error() does not clear the error code, use socket_clear_error() for this purpose.
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco. |
After the socket socket has been created using socket_create() and bound to a name with socket_bind(), it may be told to listen for incoming connections on socket.
A maximum of backlog incoming connections will be queued for processing. If a connection request arrives with the queue full the client may receive an error with an indication of ECONNREFUSED, or, if the underlying protocol supports retransmission, the request may be ignored so that retries may succeed.
Nota: The maximum number passed to the backlog parameter highly depends on the underlying platform. On linux, it is silently truncated to SOMAXCONN. On win32, if passed SOMAXCONN, the underlying service provider responsible for the socket will set the backlog to a maximum reasonable value. There is no standard provision to find out the actual backlog value on this platform.
socket_listen() is applicable only to sockets of type SOCK_STREAM or SOCK_SEQPACKET.
Retorna TRUE em caso de sucesso ou FALSE em falhas. The error code can be retrieved with socket_last_error(). This code may be passed to socket_strerror() to get a textual explanation of the error.
See also socket_accept(), socket_bind(), socket_connect(), socket_create() and socket_strerror().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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 socket_read() reads from the socket resource socket created by the socket_create() or socket_accept() functions. The maximum number of bytes read is specified by the length parameter. Otherwise you can use \r, \n, or \0 to end reading (depending on the type parameter, see below).
socket_read() returns the data as a string on success, or FALSE on error. The error code can be retrieved with socket_last_error(). This code may be passed to socket_strerror() to get a textual representation of the error.
Nota: socket_read() may return a zero length string ("") indicating the end of communication (i.e. the remote end point has closed the connection).
Optional type parameter is a named constant:
PHP_BINARY_READ - use the system read() function. Safe for reading binary data. (Default in PHP >= 4.1.0)
PHP_NORMAL_READ - reading stops at \n or \r. (Default in PHP <= 4.0.6)
See also socket_accept(), socket_bind(), socket_connect(), socket_listen(), socket_last_error(), socket_strerror() and socket_write().
(PHP 4 >= 4.1.0)
socket_readv -- Reads from an fd, using the scatter-gather array defined by iovec_idAtenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
(PHP 4 >= 4.1.0)
socket_recvmsg -- Used to receive messages on a socket, whether connection-oriented or notAtenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
(PHP 4 >= 4.1.0)
socket_select -- Runs the select() system call on the given arrays of sockets with a timeout specified by tv_sec and tv_usecAtenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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 socket_select() accepts arrays of sockets and waits for them to change status. Those coming with BSD sockets background will recognize that those socket resource arrays are in fact the so-called file descriptor sets. Three independent arrays of socket resources are watched.
The sockets listed in the read array will be watched to see if characters become available for reading (more precisely, to see if a read will not block - in particular, a socket resource is also ready on end-of-file, in which case a socket_read() will return a zero length string).
The sockets listed in the write array will be watched to see if a write will not block.
The sockets listed in the except array will be watched for exceptions.
Atenção |
On exit, the arrays are modified to indicate which socket resource actually changed status. |
You do not need to pass every array to socket_select(). You can leave it out and use an empty array or NULL instead. Also do not forget that those arrays are passed by reference and will be modified after socket_select() returns.
Example:
/* Prepare the read array */ $read = array($socket1, $socket2); if (false === ($num_changed_sockets = socket_select($read, $write = NULL, $except = NULL, 0))) { /* Error handling */ else if ($num_changed_sockets > 0) { /* At least at one of the sockets something interesting happened */ } |
Nota: Due a limitation in the current Zend Engine it is not possible to pass a constant modifier like NULL directly as a parameter to a function which expects this parameter to be passed by reference. Instead use a temporary variable or an expression with the leftmost member being a temporary variable:
socket_select($r, $w, $e = NULL, 0);
The tv_sec and tv_usec together form the timeout parameter. The timeout is an upper bound on the amount of time elapsed before socket_select() return. tv_sec may be zero , causing socket_select() to return immediately. This is useful for polling. If tv_sec is NULL (no timeout), socket_select() can block indefinitely.
On success socket_select() returns the number of socket resorces contained in the modified arrays, which may be zero if the timeout expires before anything interesting happens. On error FALSE is returned. The error code can be retrieved with socket_last_error().
Nota: Be sure to use the === operator when checking for an error. Since the socket_select() may return 0 the comparison with == would evaluate to TRUE:
if (false === socket_select($r, $w, $e = NULL, 0)) { echo "socket_select() failed, reason: " . socket_strerror(socket_last_error()) . "\n"; }
Nota: Be aware that some socket implementations need to be handled very carefully. A few basic rules:
You should always try to use socket_select() without timeout. Your program should have nothing to do if there is no data available. Code that depends on timeouts is not usually portable and difficult to debug.
No socket resource must be added to any set if you do not intend to check its result after the socket_select() call, and respond appropriately. After socket_select() returns, all socket resources in all arrays must be checked. Any socket resource that is available for writing must be written to, and any socket resource available for reading must be read from.
If you read/write to a socket returns in the arrays be aware that they do not necessarily read/write the full amount of data you have requested. Be prepared to even only be able to read/write a single byte.
It's common to most socket implementations that the only exception caught with the except array is out-of-bound data received on a socket.
See also socket_read(), socket_write(), socket_last_error() and socket_strerror().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
(PHP 4 >= 4.1.0)
socket_sendmsg -- Sends a message to a socket, regardless of whether it is connection-oriented or notAtenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Nota: This function used to be called socket_setopt() prior to PHP 4.3.0
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco. |
socket_strerror() takes as its errno parameter a socket error code as returned by socket_last_error() and returns the corresponding explanatory text. This makes it a bit more pleasant to figure out why something didn't work; for instance, instead of having to track down a system include file to find out what '-111' means, you just pass it to socket_strerror(), and it tells you what happened.
Exemplo 1. socket_strerror() example
The expected output from the above example (assuming the script is not run with root privileges):
|
See also socket_accept(), socket_bind(), socket_connect(), socket_listen(), and socket_create().
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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 socket_write() writes to the socket socket from buffer.
The optional parameter length can specify an alternate length of bytes written to the socket. If this length is greater then the buffer length, it is silently truncated to the length of the buffer.
Returns the number of bytes successfully written to the socket or FALSE one error. The error code can be retrieved with socket_last_error(). This code may be passed to socket_strerror() to get a textual explanation of the error.
Nota: socket_write() does not necessarily write all bytes from the given buffer. It's valid that, depending on the network buffers etc., only a certain amount of data, even one byte, is written though your buffer is greater. You have to watch out so you don't unintentionally forget to transmit the rest of your data.
Nota: It is perfectly valid for socket_write() to return zero which means no bytes have been written. Be sure to use the === operator to check for FALSE in case of an error.
See also socket_accept(), socket_bind(), socket_connect(), socket_listen(), socket_read() and socket_strerror().
(PHP 4 >= 4.1.0)
socket_writev -- Writes to a file descriptor, fd, using the scatter-gather array defined by iovec_idAtenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Streams were introduced with PHP 4.3.0 as a way of generalizing file, network, data compression, and other opperations which share a common set of functions and uses. In its simplest definition, a stream is a resource object which exhibits streamable behavior. That is, it can be read from or written to in a linear fashion, and may be able to fseek() to an arbitrary locations within the stream.
A wrapper is additional code which tells the stream how to handle specific protocols/encodings. For example, the http wrapper knows how to translate a URL into an HTTP/1.0 request for a file on a remote server. There are many wrappers built into PHP by default (See Apêndice I), and additional, custom wrappers may be added either within a PHP script using stream_register_wrapper(), or directly from an extension using the API Reference in Capítulo 43. Because any variety of wrapper may be added to PHP, there is no set limit on what can be done with them. To access the list of currently registered wrappers, use stream_get_wrappers().
A filter is a final piece of code which may perform opperations on data as it is being read from or written to a stream. Any number of filters may be stacked onto a stream. Custom filters can be defined in a PHP script using stream_register_filter() or in an extension using the API Reference in Capítulo 43. To access the list of currently registered filters, use stream_get_filters().
A stream is referenced as: scheme://target
scheme(string) - The name of the wrapper to be used. Examples include: file, http, https, ftp, ftps, compress.zlib, compress.bz2, and php. See Apêndice I for a list of PHP builtin wrappers. If no wrapper is specified, the function default is used (typically file://).
target - Depends on the wrapper used. For filesystem related streams this is typically a path and filename of the desired file. For network related streams this is typically a hostname, often with a path appended. Again, see Apêndice I for a description of targets for builtin streams.
Streams are an integral part of PHP as of version 4.3.0. No steps are required to enable them.
User designed wrappers can be registered via stream_register_wrapper(), using the class definition shown on that manual page.
class php_user_filter is predefined and is an abstract baseclass for use with user defined filters. See the manual page for stream_register_filter() for details on implementing user defined filters.
Constant | Description |
---|---|
STREAM_USE_PATH | Flag indicating if the stream used the include path. |
STREAM_REPORT_ERRORS | Flag indicating if the wrapper is responsible for raising errors using trigger_error() during opening of the stream. If this flag is not set, you should not raise any errors. |
As with any file or socket related function, an opperation on a stream may fail for a variety of normal reasons (i.e.: Unable to connect to remote host, file not found, etc...). A stream related call may also fail because the desired stream is not registered on the running system. See the array returned by stream_get_wrappers() for a list of streams supported by your installation of PHP. As with most PHP internal functions if a failure occours an E_WARNING message will be generated describing the nature of the error.
Exemplo 1. Using file_get_contents() to retrieve data from multiple sources
|
Exemplo 2. Making a POST request to an https server
|
Exemplo 3. Writting data to a compressed file
|
Creates and returns a stream context with any parameters supplied in params preset.
See Also: stream_context_set_params()
Returns an array of options on the specified stream or context.
Sets an option on the specified context. value is set to option for wrapper
params should be an associative array of the structure: $params['paramname'] = "paramvalue";.
Adds filtername to the list of filters attached to stream. This filter will be added with the specified params to the end of the list and will therefore be called last during stream opperations. To add a filter to the beginning of the list, use stream_filter_prepend().
Nota: stream_register_filter() must be called first in order to register the desired user filter to filtername.
See Also: stream_register_filter(), and stream_filter_prepend()
Adds filtername to the list of filters attached to stream. This filter will be added with the specified params to the beginning of the list and will therefore be called first during stream opperations. To add a filter to the end of the list, use stream_filter_append().
Nota: stream_register_filter() must be called first in order to register the desired user filter to filtername.
See Also: stream_register_filter(), and stream_filter_append()
Returns an indexed array containing the name of all stream filters available on the running system.
Exemplo 1. Using stream_get_filters()
|
See Also: stream_register_filter(), and stream_get_wrappers()
Returns information about an existing stream. The stream can be any stream created by fopen(), fsockopen() and pfsockopen(). The result array contains the following items:
timed_out (bool) - TRUE if the stream timed out while waiting for data on the last call to fread() or fgets().
blocked (bool) - TRUE if the stream is in blocking IO mode. See socket_set_blocking().
eof (bool) - TRUE if the stream has reached end-of-file. Note that for socket streams this member can be TRUE even when unread_bytes is non-zero. To determine if there is more data to be read, use feof() instead of reading this item.
unread_bytes (int) - the number of bytes currently contained in the read buffer.
The following items were added in PHP 4.3:
stream_type (string) - a label describing the underlying implementation of the stream.
wrapper_type (string) - a label describing the protocol wrapper implementation layered over the stream. See Apêndice I for more information about wrappers.
wrapper_data (mixed) - wrapper specific data attached to this stream. See Apêndice I for more information about wrappers and their wrapper data.
filters (array) - and array containing the names of any filters that have been stacked onto this stream. Filters are currently undocumented.
Nota: This function was introduced in PHP 4.3, but prior to this version, socket_get_status() could be used to retrieve the first four items, for socket based streams only.
In PHP 4.3 and later, socket_get_status() is an alias for this function.
Nota: This function does NOT work on sockets created by the Socket extension.
Returns an indexed array containing the name of all stream wrappers available on the running system.
See Also: stream_register_wrapper()
(PHP 5 CVS only)
stream_register_filter -- Register a stream filter implemented as a PHP class derived from php_user_filterstream_register_filter() allows you to implement your own filter on any registered stream used with all the other filesystem functions (such as fopen(), fread() etc.).
To implement a filter, you need to define a class as an extension of php_user_fitler with a number of member functions as defined below. When performing read/write opperations on the stream to which your filter is attached, PHP will pass the data through your filter (and any other filters attached to that stream) so that the data may be modified as desired. You must implement the methods exactly as described below - doing otherwise will lead to undefined behaviour.
stream_register_filter() will return FALSE if the filtername is already defined.
int write ( string data)This method is called whenever data is written to the attached stream (such as with fwrite()). After modifying data as needed your filter should issue: return parent::write($data); so that the next filter in the chain can perform its filter. When no filters remain, the stream will write data in its final form.
Nota: If your filter alters the length of data, for example by removing the first character, before passing onto parent::write($data); it must be certain to include that stolen character in the return count.
class myfilter extends php_user_filter { function write($data) { $data = substr($data,1); $written_by_parent = parent::write($data); return ($written_by_parent + 1); } } |
This method is called whenever data is read from the attached stream (such as with fread()). A filter should first call parent::read($maxlength); to retrieve the data from the previous filter who, ultimately, retrieved it from the stream. Your filter may then modify the data as needed and return it. Your filter should never return more than maxlength bytes. Since parent::read($maxlength); will also not return more than maxlength bytes this will ordinarily be a non-issue. However, if your filter increases the size of the data being returned, you should either call parent::read($maxlength-$x); where x is the most your filter will grow the size of the data read. Alternatively, you can build a read-buffer into your class.
int flush ( bool closing)This method is called in response to a request to flush the attached stream (such as with fflush() or fclose()). The closing parameter tells you whether the stream is, in fact, in the process of closing. The default action is to simply call: return parent::flush($closing); , your filter may wish to perform additional writes and/or cleanup calls prior to or directly after a successful flush.
void oncreate ( void)This method is called during instantiation of the filter class object. If your filter allocates or initializes any other resources (such as a buffer), this is the place to do it.
void onclose ( void)This method is called upon filter shutdown (typically, this is also during stream shutdown), and is executed after the flush method is called. If any resources were allocated or initialzed during oncreate this would be the time to destroy or dispose of them.
The example below implements a filter named rot13 on the foo-bar.txt stream which will perform ROT-13 encryption on all letter characters written to/read from that stream.
Exemplo 1. Filter for ROT13 encoding data on foo-bar.txt stream
|
See Also: stream_register_wrapper(), stream_filter_prepend(), and stream_filter_append()
stream_register_wrapper() allows you to implement your own protocol handlers and streams for use with all the other filesystem functions (such as fopen(), fread() etc.).
To implement a wrapper, you need to define a class with a number of member functions, as defined below. When someone fopens your stream, PHP will create an instance of classname and then call methods on that instance. You must implement the methods exactly as described below - doing otherwise will lead to undefined behaviour.
stream_register_wrapper() will return FALSE if the protocol already has a handler.
boolean stream_open ( string path, string mode, int options, string opened_path)This method is called immediately after your stream object is created. path specifies the URL that was passed to fopen() and that this object is expected to retrieve. You can use parse_url() to break it apart.
mode is the mode used to open the file, as detailed for fopen(). You are responsible for checking that mode is valid for the path requested.
options holds additional flags set by the streams API. It can hold one or more of the following values OR'd together.
Flag | Description |
---|---|
STREAM_USE_PATH | If path is relative, search for the resource using the include_path. |
STREAM_REPORT_ERRORS | If this flag is set, you are responsible for raising errors using trigger_error() during opening of the stream. If this flag is not set, you should not raise any errors. |
If the path is opened successfully, and STREAM_USE_PATH is set in options, you should set opened_path to the full path of the file/resource that was actually opened.
If the requested resource was opened successfully, you should return TRUE, otherwise you should return FALSE
void stream_close ( void )This method is called when the stream is closed, using fclose(). You must release any resources that were locked or allocated by the stream.
string stream_read ( int count)This method is called in response to fread() and fgets() calls on the stream. You must return up-to count bytes of data from the current read/write position as a string. If there are less than count bytes available, return as many as are available. If no more data is available, return either FALSE or an empty string. You must also update the read/write position of the stream by the number of bytes that were successfully read.
int stream_write ( string data)This method is called in response to fwrite() calls on the stream. You should store data into the underlying storage used by your stream. If there is not enough room, try to store as many bytes as possible. You should return the number of bytes that were successfully stored in the stream, or 0 if none could be stored. You must also update the read/write position of the stream by the number of bytes that were successfully written.
boolean stream_eof ( void )This method is called in response to feof() calls on the stream. You should return TRUE if the read/write position is at the end of the stream and if no more data is available to be read, or FALSE otherwise.
int stream_tell ( void )This method is called in response to ftell() calls on the stream. You should return the current read/write position of the stream.
boolean stream_seek ( int offset, int whence)This method is called in response to fseek() calls on the stream. You should update the read/write position of the stream according to offset and whence. See fseek() for more information about these parameters. Return TRUE if the position was updated, FALSE otherwise.
boolean stream_flush ( void )This method is called in response to fflush() calls on the stream. If you have cached data in your stream but not yet stored it into the underlying storage, you should do so now. Return TRUE if the cached data was successfully stored (or if there was no data to store), or FALSE if the data could not be stored.
The example below implements a var:// protocol handler that allows read/write access to a named global variable using standard filesystem stream functions such as fread(). The var:// protocol implemented below, given the url "var://foo" will read/write data to/from $GLOBALS["foo"].
Exemplo 1. A Stream for reading/writing global variables
|
(PHP 4 >= 4.3.0)
stream_select -- Runs the equivalent of the select() system call on the given arrays of streams with a timeout specified by tv_sec and tv_usecThe stream_select() function accepts arrays of streams and waits for them to change status. Its opperation is equivalent to that of the socket_select() function except in that it acts on streams.
The streams listed in the read array will be watched to see if characters become available for reading (more precisely, to see if a read will not block - in particular, a stream resource is also ready on end-of-file, in which case an fread() will return a zero length string).
The streams listed in the write array will be watched to see if a write will not block.
The streams listed in the except array will be watched for exceptions.
Atenção |
On exit, the arrays are modified to indicate which stream resource actually changed status. |
You do not need to pass every array to stream_select(). You can leave it out and use an empty array or NULL instead. Also do not forget that those arrays are passed by reference and will be modified after stream_select() returns.
Example:
/* Prepare the read array */ $read = array($stream1, $stream2); if (false === ($num_changed_streams = stream_select($read, $write = NULL, $except = NULL, 0))) { /* Error handling */ else if ($num_changed_streams > 0) { /* At least on one of the streams something interesting happened */ } |
Nota: Due a limitation in the current Zend Engine it is not possible to pass a constant modifier like NULL directly as a parameter to a function which expects this parameter to be passed by reference. Instead use a temporary variable or an expression with the leftmost member being a temporary variable:
stream_select($r, $w, $e = NULL, 0);
The tv_sec and tv_usec together form the timeout parameter. The timeout is an upper bound on the amount of time elapsed before stream_select() returns. tv_sec may be zero , causing stream_select() to return immediately. This is useful for polling. If tv_sec is NULL (no timeout), stream_select() can block indefinitely.
On success stream_select() returns the number of stream resorces contained in the modified arrays, which may be zero if the timeout expires before anything interesting happens. On error FALSE is returned.
Nota: Be sure to use the === operator when checking for an error. Since the stream_select() may return 0 the comparison with == would evaluate to TRUE:
if (false === stream_select($r, $w, $e = NULL, 0)) { echo "stream_select() failed\n"; }
Nota: Be aware that some stream implementations need to be handled very carefully. A few basic rules:
You should always try to use stream_select() without timeout. Your program should have nothing to do if there is no data available. Code that depends on timeouts is not usually portable and difficult to debug.
If you read/write to a stream returned in the arrays be aware that they do not necessarily read/write the full amount of data you have requested. Be prepared to even only be able to read/write a single byte.
See also stream_set_blocking()
If mode is FALSE, the given stream will be switched to non-blocking mode, and if TRUE, it will be switched to blocking mode. This affects calls like fgets() and fread() that read from the stream. In non-blocking mode an fgets() call will always return right away while in blocking mode it will wait for data to become available on the stream.
This function was previously called as set_socket_blocking() and later socket_set_blocking() but this usage is deprecated.
Nota: Prior to PHP 4.3, this function only worked on socket based streams. Since PHP 4.3, this function works for any stream that supports non-blocking mode (currently, regular files and socket streams).
Sets the timeout value on stream, expressed in the sum of seconds and microseconds.
Exemplo 1. stream_set_timeout() Example
|
Nota: As of PHP 4.3, this function can (potentially) work on any kind of stream. In PHP 4.3, socket based streams are still the only kind supported in the PHP core, although streams from other extensions may support this function.
This function was previously called as set_socket_timeout() and later socket_set_timeout() but this usage is deprecated.
See also: fsockopen() and fopen().
Output using fwrite() is normally buffered at 8K. This means that if there are two processes wanting to write to the same output stream (a file), each is paused after 8K of data to allow the other to write. stream_set_write_buffer() sets the buffering for write operations on the given filepointer stream to buffer bytes. If buffer is 0 then write operations are unbuffered. This ensures that all writes with fwrite() are completed before other processes are allowed to write to that output stream.
The function returns 0 on success, or EOF if the request cannot be honored.
The following example demonstrates how to use stream_set_write_buffer() to create an unbuffered stream.
Todas estas funções manipulam strings de várias maneiras. Algumas mais especializadas podem ser encontradas na expressão formal e URL handling sessões.
Para informações de como a string se comporta, especialmente com realção ao uso de aspas simples, aspas duplas, seqüências de escape, veja o Strings dentro da sessão Types do manual.
Não há nenhuma instalação nescessária para utilizar estas funções, elas fazem parte do núcleo do PHP.
Para as mais poderosas funções de manipulação de strings dê uma olhada em POSIX regular expression functions e Perl compatible regular expression functions.
Retorna uma string com barras invertidas antes dos caracteres que estão listados no parâmetro charlist. Ela escapa \n, \r etc. Como no estilo C, caracteres no código ASCII menores que 32 e maiores que 126 são convertidos para representação octadecimal.
Tome cuidado se você escolher escapar caracteres 0, a, b, f, n, r, t e v. Eles serão convertidos para \0, \a, \b, \f, \n, \r, \t e \v. No PHP \0 (NULL), \r (sinal de retorno), \n (novalinha) e \t (tab) são seqüencias de escape predefinidas, enquanto em C todas essas são seqüencias de escape predefinidas.
charlist como "\0..\37", que que escaparia todos os caracteres em código ASCII entre 0 e 37.
Quando você define uma seqüencia de caracteres no argumento charlist certifique-se que você sabe quais os caracteres que vêm dentro do intervalo que você definiu.
echo addcslashes('foo[ ]', 'A..z'); // output: \f\o\o\[ \] // All upper and lower-case letters will be escaped // ... but so will the [\]^_` and any tabs, line // feeds, carriage returns, etc. |
Veja também stripcslashes(), stripslashes(), htmlspecialchars(), e quotemeta().
Retorna uma string com barras invertidas antes dos caracteres que precisam estar entre aspas numa pesquisa ao banco de dados e etc. Estes caracteres estão com aspas simples ('), dupla ("), barra invertida (\) e NUL (o NULL byte).
Nota: magic_quotes_gpc está ON por definição.
veja também stripslashes(), htmlspecialchars(), e quotemeta().
Retorna uma string ASCII uma representação hexadecimal de str. A conversão é feita byte-wise com o high-nibble primeiro.
Esta função é um alias de rtrim().
Nota: chop() é diferente da função de Perl chop(), que remove o último caracter na string.
Retorna uma string de um único caractere contendo o caracter especificado pelo ascii.
Você pode encontrar uma tabela ASCII-table aqui: http://www.asciitable.com/.
Esta função complementa ord(). Veja também sprintf() com uma string no formato de %c.
Pode dividir uma string em pequenos pedaços que são úteis para e.g. converter base64_encode output para compatibilizar com semânticas RFC 2045 . Ela insere end (padrão para "\r\n") cada caracater chunklen (padrão para 76). Ela retorna uma nova string deixando a string original intocada.
Veja também explode(), split() wordwrap() e RFC 2045.
Esta função retorna a string dada convertida de um caracter cirílico para outro. Os argumentos from e to são caracteres simples que representam o original e o caractere Cirílico de destino. Os tipos suportados são:
k - koi8-r
w - windows-1251
i - iso8859-5
a - x-cp866
d - x-cp866
m - x-mac-cyrillic
Conta o número de ocorrências de cada byte-value (0..255) na string e retorna ela de várias maneiras. O parâmetro original Mode por definição 0. A depender do mode count_chars() pode retornar os seguintes:
0 - Uma matriz com um byte-value como chave e a freqüência de cada byte como valor.
1 - mesmo que o 0 mas apenas byte-values com freqüência maior do que 0 são listadas.
2 - mesmo que 0 mas apenas byte-values com freqüência igual a 0 são listadas.
3 - uma string contendo todos os byte-values usados.
4 - uma string contendo todos os byte-values que não foram usados.
Gera o polinômio cyclic redundancy checksum de 32-bit de comprimento do str. É usado geralmente para validar a integridade de um dado sendo transferido.
Veja também md5()
crypt() retornará uma string criptografada usando o algoritmo de encriptação Unix Standard DES-based ou ou algoritmos alternativos disponíveis no sistema. Os argumentos são uma string para ser criptografada e uma string opcional para basear em qual encriptação está. Veja a página de encriptação Unix para mais informação.
Se o argumento salt não é fornecido, um argumento aleatório será gerado pelo PHP.
Alguns SO suportam mais de um tipo de codificação. De fato, algumas vezes a codificação Standard DES-based é substituído por MD5-based . O tipo de codificação é definido pelo argumento salt. Na instalação, o PHP determina as possíveis funções de codificação e aceitará salts para outros tipos. Se nenhum salt é fornecido, o PHP auto-gera um salt padrão de 2 caracateres por definição, a menos que o tipo de codificação padrão do sistema seja MD5, nesse caso um salt MD5-compatible aleatório será gerado. O PHP define uma constante com nome CRYPT_SALT_LENGTH que dirá se um salt de 2 caracteres aplica-se ao seu sistema ou se o salt mais comprido de 12 caracteres é aplicavél.
Se você está usando um salt fornecido, você está ciente que o salt é gerado uma vez. Se você está chamando essa função repetidamente, isto pode afetar a aparência e a segurança.
O Standard DES-based crypt() retorna o salt como o primeiro two characters da saída. Ele também usa apenas os oito primeiros caracteres da str, então strings longas que começam com os mesmos oito caracteres gerarão o mesmo resultado (quando o mesmo salt é usado).
Em sistemas onde a função crypt() suporta variados tipos de codificação, as seguintes funções são definidas para 0 ou 1 a depender se um dado tipo está disponível:
CRYPT_STD_DES - Codificação Standard DES-based com um salt de 2 caracteres
CRYPT_EXT_DES - Codificação Extended DES-based com um salt de 9 caracateres
CRYPT_MD5 - Codificação MD5 com um salt de 12 caracteres começando com $1$
CRYPT_BLOWFISH - Codificação Blowfish com um salt de 16 caracteres começando com $2$
Nota: Não há função de decodificação, desde que crypt() utiliza uma algorimo de um só caminho.
Exemplo 1. crypt() exemplos
|
Veja também md5() e the Mcrypt extension.
Exibe todos os parãmetros.
echo() não é uma função atualmente (construtor da linguagem) então não é obrigatório usar parênteses. De fato, se você quer passar mais do que um parâmetro para echo, você não deve fechar os parênteses dentro de parênteses. Não é possível usar echo() num contexto de variable function, mas você pode usar print() no lugar dela.
Exemplo 1. echo() exemplos
|
echo() também tem uma sintaxe curta, onde você pode seguir imediatamente a tag de abertura com um sinal de igual.
Nota: Está sintaxe curta apenas trabalha se a configuração short_open_tag está habilitada.
Retorna uma matriz de strings, cada uma como substring de string formada pela divisão dela a partir de fronteiras presentes nela separator. Se limit está definido, a matriz retornada conterá o máximo de limit elementos com o último elemento contendo o resto da string.
Se separator está como uma string vazia (""), explode() retornará FALSE. Se separator contém um valor que não está contido em string, então explode() retornará uma matriz contendo a string.
Nota: O parâmetro limit foi adicionado no PHP 4.0.1
Nota: Ainda que implode() pode por razões históricas aceitar seus parâmetros em uma das duas ordens, explode() não pode. Você deve assegurar que o argumento separator vem antes do argumento string.
Veja também preg_split(), spliti(), split(), e implode().
Write a string produced according to the formatting string format to the stream resource specified by handle..
The format string is composed of zero or more directives: ordinary characters (excluding %) that are copied directly to the result, and conversion specifications, each of which results in fetching its own parameter. This applies to fprintf(), sprintf(), and printf().
Each conversion specification consists of a percent sign (%), followed by one or more of these elements, in order:
An optional padding specifier that says what character will be used for padding the results to the right string size. This may be a space character or a 0 (zero character). The default is to pad with spaces. An alternate padding character can be specified by prefixing it with a single quote ('). See the examples below.
An optional alignment specifier that says if the result should be left-justified or right-justified. The default is right-justified; a - character here will make it left-justified.
An optional number, a width specifier that says how many characters (minimum) this conversion should result in.
An optional precision specifier that says how many decimal digits should be displayed for floating-point numbers. This option has no effect for other types than float. (Another function useful for formatting numbers is number_format().)
A type specifier that says what type the argument data should be treated as. Possible types:
% - a literal percent character. No argument is required. |
b - the argument is treated as an integer, and presented as a binary number. |
c - the argument is treated as an integer, and presented as the character with that ASCII value. |
d - the argument is treated as an integer, and presented as a (signed) decimal number. |
u - the argument is treated as an integer, and presented as an unsigned decimal number. |
f - the argument is treated as a float, and presented as a floating-point number. |
o - the argument is treated as an integer, and presented as an octal number. |
s - the argument is treated as and presented as a string. |
x - the argument is treated as an integer and presented as a hexadecimal number (with lowercase letters). |
X - the argument is treated as an integer and presented as a hexadecimal number (with uppercase letters). |
See also: printf(), sprintf(), sscanf(), fscanf(), vsprintf(), and number_format().
Exemplo 1. sprintf(): zero-padded integers
|
Exemplo 2. sprintf(): formatting currency
|
(PHP 4 )
get_html_translation_table -- Retorna a tabela de traduçaõ usada por htmlspecialchars() e htmlentities()get_html_translation_table() retornará a tabela de tradução que é usada internamente por htmlspecialchars() e htmlentities(). Há duas novas definidas (HTML_ENTITIES, HTML_SPECIALCHARS) que permite especificar a tabela que você quer. E como nas funções htmlspecialchars() e htmlentities()você pode opcionalmente especificar a quote_style que você está trabalhando. O padrão é modo ENT_COMPAT. Veja a descrição desses modos em htmlspecialchars().
Legal é usar array_flip() para mudar a direção da tradução.
O conteúdo de $original seria: "Hallo & <Frau> & Krämer".Veja também htmlspecialchars(), htmlentities(), strtr(), e array_flip().
O parâmetro opcional max_chars_per_line indica o número máximo de caracteres por linha que será exibido. A função tenta evitar palavras quebradas.
Veja também hebrevc()
(PHP 3, PHP 4 )
hebrevc -- Converte um texto lógico Hebráico para um texto visual com conversão newlineÉ similar a hebrev() a diferença é que ela converte newlines (\n) para "<br>\n". O parâmetro opcional max_chars_per_line indica o número máximo de caracteres por linha que será exibido. A função evita quebrar palavras.
Veja também hebrev()
html_entity_decode() é o oposto da função htmlentities() no que converte todas as entidades HTML para os seus caracteres de string.
O segundo parâmetro, que é opcional, quote_style permite você definir o que será feito com 'apostrofos' e "aspas". Ele recebe uma constante entre três, sendo o padrão ENT_COMPAT:
Tabela 1. Constantes disponíveis para quote_style
Nome da Constante | Descrição |
---|---|
ENT_COMPAT | Irá converter aspas e deixar os apostrofos. |
ENT_QUOTES | Irá converter ambos. |
ENT_NOQUOTES | Irá deixar ambos sem converter. |
O conjunto de caracteres ISO-8859-1 é usado como padrão para o terceiro parâmetro, que é opcional, charset. Este defini o conjunto de caracteres usado na conversão.
Exemplo 1. Decodificando entidades html
|
Veja também htmlentities(), htmlspecialchars(), get_html_translation_table(), htmlspecialchars() e urldecode().
Esta função é idêntica a htmlspecialchars() em tudo, exceto que todos os caracteres que tem caracteres HTML equivalentes são são traduzidos nesta realidade. Como htmlspecialchars(), ele leva um segundo argumento opcional que indica o que seria feito com aspas simples e dupla. ENT_COMPAT (padrão) apenas converterá aspas duplas e deixará aspas-simples sozinha. ENT_QUOTES será convertido ambas aspas simples e dupla, e ENT_NOQUOTES deixará ambas desconvertidas.
No presente momento, o conjunto de caracteres ISO-8859-1 é usado como padrão. Suporte para o segundo argumento opcional foi adicionado no PHP 3.0.17 e PHP 4.0.3.
Como htmlspecialchars(),ele leva um terceiro argumento opcional que define o conjunto de caracteres usados na conversão. Suporte para esse argumento foi adicionado no PHP 4.1.0.
Não há o oposto desta função. Entretanto, você pode criar uma você próprio. Aqui está um exemplo de como fazer isso.
Veja também htmlspecialchars() e nl2br().
Certos caracteres tem significado especial em HTML, e seriam representados pela realidade HTML se eles estão preservanado seus significados. Esta função retorna uma string com algumas destas conversões feitas; As transformações feitas são aquelas mais úteis para programação web. Se você precisa que sejam transformados todos os caracteres da realidade HTML, use htmlentities() no lugar dela.
Esta função é útil na prevenção de textos fornecidos pelo usuário contendo marcação HTML, tal como um quadro de mensgens ou guest book. O segundo argumento opcional, quote_style, conta à função o que fazer com os caracteres aspas simples e dupla. O modo padrão, ENT_COMPAT, é o modo mais compatível com a atualidade, apenas transforma a aspas-dupla e deixa a aspas-simples como está. Se ENT_QUOTES está definida, ambas transformadas e se ENT_NOQUOTES está definida nenhuma das duas são modificadas.
As traduções executadas são:
'&' (ampersand) torna-se '&'
'"' (aspas dupla) torna-se '"' quando ENT_NOQUOTES não está definida.
''' (aspas simples) torna-se ''' apenas quando ENT_QUOTES está definida.
'<' (menor que) torna-se '<'
'>' (maior que) torna-se '>'
Note que esta função não converte nada além do que foi listado acima. Para completa realidade de conversões, veja htmlentities(). Suporte para o segundo argumento opcional foi adicionado no PHP 3.0.17 e PHP 4.0.3.
O terceiro argumento define o conjunto de caracteres usados na conversão. O conjunto de caracteres padrão é ISO-8859-1. Suporte para o terceiro argumento foi adicionado no PHP 4.1.0.
Veja também htmlentities() e nl2br().
Retorna uma string contendo os elementos da matriz na mesma ordem com uma ligação entre cada elemento.
Nota: implode() pode, por razões históricas, aceitar seus parâmetros nas duas ordens. Para consistência com explode(), entretando, ela pode ser menos confusa por usar a ordem documentada dos argumentos.
join() é um alias para implode(), e é indêntica em tudo.
Retorna a Levenshtein-Distance entre duas strings argumentos ou -1, se nenhuma das strings argumentos é mais longa que o o limite de 255 caracteres (255 seria mais do que o bastante para o nome ou comparação de dicionário, e ninguém sério estaria fazendo análises genéticas com PHP).
A distância Levenshtein é definida como o número mínimo de caracteres que você tem para substituir, inserir ou apagar para transformar str1 dentro de str2. A complexidade do algoritmo é O(m*n), onde n e m são o comprimento da str1 e str2 (rather good when compared to similar_text(), which is O(max(n,m)**3), but still expensive).
Na sua forma mais simples a função pegará apenas as duas strings como parâmetros e calculará apenas o número de operações de inserção, substituição e deletação necessárias para transformar str1 em str2.
Uma segunda variante pegará três parâmetros adicionais que definem o custo das operações de inserção, substituição e deletação. Esta é a mais geral e adapatável do que a variante um, mas não tão eficiente.
A terceira variante (que ainda não é implementada) será a mais geral e adaptável, mas também a alternativa mais lenta. Ela chamará uma função de usuário fornecida que determinará o custo para cada possível operação.
A função de usuário fornecida(The user-supplied function) será chamada com os seguintes argumentos:
operation to apply: 'I', 'R' ou 'D'
actual character in string 1
actual character in string 2
position in string 1
position in string 2
remaining characters in string 1
remaining characters in string 2
The user-supplied function approach offers the possibility to take into account the relevance of and/or difference between certain symbols (characters) or even the context those symbols appear in to determine the cost of insert, replace and delete operations, but at the cost of losing all optimizations done regarding cpu register utilization and cache misses that have been worked into the other two variants.
Veja também soundex(), similar_text(), e metaphone().
Retorna uma matriz associativa contendo numérico localizado e informação de formatação monetária.
localeconv() retorna dados baseados na localidade corrente definida por setlocale(). A matriz associativa que é retornada contém os seguintes campos:
Array element | Descrição | ||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
decimal_point | Caracter de ponto decimal | ||||||||||
thousands_sep | Thousands separator | ||||||||||
grouping | Matriz contendo agrupamentos numéricos | ||||||||||
int_curr_symbol | International currency symbol (i.e. USD) | ||||||||||
currency_symbol | Simbolo da moeda local symbol (i.e. $) | ||||||||||
mon_decimal_point | Caractere monetário de ponto decimal | ||||||||||
mon_thousands_sep | Separador monetário de mil | ||||||||||
mon_grouping | Matriz contendo agrupamentos monetários | ||||||||||
positive_sign | Sinal para valores positivos | ||||||||||
negative_sign | Sinal para valores negativos | ||||||||||
int_frac_digits | Dígitos de fração Internacionais | ||||||||||
frac_digits | Dígitos de fração locais | ||||||||||
p_cs_precedes | TRUE Se o simbolo da moeda precede um valor positivo, FALSE se eles sucede um. | ||||||||||
p_sep_by_space | TRUE Se um espaço separa o simbolo da moeda de um valor positivo, FALSE caso contrário | ||||||||||
n_cs_precedes | TRUE Se o simbolo de moeda precede um valor negativo, FALSE se ele sucede | ||||||||||
n_sep_by_space | TRUE se um espaço separa o simbolo da moeda de um valor negativo, FALSE caso contrário | ||||||||||
p_sign_posn |
| ||||||||||
n_sign_posn |
|
Os campos de agrupamento contém matrizes que definem o modo de como os números seriam agrupados. Por exemplo, o campo de agrupamento para a localidade en_US, conteria uma matriz de 2 itens com os valores 3 e 3. O mais alto índice na matriz, mais distante da esquerda do agrupamento está. Se um elemento da matriz é igual a CHAR_MAX, até aqui nenhum agrupamento é feito. Se um elemento de matriz é igual a 0, o prévio elemento seria usado.
Exemplo 1. localeconv() exemplo
|
A constante CHAR_MAX também está definida para o uso mencionado acima.
Veja também setlocale().
Nota: O segundo parâmetro foi adicionado no PHP 4.1.0
Esta função retorna uma string com whitespace retirados do início de str. Sem o segundo parâmetro, ltrim() retirará estes caracters:
" " (ASCII 32 (0x20)), um espaço normal.
"\t" (ASCII 9 (0x09)), uma tabela.
"\n" (ASCII 10 (0x0A)), a new line (line feed).
"\r" (ASCII 13 (0x0D)), a carriage return.
"\0" (ASCII 0 (0x00)), O NUL-byte.
"\x0B" (ASCII 11 (0x0B)), uma tabela vertical.
Você pode também especificar os caracteres que você quer retirar, por meio do parâmetro charlist. Simplesmente lista todos os caracteres que você quer que sejam retirados. Com .. você pode especificar um ordem de caracteres.
Exemplo 1. Exemplo do uso de ltrim()
|
Calcula o hash MD5 de um filename especificado usando o RSA Data Security, Inc. MD5 Message-Digest Algorithm, e retorna esse hash.
Esta função tem o mesmo propósito da linha de comando md5sum.
Calcula o hash MD5 de str usando o RSA Data Security, Inc. MD5 Message-Digest Algorithm, e retorna esse hash. O hash é um número hexadecimal caracter-32.
Veja também crc32() e md5_file()
Calcula a metaphone key de str.
Similar a soundex() metaphone cria a mesma key para palavras sonoras similares. Ela é mais precisa do que soundex() por ela conhecer as regras básicas da pronunciação inglesa. As metaphone keys geradas são de comprimentos variados.
Metaphone foi desenvolvido por Lawrence Philips <lphilips@verity.com>. Ela é descrita em ["Practical Algorithms for Programmers", Binstock & Rex, Addison Wesley, 1995].
money_format() returns a formatted version of number. This function wraps the C library function strfmon(), with the difference that this implementation converts only one number at a time.
The format specification consists of the following sequence:
a % character
optional flags
optional field width
optional left precision
optional right precision
a required conversion character
Flags. One or more of the optional flags below can be used:
The character = followed by a a (single byte) character f to be used as the numeric fill character. The default fill character is space.
Disable the use of grouping characters (as defined by the current locale).
Specify the formatting style for positive and negative numbers. If + is used, the locale's equivalent for + and - will be used. If ( is used, negative amounts are enclosed in parenthesis. If no specification is given, the default is +.
Suppress the currency symbol from the output string.
If present, it will make all fields left-justified (padded to the right), as opposed to the default which is for the fields to be right-justified (padded to the left).
Field width.
A decimal digit string specifying a minimum field width. Field will be right-justified unless the flag - is used. Default value is 0 (zero).
Left precision.
The maximum number of digits (n) expected to the left of the decimal character (e.g. the decimal point). It is used usually to keep formatted output aligned in the same columns, using the fill character if the number of digits is less than n. If the number of actual digits is bigger than n, then this specification is ignored.
If grouping has not been suppressed using the ^ flag, grouping separators will be inserted before the fill characters (if any) are added. Grouping separators will not be applied to fill characters, even if the fill character is a digit.
To ensure alignment, any characters appearing before or after the number in the formatted output such as currency or sign symbols are padded as necessary with space characters to make their positive and negative formats an equal length.
Right precision .
A period followed by the number of digits (p) after the decimal character. If the value of p is 0 (zero), the decimal character and the digits to its right will be omitted. If no right precision is included, the default will dictated by the current local in use. The amount being formatted is rounded to the specified number of digits prior to formatting.
Conversion characters .
The number is formatted according to the locale's international currency format (e.g. for the USA locale: USD 1,234.56).
The number is formatted according to the locale's national currency format (e.g. for the de_DE locale: DM1.234,56).
Returns the the % character.
Nota: The LC_MONETARY category of the locale settings, affects the behavior of this function. Use setlocale() to set to the appropriate default locale before using this function.
Characters before and after the formatting string will be returned unchanged.
Exemplo 1. money_format() Example We will use different locales and format specifications to illustrate the use of this function.
|
See also: setlocale(), number_format(),sprintf(), printf() and sscanf().
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Retorna string com '<br />' inserido antes de todas as newlines.
Nota: Começa no PHP 4.0.5, nl2br() está agora em XHTML complacente. Todas as versões anteriores a 4.0.5 retornarão string com '<br>' inserido antes das newlines ao invés de '<br />'.
Veja também htmlspecialchars(), htmlentities() e wordwrap().
number_format() retorna uma versão formatada de number. Esta função aceita um, dois ou quatro parâmetros (não três):
Se apenas um parâmetro é dado, number será formatado sem decimais, mas com uma virgula (",") entre cada grupo de milhar.
Se dois parâmetros são dados, number será formatado com o número de casas decimais especificadas em decimals com um ponto (".") na frente, e uma vírgula (",") entre cada grupo de milhar.
Se todos os quatro parâmetros forem dados, number será formatado com o número de casas decimais em decimals, dec_point ao invés do ponto (".") antes das casas decimais e thousands_sep ao invés de uma vírgula (",") entre os grupos de milhares.
Nota: Somente o primeiro caractere de thousands_sep é usado. Por exemplo, se você usar foo como o parâmetro thousands_sep no número 1000, number_format() irá retornar 1f000.
Exemplo 1. Exemplo number_format() Por exemplo, a notação Francesa usa duas casas decimais, vírgula (',') como separador decimal, e espaço (' ') como separador de milhar. Isto é feito com a linha :
|
Retorna o valor ASCII do primeiro caractere de string. Esta função complementa chr().
Você pode achar a tabela ASCII aqui: http://www.asciitable.com/.
Veja também chr().
Converte str como se ela tivesse sido passada via URL e define o valor das variáveis. Se o segundo parâmetro arr estiver presente, as variáveis são colocadas nesta variável como uma matriz de elementos.
Nota: Suporte para o segundo parâmetro, que é opcional, foi adicionado no PHP 4.0.3.
Nota: Para pegar a QUERY_STRING atual, você deve usar a variável $_SERVER['QUERY_STRING']. também você deve querer ler a seção sobre variáveis de fora do PHP.
Veja também parse_url(), pathinfo(), set_magic_quotes_runtime(), e urldecode().
Mostra arg. Retorna TRUE em caso de sucesso ou FALSE em falhas.
print() não é atualmente uma função real (é uma construção da linguagem) então você não precisa usar parêntesis com ela.
Exemplo 1. Exemplos print()
|
Produz uma saída de acordo com format, o qual é descrito na documentação para sprintf().
Veja também print(), sprintf(), sscanf(), fscanf(), e flush().
(PHP 3>= 3.0.6, PHP 4 )
quoted_printable_decode -- Converte uma string quoted-printable para uma string de 8 bitEsta função retorna uma string de 8-bit correspondendo a string quoted-printable decodificada. Esta função é similar a imap_qprint(), com a exceção de não requerer o módulo IMAP para funcionar.
Retorna uma versão de str com uma barra invertida (\) entes de cada um destes caracteres:
. \\ + * ? [ ^ ] ( $ ) |
Veja também addslashes(), htmlentities(), htmlspecialchars(), nl2br(), and stripslashes().
Nota: O Segundo parâmetro foi adicionado no PHP 4.1.0
Esta função retorna a string como os espaços em branco retirados do final de str. Sem o segundo parâmetro, rtrim() irá retirar os seguintes caracteres:
" " (ASCII 32 (0x20)), um espaço comum.
"\t" (ASCII 9 (0x09)), uma tabulação.
"\n" (ASCII 10 (0x0A)), uma nova linha.
"\r" (ASCII 13 (0x0D)), um retorno de carro(ENTER).
"\0" (ASCII 0 (0x00)), o byte NULL.
"\x0B" (ASCII 11 (0x0B)), uma tabulação vertical.
Você também pode especificar os caracteres que você deseja retirar, pelo parâmetro charlist. Simplesmente liste todos os caracteres que você quer ver retirados. Com .. você pode especificar um intervalo de caracteres.
Exemplo 1. Exemplo de uso da função rtrim()
|
Category is a named constant (or string) specifying the category of the functions affected by the locale setting:
LC_ALL for all of the below
LC_COLLATE for string comparison, see strcoll()
LC_CTYPE for character classification and conversion, for example strtoupper()
LC_MONETARY for localeconv()
LC_NUMERIC for decimal separator (See also localeconv())
LC_TIME for date and time formatting with strftime()
If locale is the empty string "", the locale names will be set from the values of environment variables with the same names as the above categories, or from "LANG".
If locale is zero or "0", the locale setting is not affected, only the current setting is returned.
If locale is an array or followed by additional parameters then each array element or parameter is tried to be set as new locale until success. This is usefull if a locale is known under different names on different systems or for providing a fallback for a possibly not available locale.
Nota: Passing multiple locales is not available before PHP 4.3.0
Setlocale returns the new current locale, or FALSE if the locale functionality is not implemented in the platform, the specified locale does not exist or the category name is invalid. An invalid category name also causes a warning message.
Nota: The return value of setlocale() depends on the system that PHP is running. It returns exactly what the system setlocale function returns.
Exemplo 1. setlocale() Examples
|
Calcula a hash sha1 de nomedoarquivo usando US Secure Hash Algorithm 1, e retorna esta hash. A hash é um número hexadecimal de 40 caracteres. Em caso de falha é retornado FALSE.
Veja também sha1(), crc32(), e md5_file()
Calcula a hash sha1 de str usando US Secure Hash Algorithm 1, e retorna esta hash. A hash é um número hexadecimal de 40 caracteres.
Veja também sha1_file(), crc32(), e md5()
This calculates the similarity between two strings as described in Oliver [1993]. Note that this implementation does not use a stack as in Oliver's pseudo code, but recursive calls which may or may not speed up the whole process. Note also that the complexity of this algorithm is O(N**3) where N is the length of the longest string.
By passing a reference as third argument, similar_text() will calculate the similarity in percent for you. It returns the number of matching chars in both strings.
Calculates the soundex key of str.
Soundex keys have the property that words pronounced similarly produce the same soundex key, and can thus be used to simplify searches in databases where you know the pronunciation but not the spelling. This soundex function returns a string 4 characters long, starting with a letter.
This particular soundex function is one described by Donald Knuth in "The Art Of Computer Programming, vol. 3: Sorting And Searching", Addison-Wesley (1973), pp. 391-392.
Exemplo 1. Soundex Examples
|
See also levenshtein(), metaphone(), and similar_text().
Returns a string produced according to the formatting string format.
The format string is composed of zero or more directives: ordinary characters (excluding %) that are copied directly to the result, and conversion specifications, each of which results in fetching its own parameter. This applies to both sprintf() and printf().
Each conversion specification consists of a percent sign (%), followed by one or more of these elements, in order:
An optional padding specifier that says what character will be used for padding the results to the right string size. This may be a space character or a 0 (zero character). The default is to pad with spaces. An alternate padding character can be specified by prefixing it with a single quote ('). See the examples below.
An optional alignment specifier that says if the result should be left-justified or right-justified. The default is right-justified; a - character here will make it left-justified.
An optional number, a width specifier that says how many characters (minimum) this conversion should result in.
An optional precision specifier that says how many decimal digits should be displayed for floating-point numbers. This option has no effect for other types than float. (Another function useful for formatting numbers is number_format().)
A type specifier that says what type the argument data should be treated as. Possible types:
% - a literal percent character. No argument is required. |
b - the argument is treated as an integer, and presented as a binary number. |
c - the argument is treated as an integer, and presented as the character with that ASCII value. |
d - the argument is treated as an integer, and presented as a (signed) decimal number. |
u - the argument is treated as an integer, and presented as an unsigned decimal number. |
f - the argument is treated as a float, and presented as a floating-point number. |
o - the argument is treated as an integer, and presented as an octal number. |
s - the argument is treated as and presented as a string. |
x - the argument is treated as an integer and presented as a hexadecimal number (with lowercase letters). |
X - the argument is treated as an integer and presented as a hexadecimal number (with uppercase letters). |
As of PHP version 4.0.6 the format string supports argument numbering/swapping. Here is an example:
See also printf(), sscanf(), fscanf(), vsprintf(), and number_format().
The function sscanf() is the input analog of printf(). sscanf() reads from the string str and interprets it according to the specified format. If only two parameters were passed to this function, the values parsed will be returned as an array.
Any whitespace in the format string matches any whitespace in the input string. This means that even a tab \t in the format string can match a single space character in the input string.
This functions returns the input string padded on the left, the right, or both sides to the specified padding length. If the optional argument pad_string is not supplied, the input is padded with spaces, otherwise it is padded with characters from pad_string up to the limit.
Optional argument pad_type can be STR_PAD_RIGHT, STR_PAD_LEFT, or STR_PAD_BOTH. If pad_type is not specified it is assumed to be STR_PAD_RIGHT.
If the value of pad_length is negative or less than the length of the input string, no padding takes place.
Returns input_str repeated multiplier times. multiplier has to be greater than or equal to 0. If the multiplier is set to 0, the function will return an empty string.
This will output "-=-=-=-=-=-=-=-=-=-=".
See also for, str_pad(), and substr_count().
(PHP 3>= 3.0.6, PHP 4 )
str_replace -- Replace all occurrences of the search string with the replacement stringThis function returns a string or an array with all occurences of search in subject replaced with the given replace value. If you don't need fancy replacing rules, you should always use this function instead of ereg_replace() or preg_replace().
In PHP 4.0.5 and later, every parameter to str_replace() can be an array.
If subject is an array, then the search and replace is performed with every entry of subject, and the return value is an array as well.
If search and replace are arrays, then str_replace() takes a value from each array and uses them to do search and replace on subject. If replace has fewer values than search, then an empty string is used for the rest of replacement values. If search is an array and replace is a string; then this replacement string is used for every value of search.
This function is binary safe.
Nota: str_replace() was added in PHP 3.0.6, but was buggy up until PHP 3.0.8.
See also ereg_replace(), preg_replace(), and strtr().
This function performs the ROT13 encoding on the str argument and returns the resulting string. The ROT13 encoding simply shifts every letter by 13 places in the alphabet while leaving non-alpha characters untouched. Encoding and decoding are done by the same function, passing an encoded string as argument will return the original version.
str_shuffle() shuffles a string. One permutation of all possible is created.
Counts the number of words inside string. If the optional format is not specified, then the return value will be an integer representing the number of words found. In the event the format is specified, the return value will be an array, content of which is dependent on the format. The possible value for the format and the resultant outputs are listed below.
1 - returns an array containing all the words found inside the string.
2 - returns an associative array, where the key is the numeric position of the word inside the string and the value is the actual word itself.
For the purpose of this function, 'word' is defined as a locale dependent string containing alphabetic characters, which also may contain, but not start with "'" and "-" characters.
Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.
See also ereg(), strcmp(), substr(), stristr(), strncasecmp(), and strstr().
Esta função é um apelido para strstr(), e é idêndica de todos os meios.
Retorna < 0 se str1 é menor do que str2; > 0 se str1 é maior do que str2, e 0 se forem iguais.
Note que esta função diferencia maiúsculas e minúsculas.
Veja também ereg(), strcasecmp(), substr(), stristr(), strncasecmp(), strncmp(), e strstr().
Retorna < 0 se str1 é menor do que str2; > 0 se str1 é maior do que str2, e 0 se forem iguais. strcoll() usa o local atual para fazer as comparações. Se o local atual for C ou POSIX, esta função é equivalente à strcmp().
Note que esta função diferencia maiúsculas e minúsculas, e diferentemente de strcmp() esta função não é segura para binário.
Nota: strcoll() foi adicionada no PHP 4.0.5, mas não foi ativada para o win32 até 4.2.3.
Veja também ereg(), strcmp(), strcasecmp(), substr(), stristr(), strncasecmp(), strncmp(), strstr(), e setlocale().
Retorna o tamanho do segmento inicial de str1 que não contém nenhum dos caracteres em str2.
Veja também strspn().
Esta função tenta retornar uma string retirando todas as tags HTML e PHP de str. Ele erra no lado de ter cuidado no caso de tags com problemas ou incompletas. Usa o mesmo sistema para retirar as tags do que fgetss().
Você pode utilizar o segundo parâmetro, que é opcional, para indicar tags que não devam ser retiradas.
Nota: allowable_tags foi adicionado em PHP 3.0.13 e PHP 4.0b3.
Atenção |
Esta função não modifica nenhum dos atributos das tags que você permitiu usando allowable_tags, incluindo os atributos style e onmouseover que um usuário travesso pode abusar quando colocar texto a ser mostrado para os outros usuários. |
Retorna uma string com as barras invertidas retiradas. Reconhece estilo C \n, \r ..., representação octal e hexadecimal.
Veja também addcslashes().
Retorna uma string com as barras invertidas retiradas. (\' se torna ' e assim por diante.) Barras invertidas duplas se tornam barras invertidas simples.
Veja também addslashes().
Returns all of haystack from the first occurrence of needle to the end. needle and haystack are examined in a case-insensitive manner.
If needle is not found, returns FALSE.
If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.
This function implements a comparison algorithm that orders alphanumeric strings in the way a human being would. The behaviour of this function is similar to strnatcmp(), except that the comparison is not case sensitive. For more infomation see: Martin Pool's Natural Order String Comparison page.
Similar to other string comparison functions, this one returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.
See also ereg(), strcasecmp(), substr(), stristr(), strcmp(), strncmp(), strncasecmp(), strnatcmp(), and strstr().
This function implements a comparison algorithm that orders alphanumeric strings in the way a human being would, this is described as a "natural ordering". An example of the difference between this algorithm and the regular computer string sorting algorithms (used in strcmp()) can be seen below:
$arr1 = $arr2 = array("img12.png","img10.png","img2.png","img1.png"); echo "Standard string comparison\n"; usort($arr1,"strcmp"); print_r($arr1); echo "\nNatural order string comparison\n"; usort($arr2,"strnatcmp"); print_r($arr2); |
Standard string comparison Array ( [0] => img1.png [1] => img10.png [2] => img12.png [3] => img2.png ) Natural order string comparison Array ( [0] => img1.png [1] => img2.png [2] => img10.png [3] => img12.png ) |
Similar to other string comparison functions, this one returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.
Note that this comparison is case sensitive.
See also ereg(), strcasecmp(), substr(), stristr(), strcmp(), strncmp(), strncasecmp(), strnatcasecmp(), strstr(), natsort() and natcasesort().
(PHP 4 >= 4.0.2)
strncasecmp -- Binary safe case-insensitive string comparison of the first n charactersThis function is similar to strcasecmp(), with the difference that you can specify the (upper limit of the) number of characters (len) from each string to be used in the comparison. If any of the strings is shorter than len, then the length of that string will be used for the comparison.
Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.
See also ereg(), strcasecmp(), strcmp(), substr(), stristr(), and strstr().
This function is similar to strcmp(), with the difference that you can specify the (upper limit of the) number of characters (len) from each string to be used in the comparison. If any of the strings is shorter than len, then the length of that string will be used for the comparison.
Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.
Note that this comparison is case sensitive.
See also ereg(), strncasecmp(), strcasecmp(), substr(), stristr(), strcmp(), and strstr().
Returns the numeric position of the first occurrence of needle in the haystack string. Unlike the strrpos(), this function can take a full string as the needle parameter and the entire string will be used.
If needle is not found, returns FALSE.
Nota: It is easy to mistake the return values for "character found at position 0" and "character not found". Here's how to detect the difference:
If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.
The optional offset parameter allows you to specify which character in haystack to start searching. The position returned is still relative to the the beginning of haystack.
See also strrpos(), strrchr(), substr(), stristr(), and strstr().
This function returns the portion of haystack which starts at the last occurrence of needle and goes until the end of haystack.
Returns FALSE if needle is not found.
If needle contains more than one character, the first is used.
If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.
Returns the numeric position of the last occurrence of needle in the haystack string. Note that the needle in this case can only be a single character. If a string is passed as the needle, then only the first character of that string will be used.
If needle is not found, returns FALSE.
Nota: It is easy to mistake the return values for "character found at position 0" and "character not found". Here's how to detect the difference:
If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.
See also strpos(), strrchr(), substr(), stristr(), and strstr().
Returns the length of the initial segment of str1 which consists entirely of characters in str2.
The line of code:
will assign 2 to $var, because the string "42" will be the longest segment containing characters from "1234567890".See also strcspn().
Returns part of haystack string from the first occurrence of needle to the end of haystack.
If needle is not found, returns FALSE.
If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.
Nota: This function is case-sensitive. For case-insensitive searches, use stristr().
Nota: If you only want to determine if a particular needle occurs within haystack, use the faster and less memory intensive function strpos() instead.
See also ereg(), preg_match(), strchr(), stristr(), strpos(), strrchr(), and substr().
strtok() splits a string (arg1) into smaller strings (tokens), with each token being delimited by any character from arg2. That is, if you have a string like "This is an example string" you could tokenize this string into its individual words by using the space character as the token.
Note that only the first call to strtok uses the string argument. Every subsequent call to strtok only needs the token to use, as it keeps track of where it is in the current string. To start over, or to tokenize a new string you simply call strtok with the string argument again to initialize it. Note that you may put multiple tokens in the token parameter. The string will be tokenized when any one of the characters in the argument are found.
The behavior when an empty part was found changed with PHP 4.1.0. The old behavior returned an empty string, while the new, correct, behavior simply skips the part of the string:
Also be careful that your tokens may be equal to "0". This evaluates to FALSE in conditional expressions.
Returns string with all alphabetic characters converted to lowercase.
Note that 'alphabetic' is determined by the current locale. This means that in i.e. the default "C" locale, characters such as umlaut-A (Ä) will not be converted.
See also strtoupper(), ucfirst(), and ucwords().
Returns string with all alphabetic characters converted to uppercase.
Note that 'alphabetic' is determined by the current locale. For instance, in the default "C" locale characters such as umlaut-a (ä) will not be converted.
See also strtolower(), ucfirst(), and ucwords().
This function returns a copy of str, translating all occurrences of each character in from to the corresponding character in to and returning the result.
If from and to are different lengths, the extra characters in the longer of the two are ignored.
strtr() can be called with only two arguments. If called with two arguments it behaves in a new way: from then has to be an array that contains string -> string pairs that will be replaced in the source string. strtr() will always look for the longest possible match first and will *NOT* try to replace stuff that it has already worked on.
Examples:
$trans = array("hello" => "hi", "hi" => "hello"); echo strtr("hi all, I said hello", $trans) . "\n"; |
Nota: This optional to and from parameters were added in PHP 4.0.0
See also ereg_replace().
substr_count() returns the number of times the needle substring occurs in the haystack string.
See also count_chars(), strpos(), substr(), and strstr().
substr_replace() replaces a copy of string delimited by the start and (optionally) length parameters with the string given in replacement. The result is returned.
If start is positive, the replacing will begin at the start'th offset into string.
If start is negative, the replacing will begin at the start'th character from the end of string.
If length is given and is positive, it represents the length of the portion of string which is to be replaced. If it is negative, it represents the number of characters from the end of string at which to stop replacing. If it is not given, then it will default to strlen( string ); i.e. end the replacing at the end of string.
Exemplo 1. substr_replace() example
|
See also str_replace() and substr().
substr() returns the portion of string specified by the start and length parameters.
If start is non-negative, the returned string will start at the start'th position in string, counting from zero. For instance, in the string 'abcdef', the character at position 0 is 'a', the character at position 2 is 'c', and so forth.
Exemplo 1. Basic substr() usage
|
If start is negative, the returned string will start at the start'th character from the end of string.
If length is given and is positive, the string returned will contain at most length characters beginning from start (depending on the length of string). If string is less than start characters long, FALSE will be returned.
If length is given and is negative, then that many characters will be omitted from the end of string (after the start position has been calculated when a start is negative). If start denotes a position beyond this truncation, an empty string will be returned.
Nota: The optional charlist parameter was added in PHP 4.1.0
This function returns a string with whitespace stripped from the beginning and end of str. Without the second parameter, trim() will strip these characters:
" " (ASCII 32 (0x20)), an ordinary space.
"\t" (ASCII 9 (0x09)), a tab.
"\n" (ASCII 10 (0x0A)), a new line (line feed).
"\r" (ASCII 13 (0x0D)), a carriage return.
"\0" (ASCII 0 (0x00)), the NUL-byte.
"\x0B" (ASCII 11 (0x0B)), a vertical tab.
You can also specify the characters you want to strip, by means of the charlist parameter. Simply list all characters that you want to be stripped. With .. you can specify a range of characters.
Exemplo 1. Usage example of trim()
|
Returns a string with the first character of str capitalized, if that character is alphabetic.
Note that 'alphabetic' is determined by the current locale. For instance, in the default "C" locale characters such as umlaut-a (ä) will not be converted.
See also strtolower(), strtoupper(), and ucwords().
Returns a string with the first character of each word in str capitalized, if that character is alphabetic.
Nota: The definition of a word is any string of characters that is immediately after a whitespace (These are: space, form-feed, newline, carriage return, horizontal tab, and vertical tab).
See also strtoupper(), strtolower() and ucfirst().
Display array values as a formatted string according to format (which is described in the documentation for sprintf()).
Operates as printf() but accepts an array of arguments, rather than a variable number of arguments.
See also printf(), sprintf(), vsprintf()
Return array values as a formatted string according to format (which is described in the documentation for sprintf()).
Operates as sprintf() but accepts an array of arguments, rather than a variable number of arguments.
(PHP 4 >= 4.0.2)
wordwrap -- Wraps a string to a given number of characters using a string break character.Returns a string with str wrapped at the column number specified by the (optional) width parameter. The line is broken using the (optional) break parameter.
wordwrap() will automatically wrap at column 75 and break using '\n' (newline) if width or break are not given.
If the cut is set to 1, the string is always wrapped at the specified width. So if you have a word that is larger than the given width, it is broken apart. (See second example).
Nota: The optional cut parameter was added in PHP 4.0.3
This example would display:
This example would display:
See also nl2br().
(PHP 3>= 3.0.6, PHP 4 )
sybase_affected_rows -- informa o número de linhas afetadas pela última consultaRetorna: o número de linhas afetadas pela última consulta.
sybase_affected_rows() retorna o número de linhas afetadas pelo último INSERT, UPDATE ou DELETE no servidor associado com o identificador de recurso especificado. Se o identificador de recurso não for especificado a última conexão aberta é utilizada.
Este comando não tem efeito em consultas SELECT; apenas em consultas que modificam registros. Para recuperar o número de linhas retornadas por um SELECT, utilize sybase_num_rows().
Nota: Esta funcão está disponível apenas utilizando-se a biblioteca de interface CT para o Sybase e não disponível para a biblioteca DB.
Retorna: TRUE em caso de sucesso, FALSE em caso de falha
sybase_close() fecha a conexão com um banco de dados Sybase, o qual está associado ao identificador de recurso especificado. Se o identificador de recurso não for especificado, a última conexão aberta é utilizada.
Note que isto não é normalmente necessário, já que as conexões não-persistentes abertas não automaticamente são fechadas ao final da execução do script.
sybase_close() não fechará conexões persistentes geradas pelo sybase_pconnect().
Veja também: sybase_connect(), sybase_pconnect().
Retorna: um identificador de recurso Sybase positivo em caso de sucesso ou um FALSE em caso de falha.
sybase_connect() estabelece uma conexão com um servidor Sybase. O argumento servername tem que ser um nome de servidor que é definido no arquivo 'interfaces'.
Se uma segunda chamada é feita ao sybase_connect() com os mesmos argumentos nenhum novo recurso será estabelecido. Ao invés disto, o identificador de recurso do recurso já aberto será retornado.
O recurso com o servidor será fechado tão logo a execução do script termine, a não ser que ele seja fechado anteriormente ao se chamar explicitamente o sybase_close().
Veja também sybase_pconnect(), sybase_close().
Returns: TRUE on success, FALSE on failure
sybase_data_seek() moves the internal row pointer of the Sybase result associated with the specified result identifier to pointer to the specifyed row number. The next call to sybase_fetch_row() would return that row.
See also: sybase_data_seek().
Returns: An array that corresponds to the fetched row, or FALSE if there are no more rows.
sybase_fetch_array() is an extended version of sybase_fetch_row(). In addition to storing the data in the numeric indices of the result array, it also stores the data in associative indices, using the field names as keys.
An important thing to note is that using sybase_fetch_array() is NOT significantly slower than using sybase_fetch_row(), while it provides a significant added value.
For further details, also see sybase_fetch_row().
Returns an object containing field information.
sybase_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 sybase_fetch_field() is retreived.
The properties of the object are:
name - column name. if the column is a result of a function, this property is set to computed#N, where #N is a serial number.
column_source - the table from which the column was taken
max_length - maximum length of the column
numeric - 1 if the column is numeric
type - datatype of the column
See also sybase_field_seek()
Returns: An object with properties that correspond to the fetched row, or FALSE if there are no more rows.
sybase_fetch_object() is similar to sybase_fetch_array(), with one difference - an object is returned, instead of an array. Indirectly, that means that you can only access the data by the field names, and not by their offsets (numbers are illegal property names).
Speed-wise, the function is identical to sybase_fetch_array(), and almost as quick as sybase_fetch_row() (the difference is insignificant).
See also: sybase_fetch_array() and sybase_fetch_row().
Returns: An array that corresponds to the fetched row, or FALSE if there are no more rows.
sybase_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 sybase_fetch_row() would return the next row in the result set, or FALSE if there are no more rows.
See also: sybase_fetch_array(), sybase_fetch_object(), sybase_data_seek(), sybase_fetch_lengths(), and sybase_result().
Seeks to the specified field offset. If the next call to sybase_fetch_field() won't include a field offset, this field would be returned.
See also: sybase_fetch_field().
sybase_free_result() only needs to be called if you are worried about using too much memory while your script is running. All result memory will automatically be freed when the script ends. You may call sybase_free_result() with the result identifier as an argument and the associated result memory will be freed.
sybase_get_last_message() returns the last message reported by the server.
sybase_min_client_severity() sets the minimum client severity level.
Nota: This function is only available using the CT library interface to Sybase, and not the DB library.
See also: sybase_min_server_severity().
sybase_min_error_severity() sets the minimum error severity level.
See also: sybase_min_message_severity().
sybase_min_message_severity() sets the minimum message severity level.
See also: sybase_min_error_severity().
sybase_min_server_severity() sets the minimum server severity level.
Nota: This function is only available using the CT library interface to Sybase, and not the DB library.
See also: sybase_min_client_severity().
sybase_num_fields() returns the number of fields in a result set.
See also: sybase_db_query(), sybase_query(), sybase_fetch_field(), sybase_num_rows().
sybase_num_rows() returns the number of rows in a result set.
See also: sybase_db_query(), sybase_query() and, sybase_fetch_row().
Returns: A positive Sybase persistent link identifier on success, or FALSE on error
sybase_pconnect() acts very much like sybase_connect() with two major differences.
First, when connecting, the function would first try to find a (persistent) link that's already open with the same host, username and password. If one is found, an identifier for it will be returned instead of opening a new connection.
Second, the connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (sybase_close() will not close links established by sybase_pconnect()()).
This type of links is therefore called 'persistent'.
Returns: A positive Sybase result identifier on success, or FALSE on error.
sybase_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 sybase_connect() was called, and use it.
See also: sybase_db_query(), sybase_select_db(), and sybase_connect().
Returns: The contents of the cell at the row and offset in the specified Sybase result set.
sybase_result() returns the contents of one cell from a Sybase 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 (tablename.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 sybase_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: sybase_fetch_row(), sybase_fetch_array(), and sybase_fetch_object().
Returns: TRUE on success, FALSE on error
sybase_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 sybase_connect() was called, and use it.
Every subsequent call to sybase_query() will be made on the active database.
See also: sybase_connect(), sybase_pconnect(), and sybase_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. |
See also the appendix about tokens.
Beginning with PHP 4.3.0 these functions are enabled by default. For older versions you have to configure and compile PHP with --enable-tokenizer. You can disable tokenizer support with --disable-tokenizer.
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 tokenizer is available with PHP 4.3.0.
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.
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
base64_decode() decodes encoded_data e retorna o dado original. O retorno pode ser binário.
Veja também: base64_encode(), RFC-2045 seção 6.8.
base64_encode() returns Dado codificado com base64. Esta codificação é designada para que dados binários durem no transporte sobre camadas de transorte que não são 8-bit clean, como mensagens de e-mail.
Dados codificados na Base-64 tem aproximadamente 33% mais espaço que dos dados originais.
Veja também: base64_decode(), chunk_split(), RFC-2045 seção 6.8.
(PHP 3>= 3.0.4, PHP 4 )
get_meta_tags -- Extracts all meta tag content attributes from a file and returns an arrayOpens filename and parses it line by line for <meta> tags in the file. This can be a local file or an URL. The parsing stops at </head>.
Setting use_include_path to 1 will result in PHP trying to open the file along the standard include path as per the include_path directive. This is used for local files, not URLs.
The value of the name property becomes the key, the value of the content property becomes the value of the returned array, so you can easily use standard array functions to traverse it or access single values. Special characters in the value of the name property are substituted with '_', the rest is converted to lower case. If two meta tags have the same name, only the last one is returned.
Exemplo 2. What get_meta_tags() returns
|
Nota: As of PHP 4.0.5, get_meta_tags() supports unquoted html attributes.
See also htmlentities() and urlencode().
Esta função retorna um array associativo qualquer um dos vários componentes de uma URL que estão presentes. Isto inclui "scheme", "host", "port", "user", "pass", "path", "query", e "fragment".
Returns a string in which the sequences with percent (%) signs followed by two hex digits have been replaced with literal characters. For example, the string
foo%20bar%40baz |
foo bar@baz |
Nota: rawurldecode() does not decode plus symbols ('+') into spaces. urldecode() does.
See also rawurlencode(), urldecode(), urlencode().
Returns a string in which all non-alphanumeric characters except
-_. |
Or, if you pass information in a PATH_INFO component of the URL:
See also rawurldecode(), urldecode(), urlencode() and RFC 1738
Decodifica qualquer %## codificado na string. A string decodificada é o valor de retorno.
Veja também urlencode().
Retorna uma string onde todos caracteres não-alfanuméricos exceto -_. é substituido por um sinal de porcento (%) seguidos por dois digítos hexadecimais e espaços codificados como um sinal de 'mais' (+). É codificando o mesmo caminho que um dado enviados por um formulário WWW é codificado , que é a mesma coisa como em um tipo de mídia application/x-www-form-urlencoded. Isto difere da codificação RFC1738 (veja rawurlencode()) por rasões históricas, espaçoes são codificados como um sinal de 'mais' (+). Esta função é conveniente quando codificado uma string para ser usada em uma parte de consulta em uma URL, como um conveniente meio de passar variáveis para uma próxima página:
Veja também urldecode().
For information on how variables behave, see the Variables entry in the Language Reference section of the manual.
Não há nenhuma instalação nescessária para utilizar estas funções, elas fazem parte do núcleo do PHP.
O comportamento dessas funções podem ser modificado pelas configurações do php.ini.
Tabela 1. Variables Configuration Options
Name | Default | Changeable |
---|---|---|
unserialize_callback_func | "" | PHP_INI_ALL |
Here is a short explanation of the configuration directives.
The unserialize callback function will called (with the undefind class' name as parameter), if the unserializer finds an undefined class which should be instanciated. A warning appears if the specified function is not defined, or if the function doesn't include/implement the missing class. So only set this entry, if you really want to implement such a callback-function.
See also unserialize().
This function is an alias of floatval().
Nota: This alias is a left-over from a function-renaming. In older versions of PHP you'll need to use this alias of the floatval() function, because floatval() wasn't yet available in that version.
Nota: empty() is a language construct.
This is the opposite of (boolean) var, except that no warning is generated when the variable is not set. See converting to boolean for more information.
$var = 0; if (empty($var)) { // evaluates true echo '$var is either 0 or not set at all'; } if (!isset($var)) { // evaluates false echo '$var is not set at all'; } |
Note that this is meaningless when used on anything which isn't a variable; i.e. empty (addslashes ($name)) has no meaning since it would be checking whether something which isn't a variable is a variable with a FALSE value.
Returns the float value of var.
Var may be any scalar type. You cannot use floatval() on arrays or objects.
$var = '122.34343The'; $float_value_of_var = floatval ($var); print $float_value_of_var; // prints 122.34343 |
See also intval(), strval(), settype() and Type juggling.
This function returns an multidimensional array containing a list of all defined variables, be them environment, server or user-defined variables.
$b = array(1,1,2,3,5,8); $arr = get_defined_vars(); // print $b print_r($arr["b"]); // print path to the PHP interpreter (if used as a CGI) // e.g. /usr/local/bin/php echo $arr["_"]; // print the command-line paramaters if any print_r($arr["argv"]); // print all the server vars print_r($arr["_SERVER"]); // print all the available keys for the arrays of variables print_r(array_keys(get_defined_vars())); |
See also get_defined_functions() and get_defined_constants().
This function returns a string representing the type of the resource passed to it. If the paramater is not a valid resource, it generates an error.
Returns the type of the PHP variable var.
Atenção |
Never use gettype() to test for a certain type, since the returned string may be subject to change in a future version. In addition, it is slow too, as it involves string comparision . Instead, use the is_* functions. |
Possibles values for the returned string are:
"boolean" (since PHP 4)
"integer"
"double" (for historical reasons "double" is returned in case of a float, and not simply "float")
"string"
"array"
"object"
"resource" (since PHP 4)
"NULL" (since PHP 4)
"user function" (PHP 3 only, deprecated)
"unknown type"
For PHP 4, you should use function_exists() and method_exists() to replace the prior usage of gettype() on a function.
See also settype(), is_array(), is_bool(), is_float(), is_integer(), is_null(), is_numeric(), is_object(), is_resource(), is_scalar(), and is_string().
Imports GET/POST/Cookie variables into the global scope. It is useful if you disabled register_globals, but would like to see some variables in the global scope.
Using the types parameter, you can specify which request variables to import. You can use 'G', 'P' and 'C' characters respectively for GET, POST and Cookie. These characters are not case sensitive, so you can also use any combination of 'g', 'p' and 'c'. POST includes the POST uploaded file information. Note that the order of the letters matters, as when using "gp", the POST variables will overwrite GET variables with the same name. Any other letters than GPC are discarded.
The prefix parameter is used as a variable name prefix, prepended before all variable's name imported into the global scope. So if you have a GET value named "userid", and provide a prefix "pref_", then you'll get a global variable named $pref_userid.
If you're interested in importing other variables into the global scope, such as SERVER, consider using extract().
Nota: Although the prefix parameter is optional, you will get an E_NOTICE level error if you specify no prefix, or specify an empty string as a prefix. This is a possible security hazard. Notice level errors are not displayed using the default error reporting level.
// This will import GET and POST vars // with an "rvar_" prefix import_request_variables("gP", "rvar_"); print $rvar_foo; |
See also $_REQUEST, register_globals, Predefined Variables, and extract().
Returns the integer value of var, using the specified base for the conversion (the default is base 10).
var may be any scalar type. You cannot use intval() on arrays or objects.
Nota: The base argument for intval() has no effect unless the var argument is a string.
See also floatval(), strval(), settype() and Type juggling.
Returns TRUE if var is an array, FALSE otherwise.
See also is_float(), is_int(), is_integer(), is_string(), and is_object().
Returns TRUE if the var parameter is a boolean.
See also is_array(), is_float(), is_int(), is_integer(), is_string(), and is_object().
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Returns TRUE if var is a float, FALSE otherwise.
Nota: To test if a variable is a number or a numeric string (such as form input, which is always a string), you must use is_numeric().
See also is_bool(), is_int(), is_integer(), is_numeric(), is_string(), is_array(), and is_object(),
Returns TRUE if var is an integer FALSE otherwise.
Nota: To test if a variable is a number or a numeric string (such as form input, which is always a string), you must use is_numeric().
See also is_bool(), is_float(), is_integer(), is_numeric(), is_string(), is_array(), and is_object().
Returns TRUE if var is null, FALSE otherwise.
See the NULL type when a variable is considered to be NULL and when not.
See also NULL, is_bool(), is_numeric(), is_float(), is_int(), is_string(), is_object(), is_array(), is_integer(), and is_real()
Returns TRUE if var is a number or a numeric string, FALSE otherwise.
See also is_bool(), is_float(), is_int(), is_string(), is_object(), is_array(), and is_integer().
Returns TRUE if var is an object, FALSE otherwise.
See also is_bool(), is_int(), is_integer(), is_float(), is_string(), and is_array().
is_resource() returns TRUE if the variable given by the var parameter is a resource, otherwise it returns FALSE.
See the documentation on the resource-type for more information.
is_scalar() returns TRUE if the variable given by the var parameter is a scalar, otherwise it returns FALSE.
Scalar variables are those containing an integer, float, string or boolean. Types array, object and resource or not scalar.
function show_var($var) { if (is_scalar($var)) { echo $var; } else { var_dump($var); } } $pi = 3.1416; $proteins = array("hemoglobin", "cytochrome c oxidase", "ferredoxin"); show_var($pi); // prints: 3.1416 show_var($proteins) // prints: // array(3) { // [0]=> // string(10) "hemoglobin" // [1]=> // string(20) "cytochrome c oxidase" // [2]=> // string(10) "ferredoxin" // } |
Nota: is_scalar() does not consider resource type values to be scalar as resources are abstract datatypes which are currently based on integers. This implementation detail should not be relied upon, as it may change.
See also is_bool(), is_numeric(), is_float(), is_int(), is_real(), is_string(), is_object(), is_array(), and is_integer().
Returns TRUE if var is a string, FALSE otherwise.
See also is_bool(), is_int(), is_integer(), is_float(), is_real(), is_object(), and is_array().
Nota: isset() is a language construct.
Returns TRUE if var exists; FALSE otherwise.
If a variable has been unset with unset(), it will no longer be isset(). isset() will return FALSE if testing a variable that has been set to NULL. Also note that a NULL byte ("\0") is not equivalent to the PHP NULL constant.
Warning: isset() only works with variables as passing anything else will result in a parse error. For checking if constants are set use the defined() function.
<?php $var = ''; // This will evaluate to &true; so the text will be printed. if (isset($var)) { print "This var is set set so I will print."; } // In the next examples we'll use var_dump to output // the return value of isset(). $a = "test"; $b = "anothertest"; var_dump( isset($a) ); // TRUE var_dump( isset ($a, $b) ); // TRUE unset ($a); var_dump( isset ($a) ); // FALSE var_dump( isset ($a, $b) ); // FALSE $foo = NULL; var_dump( isset ($foo) ); // FALSE ?> |
This also work for elements in arrays:
<?php $a = array ('test' => 1, 'hello' => NULL); var_dump( isset ($a['test']) ); // TRUE var_dump( isset ($a['foo']) ); // FALSE var_dump( isset ($a['hello']) ); // FALSE // The key 'hello' equals NULL so is considered unset // If you want to check for NULL key values then try: var_dump( array_key_exists('hello', $a) ); // TRUE ?> |
See also empty(), unset(), defined(), array_key_exists() and the error control @ operator.
print_r() displays information about a variable in a way that's readable by humans. If given a string, integer or float, the value itself will be printed. If given an array, values will be presented in a format that shows keys and elements. Similar notation is used for objects.
Remember that print_r() will move the array pointer to the end. Use reset() to bring it back to beginning.
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).
<pre> <?php $a = array ('a' => 'apple', 'b' => 'banana', 'c' => array ('x','y','z')); print_r ($a); ?> </pre> |
Which will output:
<pre> Array ( [a] => apple [b] => banana [c] => Array ( [0] => x [1] => y [2] => z ) ) </pre> |
Nota: Prior to PHP 4.0.4, print_r() will continue forever if given an array or object that contains a direct or indirect reference to itself. An example is print_r($GLOBALS) because $GLOBALS is itself a global variable that contains a reference to itself.
See also ob_start(), var_dump(), and var_export().
serialize() returns a string containing a byte-stream representation of value that can be stored anywhere.
This is useful for storing or passing PHP values around without losing their type and structure.
To make the serialized string into a PHP value again, use unserialize(). serialize() handles all types, except the resource-type. You can even serialize() arrays that contain references to itself. References inside the array/object you are serialize()ing will also be stored.
When serializing objects, PHP will attempt to call the member function __sleep() prior to serialization. This is to allow the object to do any last minute clean-up, etc. prior to being serialized. Likewise, when the object is restored using unserialize() the __wakeup() member function is called.
Nota: In PHP 3, object properties will be serialized, but methods are lost. PHP 4 removes that limitation and restores both properties and methods. Please see the Serializing Objects section of Classes and Objects for more information.
Exemplo 1. serialize() example
|
See Also: unserialize().
Set the type of variable var to type.
Possibles values of type are:
"boolean" (or, since PHP 4.2.0, "bool")
"integer" (or, since PHP 4.2.0, "int")
"float" (only possible since PHP 4.2.0, for older versions use the deprecated variant "double")
"string"
"array"
"object"
"null" (since PHP 4.2.0)
Retorna TRUE em caso de sucesso ou FALSE em falhas.
See also gettype(), type-casting and type-juggling.
Returns the string value of var. See the documentation on string for more information on converting to string.
var may be any scalar type. You cannot use strval() on arrays or objects.
See also floatval(), intval(), settype() and Type juggling.
unserialize() takes a single serialized variable (see serialize()) and converts it back into a PHP value. The converted value is returned, and can be an integer, float, string, array or object. In case the passed string is not unserializeable, FALSE is returned.
unserialize_callback_func directive: It's possible to set a callback-function which will be called, if an undefined class should be instantiated during unserializing. (to prevent getting an incomplete object "__PHP_Incomplete_Class".) Use your php.ini, ini_set() or .htaccess to define 'unserialize_callback_func'. Everytime an undefined class should be instantiated, it'll be called. To disable this feature just empty this setting. Also note that the directive unserialize_callback_func directive became available in PHP 4.2.0.
Nota: The callback parameter was added in PHP 4.2.0
If the variable being unserialized is an object, after successfully reconstructing the object PHP will automatically attempt to call the __wakeup() member function (if it exists).
Exemplo 1. unserialize_callback_func example
|
Nota: In PHP 3, methods are not preserved when unserializing a serialized object. PHP 4 removes that limitation and restores both properties and methods. Please see the Serializing Objects section of Classes and Objects or more information.
Exemplo 2. unserialize() example
|
See Also: serialize().
Nota: unset() is a language construct.
unset() destroys the specified variables. Note that in PHP 3, unset() will always return TRUE (actually, the integer value 1). In PHP 4, however, unset() is no longer a true function: it is now a statement. As such no value is returned, and attempting to take the value of unset() results in a parse error.
The behavior of unset() inside of a function can vary depending on what type of variable you are attempting to destroy.
If a globalized variable is unset() inside of a function, only the local variable is destroyed. The variable in the calling environment will retain the same value as before unset() was called.
The above example would output:If a variable that is PASSED BY REFERENCE is unset() inside of a function, only the local variable is destroyed. The variable in the calling environment will retain the same value as before unset() was called.
function foo(&$bar) { unset($bar); $bar = "blah"; } $bar = 'something'; echo "$bar\n"; foo($bar); echo "$bar\n"; |
If a static variable is unset() inside of a function, unset() destroyes the variable and all its references.
The above example would output:If you would like to unset() a global variable inside of a function, you can use the $GLOBALS array to do so:
This function returns structured information about one or more expressions that includes its type and value. Arrays are explored recursively with values indented to show structure.
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).
Compare var_dump() to print_r().
Exemplo 1. var_dump() example
|
This function returns structured information about the variable that is passed to this function. It is similar to var_dump() with the exception that the returned representation is valid PHP code.
You can also return the variable representation by using TRUE as second parameter to this function.
Compare var_export() to var_dump().
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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
(4.0.5 - 4.2.3 only)
vpopmail_auth_user -- Attempt to validate a username/domain/password. Returns true/falseAtenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
This extension is a generic extension API to DLLs. This was originally written to allow access to the Win32 API from PHP, although you can also access other functions exported via other DLLs.
Currently supported types are generic PHP types (strings, booleans, floats, integers and nulls) and types you define with w32api_deftype().
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. |
Não há nenhuma instalação nescessária para utilizar estas funções, elas fazem parte do núcleo do PHP.
This extension defines one resource type, used for user defined types. The name of this resource is "dynaparm".
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.
This example gets the amount of time the system has been running and displays it in a message box.
Exemplo 1. Get the uptime and display it in a message box
|
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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 you would like to define a type for a w32api call, you need to call w32api_deftype(). This function takes 2n+1 arguments, where n is the number of members the type has. The first argument is the name of the type. After that is the type of the member followed by the members name (in pairs). A member type can be a user defined type. All the type names are case sensitive. Built in type names should be provided in lowercase. Retorna TRUE em caso de sucesso ou FALSE em falhas.
(4.2.0 - 4.2.3 only)
w32api_init_dtype -- Creates an instance of the data type typename and fills it with the values passedAtenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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 creates an instance of the data type named typename, filling in the values of the data type. The typename parameter is case sensitive. You should give the values in the same order as you defined the data type with w32api_deftype(). The type of the resource returned is dynaparm.
(4.2.0 - 4.2.3 only)
w32api_invoke_function -- Invokes function funcname with the arguments passed after the function nameAtenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar em futuras versões do PHP, SEM QUALQUER NOTIFICAÇÃO. Esteja avisado, e use esta função por sua própria conta e risco. |
w32api_invoke_function() tries to find the previously registered function, named funcname, passing the parameters you provided. The return type is the one you set when you registered the function, the value is the one returned by the function itself. Any of the arguments can be of any PHP type or w32api_deftype() defined type, as needed.
(4.2.0 - 4.2.3 only)
w32api_register_function -- Registers function function_name from library with PHPAtenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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 tries to find the function_name function in libary, and tries to import it into PHP. The function will be registered with the given return_type. This type can be a generic PHP type, or a type defined with w32api_deftype(). All type names are case sensitive. Built in type names should be provided in lowercase. 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. |
This function sets the method call type. The parameter can be one of the constants DC_CALL_CDECL or DC_CALL_STD. The extension default is DC_CALL_STD.
These functions are intended for work with WDDX.
In order to use WDDX, you will need to install the expat library (which comes with Apache 1.3.7 or higher).
After installing expat compile PHP with --enable-wddx.
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.
All the functions that serialize variables use the first element of an array to determine whether the array is to be serialized into an array or structure. If the first element has string key, then it is serialized into a structure, otherwise, into an array.
This example will produce:
<wddxPacket version='1.0'><header comment='PHP packet'/><data> <string>PHP to WDDX packet example</string></data></wddxPacket> |
Exemplo 2. Using incremental packets
|
This example will produce:
<wddxPacket version='1.0'><header comment='PHP'/><data><struct> <var name='pi'><number>3.1415926</number></var><var name='cities'> <array length='3'><string>Austin</string><string>Novato</string> <string>Seattle</string></array></var></struct></data></wddxPacket> |
Nota: If you want to serialize non-ASCII characters you have to set the appropriate locale before doing so (see setlocale()).
wddx_add_vars() is used to serialize passed variables and add the result to the packet specified by the packet_id. The variables to be serialized are specified in exactly the same way as wddx_serialize_vars().
wddx_deserialize() takes a packet string and deserializes it. It returns the result which can be string, number, or array. Note that structures are deserialized into associative arrays.
wddx_packet_end() ends the WDDX packet specified by the packet_id and returns the string with the packet.
Use wddx_packet_start() to start a new WDDX packet for incremental addition of variables. It takes an optional comment string and returns a packet ID for use in later functions. It automatically creates a structure definition inside the packet to contain the variables.
wddx_serialize_value() is used to create a WDDX packet from a single given value. It takes the value contained in var, and an optional comment string that appears in the packet header, and returns the WDDX packet.
wddx_serialize_vars() is used to create a WDDX packet with a structure that contains the serialized representation of the passed variables.
wddx_serialize_vars() takes a variable number of arguments, each of which can be either a string naming a variable or an array containing strings naming the variables or another array, etc.
The above example will produce:
<wddxPacket version='1.0'><header/><data><struct><var name='a'><number>1</number></var> <var name='b'><number>5.5</number></var><var name='c'><array length='3'> <string>blue</string><string>orange</string><string>violet</string></array></var> <var name='d'><string>colors</string></var></struct></data></wddxPacket> |
XML (eXtensible Markup Language) is a data format for structured document interchange on the Web. It is a standard defined by The World Wide Web consortium (W3C). Information about XML and related technologies can be found at http://www.w3.org/XML/.
This PHP extension implements support for James Clark's expat in PHP. This toolkit lets you parse, but not validate, XML documents. It supports three source character encodings also provided by PHP: US-ASCII, ISO-8859-1 and UTF-8. UTF-16 is not supported.
This extension lets you create XML parsers and then define handlers for different XML events. Each XML parser also has a few parameters you can adjust.
This extension uses expat, which can be found at http://www.jclark.com/xml/. The Makefile that comes with expat does not build a library by default, you can use this make rule for that:
libexpat.a: $(OBJS) ar -rc $@ $(OBJS) ranlib $@ |
These functions are enabled by default, using the bundled expat library. You can disable XML support with --disable-xml. If you compile PHP as a module for Apache 1.3.9 or later, PHP will automatically use the bundled expat library from Apache. In order you dont't want to use the bundled expat library configure PHP --with-expat-dir=DIR, where DIR should point to the base installation directory of expat.
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.
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.
The XML event handlers defined are:
Tabela 1. Supported XML handlers
PHP function to set handler | Event description |
---|---|
xml_set_element_handler() | Element events are issued whenever the XML parser encounters start or end tags. There are separate handlers for start tags and end tags. |
xml_set_character_data_handler() | Character data is roughly all the non-markup contents of XML documents, including whitespace between tags. Note that the XML parser does not add or remove any whitespace, it is up to the application (you) to decide whether whitespace is significant. |
xml_set_processing_instruction_handler() | PHP programmers should be familiar with processing instructions (PIs) already. <?php ?> is a processing instruction, where php is called the "PI target". The handling of these are application-specific, except that all PI targets starting with "XML" are reserved. |
xml_set_default_handler() | What goes not to another handler goes to the default handler. You will get things like the XML and document type declarations in the default handler. |
xml_set_unparsed_entity_decl_handler() | This handler will be called for declaration of an unparsed (NDATA) entity. |
xml_set_notation_decl_handler() | This handler is called for declaration of a notation. |
xml_set_external_entity_ref_handler() | This handler is called when the XML parser finds a reference to an external parsed general entity. This can be a reference to a file or URL, for example. See the external entity example for a demonstration. |
The element handler functions may get their element names case-folded. Case-folding is defined by the XML standard as "a process applied to a sequence of characters, in which those identified as non-uppercase are replaced by their uppercase equivalents". In other words, when it comes to XML, case-folding simply means uppercasing.
By default, all the element names that are passed to the handler functions are case-folded. This behaviour can be queried and controlled per XML parser with the xml_parser_get_option() and xml_parser_set_option() functions, respectively.
The following constants are defined for XML error codes (as returned by xml_parse()):
XML_ERROR_NONE |
XML_ERROR_NO_MEMORY |
XML_ERROR_SYNTAX |
XML_ERROR_NO_ELEMENTS |
XML_ERROR_INVALID_TOKEN |
XML_ERROR_UNCLOSED_TOKEN |
XML_ERROR_PARTIAL_CHAR |
XML_ERROR_TAG_MISMATCH |
XML_ERROR_DUPLICATE_ATTRIBUTE |
XML_ERROR_JUNK_AFTER_DOC_ELEMENT |
XML_ERROR_PARAM_ENTITY_REF |
XML_ERROR_UNDEFINED_ENTITY |
XML_ERROR_RECURSIVE_ENTITY_REF |
XML_ERROR_ASYNC_ENTITY |
XML_ERROR_BAD_CHAR_REF |
XML_ERROR_BINARY_ENTITY_REF |
XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF |
XML_ERROR_MISPLACED_XML_PI |
XML_ERROR_UNKNOWN_ENCODING |
XML_ERROR_INCORRECT_ENCODING |
XML_ERROR_UNCLOSED_CDATA_SECTION |
XML_ERROR_EXTERNAL_ENTITY_HANDLING |
PHP's XML extension supports the Unicode character set through different character encodings. There are two types of character encodings, source encoding and target encoding. PHP's internal representation of the document is always encoded with UTF-8.
Source encoding is done when an XML document is parsed. Upon creating an XML parser, a source encoding can be specified (this encoding can not be changed later in the XML parser's lifetime). The supported source encodings are ISO-8859-1, US-ASCII and UTF-8. The former two are single-byte encodings, which means that each character is represented by a single byte. UTF-8 can encode characters composed by a variable number of bits (up to 21) in one to four bytes. The default source encoding used by PHP is ISO-8859-1.
Target encoding is done when PHP passes data to XML handler functions. When an XML parser is created, the target encoding is set to the same as the source encoding, but this may be changed at any point. The target encoding will affect character data as well as tag names and processing instruction targets.
If the XML parser encounters characters outside the range that its source encoding is capable of representing, it will return an error.
If PHP encounters characters in the parsed XML document that can not be represented in the chosen target encoding, the problem characters will be "demoted". Currently, this means that such characters are replaced by a question mark.
Here are some example PHP scripts parsing XML documents.
This first example displays the stucture of the start elements in a document with indentation.
Exemplo 1. Show XML Element Structure
|
Exemplo 2. Map XML to HTML This example maps tags in an XML document directly to HTML tags. Elements not found in the "map array" are ignored. Of course, this example will only work with a specific XML document type.
|
This example highlights XML code. It illustrates how to use an external entity reference handler to include and parse other documents, as well as how PIs can be processed, and a way of determining "trust" for PIs containing code.
XML documents that can be used for this example are found below the example (xmltest.xml and xmltest2.xml.)
Exemplo 3. External Entity Example
|
Exemplo 4. xmltest.xml
|
This file is included from xmltest.xml:
(PHP 3>= 3.0.6, PHP 4 )
utf8_decode -- Converts a string with ISO-8859-1 characters encoded with UTF-8 to single-byte ISO-8859-1.This function decodes data, assumed to be UTF-8 encoded, to ISO-8859-1.
See utf8_encode() for an explaination of UTF-8 encoding.
This function encodes the string data to UTF-8, and returns the encoded version. UTF-8 is a standard mechanism used by Unicode for encoding wide character values into a byte stream. UTF-8 is transparent to plain ASCII characters, is self-synchronized (meaning it is possible for a program to figure out where in the bytestream characters start) and can be used with normal string comparison functions for sorting and such. PHP encodes UTF-8 characters in up to four bytes, like this:
Each b represents a bit that can be used to store character data.
An error code from xml_get_error_code().
Returns a string with a textual description of the error code code, or FALSE if no description was found.
A reference to the XML parser to get byte index from.
This function returns FALSE if parser does not refer to a valid parser, or else it returns which byte index the parser is currently at in its data buffer (starting at 0).
A reference to the XML parser to get column number from.
This function returns FALSE if parser does not refer to a valid parser, or else it returns which column on the current line (as given by xml_get_current_line_number()) the parser is currently at.
A reference to the XML parser to get line number from.
This function returns FALSE if parser does not refer to a valid parser, or else it returns which line the parser is currently at in its data buffer.
A reference to the XML parser to get error code from.
This function returns FALSE if parser does not refer to a valid parser, or else it returns one of the error codes listed in the error codes section.
This function parses an XML file into 2 parallel array structures, one (index) containing pointers to the location of the appropriate values in the values array. These last two parameters must be passed by reference.
Below is an example that illustrates the internal structure of the arrays being generated by the function. We use a simple note tag embeded inside a para tag, and then we parse this an print out the structures generated:
$simple = "<para><note>simple note</note></para>"; $p = xml_parser_create(); xml_parse_into_struct($p,$simple,$vals,$index); xml_parser_free($p); echo "Index array\n"; print_r($index); echo "\nVals array\n"; print_r($vals); |
Index array Array ( [PARA] => Array ( [0] => 0 [1] => 2 ) [NOTE] => Array ( [0] => 1 ) ) Vals array Array ( [0] => Array ( [tag] => PARA [type] => open [level] => 1 ) [1] => Array ( [tag] => NOTE [type] => complete [level] => 2 [value] => simple note ) [2] => Array ( [tag] => PARA [type] => close [level] => 1 ) ) |
Event-driven parsing (based on the expat library) can get complicated when you have an XML document that is complex. This function does not produce a DOM style object, but it generates structures amenable of being transversed in a tree fashion. Thus, we can create objects representing the data in the XML file easily. Let's consider the following XML file representing a small database of aminoacids information:
Exemplo 1. moldb.xml - small database of molecular information
|
Exemplo 2. parsemoldb.php - parses moldb.xml into and array of molecular objects
|
A reference to the XML parser to use.
Chunk of data to parse. A document may be parsed piece-wise by calling xml_parse() several times with new data, as long as the is_final parameter is set and TRUE when the last data is parsed.
If set and TRUE, data is the last piece of data sent in this parse.
When the XML document is parsed, the handlers for the configured events are called as many times as necessary, after which this function returns TRUE or FALSE.
TRUE is returned if the parse was successful, FALSE if it was not successful, or if parser does not refer to a valid parser. For unsuccessful parses, error information can be retrieved with xml_get_error_code(), xml_error_string(), xml_get_current_line_number(), xml_get_current_column_number() and xml_get_current_byte_index().
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Which character encoding the parser should use. The following character encodings are supported:
ISO-8859-1 (default) |
US-ASCII |
UTF-8 |
A reference to the XML parser to free.
This function returns FALSE if parser does not refer to a valid parser, or else it frees the parser and returns TRUE.
A reference to the XML parser to get an option from.
Which option to fetch. See xml_parser_set_option() for a list of options.
This function returns FALSE if parser does not refer to a valid parser, or if the option could not be set. Else the option's value is returned.
See xml_parser_set_option() for the list of options.
A reference to the XML parser to set an option in.
Which option to set. See below.
The option's new value.
This function returns FALSE if parser does not refer to a valid parser, or if the option could not be set. Else the option is set and TRUE is returned.
The following options are available:
Tabela 1. XML parser options
Option constant | Data type | Description |
---|---|---|
XML_OPTION_CASE_FOLDING | integer | Controls whether case-folding is enabled for this XML parser. Enabled by default. |
XML_OPTION_TARGET_ENCODING | string | Sets which target encoding to use in this XML parser. By default, it is set to the same as the source encoding used by xml_parser_create(). Supported target encodings are ISO-8859-1, US-ASCII and UTF-8. |
Sets the character data handler function for the XML parser parser. handler is a string containing the name of a function that must exist when xml_parse() is called for parser.
The function named by handler must accept two
parameters: handler (
resource parser, string data)
The first parameter, parser, is a reference to the XML parser calling the handler.
The second parameter, data, contains the character data as a string.
If a handler function is set to an empty string, or FALSE, the handler in question is disabled.
TRUE is returned if the handler is set up, FALSE if parser is not a parser.
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.
Sets the default handler function for the XML parser parser. handler is a string containing the name of a function that must exist when xml_parse() is called for parser.
The function named by handler must accept two
parameters: handler (
resource parser, string data)
The first parameter, parser, is a reference to the XML parser calling the handler.
The second parameter, data, contains the character data. This may be the XML declaration, document type declaration, entities or other data for which no other handler exists.
If a handler function is set to an empty string, or FALSE, the handler in question is disabled.
TRUE is returned if the handler is set up, FALSE if parser is not a parser.
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.
Sets the element handler functions for the XML parser parser. start_element_handler and end_element_handler are strings containing the names of functions that must exist when xml_parse() is called for parser.
The function named by start_element_handler
must accept three parameters: start_element_handler ( resource parser,
string name, array attribs)
The first parameter, parser, is a reference to the XML parser calling the handler.
The second parameter, name, contains the name of the element for which this handler is called. If case-folding is in effect for this parser, the element name will be in uppercase letters.
The third parameter, attribs, contains an associative array with the element's attributes (if any). The keys of this array are the attribute names, the values are the attribute values. Attribute names are case-folded on the same criteria as element names. Attribute values are not case-folded.
The original order of the attributes can be retrieved by walking through attribs the normal way, using each(). The first key in the array was the first attribute, and so on.
The function named by end_element_handler
must accept two parameters: end_element_handler ( resource parser, string
name)
The first parameter, parser, is a reference to the XML parser calling the handler.
The second parameter, name, contains the name of the element for which this handler is called. If case-folding is in effect for this parser, the element name will be in uppercase letters.
If a handler function is set to an empty string, or FALSE, the handler in question is disabled.
TRUE is returned if the handlers are set up, FALSE if parser is not a parser.
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.
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
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.
(PHP 3>= 3.0.6, PHP 4 )
xml_set_external_entity_ref_handler -- set up external entity reference handlerSets the external entity reference handler function for the XML parser parser. handler is a string containing the name of a function that must exist when xml_parse() is called for parser.
The function named by handler must accept
five parameters, and should return an integer value. If the value returned from
the handler is FALSE (which it will be if no
value is returned), the XML parser will stop parsing and xml_get_error_code() will return XML_ERROR_EXTERNAL_ENTITY_HANDLING. handler ( resource
parser, string open_entity_names, string base, string system_id, string
public_id)
The first parameter, parser, is a reference to the XML parser calling the handler.
The second parameter, open_entity_names, is a space-separated list of the names of the entities that are open for the parse of this entity (including the name of the referenced entity).
This is the base for resolving the system identifier (system_id) of the external entity. Currently this parameter will always be set to an empty string.
The fourth parameter, system_id, is the system identifier as specified in the entity declaration.
The fifth parameter, public_id, is the public identifier as specified in the entity declaration, or an empty string if none was specified; the whitespace in the public identifier will have been normalized as required by the XML spec.
If a handler function is set to an empty string, or FALSE, the handler in question is disabled.
TRUE is returned if the handler is set up, FALSE if parser is not a parser.
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.
Sets the notation declaration handler function for the XML parser parser. handler is a string containing the name of a function that must exist when xml_parse() is called for parser.
A notation declaration is part of the document's DTD and has the following format:
<!NOTATION name {system_id | public_id}> |
The function named by handler must accept
five parameters: handler ( resource parser, string
notation_name, string base, string system_id, string public_id)
The first parameter, parser, is a reference to the XML parser calling the handler.
This is the notation's name, as per the notation format described above.
This is the base for resolving the system identifier (system_id) of the notation declaration. Currently this parameter will always be set to an empty string.
System identifier of the external notation declaration.
Public identifier of the external notation declaration.
If a handler function is set to an empty string, or FALSE, the handler in question is disabled.
TRUE is returned if the handler is set up, FALSE if parser is not a parser.
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.
This function allows to use parser inside object. All callback functions could be set with xml_set_element_handler() etc and assumed to be methods of object.
<?php class xml { var $parser; function xml() { $this->parser = xml_parser_create(); xml_set_object($this->parser, &$this); xml_set_element_handler($this->parser, "tag_open", "tag_close"); xml_set_character_data_handler($this->parser, "cdata"); } function parse($data) { xml_parse($this->parser, $data); } function tag_open($parser, $tag, $attributes) { var_dump($parser, $tag, $attributes); } function cdata($parser, $cdata) { var_dump($parser, $cdata); } function tag_close($parser, $tag) { var_dump($parser, $tag); } } // end of class xml $xml_parser = new xml(); $xml_parser->parse("<A ID='hallo'>PHP</A>"); ?> |
(PHP 3>= 3.0.6, PHP 4 )
xml_set_processing_instruction_handler -- Set up processing instruction (PI) handlerSets the processing instruction (PI) handler function for the XML parser parser. handler is a string containing the name of a function that must exist when xml_parse() is called for parser.
A processing instruction has the following format:
You can put PHP code into such a tag, but be aware of one limitation: in an XML PI, the PI end tag (?>) can not be quoted, so this character sequence should not appear in the PHP code you embed with PIs in XML documents. If it does, the rest of the PHP code, as well as the "real" PI end tag, will be treated as character data.The function named by handler must accept
three parameters: handler ( resource parser, string target,
string data)
The first parameter, parser, is a reference to the XML parser calling the handler.
The second parameter, target, contains the PI target.
The third parameter, data, contains the PI data.
If a handler function is set to an empty string, or FALSE, the handler in question is disabled.
TRUE is returned if the handler is set up, FALSE if parser is not a parser.
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.
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
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.
(PHP 3>= 3.0.6, PHP 4 )
xml_set_unparsed_entity_decl_handler -- Set up unparsed entity declaration handlerSets the unparsed entity declaration handler function for the XML parser parser. handler is a string containing the name of a function that must exist when xml_parse() is called for parser.
This handler will be called if the XML parser encounters an external entity declaration with an NDATA declaration, like the following:
<!ENTITY name {publicId | systemId} NDATA notationName> |
See section 4.2.2 of the XML 1.0 spec for the definition of notation declared external entities.
The function named by handler must accept six
parameters: handler (
resource parser, string entity_name, string base, string system_id, string
public_id, string notation_name)
The first parameter, parser, is a reference to the XML parser calling the handler.
The name of the entity that is about to be defined.
This is the base for resolving the system identifier (systemId) of the external entity. Currently this parameter will always be set to an empty string.
System identifier for the external entity.
Public identifier for the external entity.
Name of the notation of this entity (see xml_set_notation_decl_handler()).
If a handler function is set to an empty string, or FALSE, the handler in question is disabled.
TRUE is returned if the handler is set up, FALSE if parser is not a parser.
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.
These functions can be used to write XML-RPC servers and clients. You can find more information about XML-RPC at http://www.xmlrpc.com/, and more documentation on this extension and it's functions at http://xmlrpc-epi.sourceforge.net/.
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. |
XML-RPC support in PHP is not enabled by default. You will need to use the --with-xmlrpc[=DIR] configuration option when compiling PHP to enable XML-RPC support. This extension is bundled into PHP as of 4.1.0.
O comportamento dessas funções podem ser modificado pelas configurações do php.ini.
Tabela 1. XML-RPC configuration options
Name | Default | Changeable |
---|---|---|
xmlrpc_errors | "0" | PHP_INI_SYSTEM |
xmlrpc_error_number | "0" | PHP_INI_ALL |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
(PHP 4 >= 4.1.0)
xmlrpc_get_type -- Gets xmlrpc type for a PHP value. Especially useful for base64 and datetime stringsAtenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
(PHP 4 >= 4.1.0)
xmlrpc_server_register_introspection_callback -- Register a PHP function to generate documentationAtenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
(PHP 4 >= 4.1.0)
xmlrpc_server_register_method -- Register a PHP function to resource method matching method_nameAtenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
Atenção |
Esta função é EXPERIMENTAL. Isso quer dizer que o comportamento desta função e seu nome, incluindo TUDO o que está documentado aqui pode mudar 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. |
This PHP extension provides a processor independent API to XSLT transformations. Currently this extension only supports the Sablotron library from the Ginger Alliance. Support is planned for other libraries, such as the Xalan library or the libxslt library.
XSLT (Extensible Stylesheet Language (XSL) Transformations) is a language for transforming XML documents into other XML documents. It is a standard defined by The World Wide Web Consortium (W3C). Information about XSLT and related technologies can be found at http://www.w3.org/TR/xslt.
Nota: This extension is different than the sablotron extension distributed with versions of PHP prior to PHP 4.1, currently only the new XSLT extension in PHP 4.1 is supported. If you need support for the old extension, please ask your questions on the PHP mailing lists.
This extension uses Sablotron and expat, which can both be found at http://www.gingerall.com/. Binaries are provided as well as source.
On UNIX, run configure with the --enable-xslt --with-xslt-sablot options. The Sablotron library should be installed somewhere your compiler can find it.
Make sure you have the same libraries linked to the Sablotron library as those, which are linked with PHP. The configuration options: --with-expat-dir=DIR --with-iconv-dir=DIR are there to help you specify them. When asking for support, always mention these directives, and whether there are other versions of those libraries installed on your system somewhere. Naturally, provide all the version numbers.
JavaScript E-XSLT support: If you compiled Sablotron with JavaScript support, you must specify the option: --with-sablot-js=DIR.
Note to Win32 Users: In order to enable this module on a Windows environment, you must copy sablot.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)
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.
Drop all logging and error reporting. This is a generic option for all backends that may be added in the future.
Tell Sablotron to parse public entities. By default this has been turned off.
Do not add the meta tag "Content-Type" for HTML output. The default is set during compilation of Sablotron.
Suppress the whitespace stripping (on data files only).
Consider unresolved documents (the document() function) non-lethal.
Error return code, for scheme handlers.
Create and return a new XSLT processor resource for manipulation by the other XSLT functions.
Return an error code describing the last error that occured on the passed XSLT processor.
Return a string describing the last error that occured on the passed XSLT processor.
Exemplo 1. Handling errors using the xslt_error() and xslt_errno() functions.
|
The xslt_process() function is the crux of the new XSLT extension. It allows you to perform an XSLT transformation using almost any type of input source - the containers. This is accomplished through the use of argument buffers -- a concept taken from the Sablotron XSLT processor (currently the only XSLT processor this extension supports). The input containers default to a filename 'containing' the document to be processed. The result container defaults to a filename for the transformed document. If the result container is not specified - i.e. NULL - than the result is returned.
Atenção |
This function has changed it's arguments, sinceversion 4.0.6. Do NOT provide the actual xml or xsl content as 2nd and 3rd argument, as this will create a segmentation fault, in Sablotron versions up to and including 0.95. |
Containers can also be set via the $arguments array (see below).
The simplest type of transformation with the xslt_process() function is the transformation of an XML file with an XSLT file, placing the result in a third file containing the new XML (or HTML) document. Doing this with sablotron is really quite easy...
Exemplo 1. Using the xslt_process() to transform an XML file and a XSL file to a new XML file
|
While this functionality is great, many times, especially in a web environment, you want to be able to print out your results directly. Therefore, if you omit the third argument to the xslt_process() function (or provide a NULL value for the argument), it will automatically return the value of the XSLT transformation, instead of writing it to a file...
Exemplo 2. Using the xslt_process() to transform an XML file and a XSL file to a variable containing the resulting XML data
|
The above two cases are the two simplest cases there are when it comes to XSLT transformation and I'd dare say that they are the most common cases, however, sometimes you get your XML and XSLT code from external sources, such as a database or a socket. In these cases you'll have the XML and/or XSLT data in a variable -- and in production applications the overhead of dumping these to file may be too much. This is where XSLT's "argument" syntax, comes to the rescue. Instead of files as the XML and XSLT arguments to the xslt_process() function, you can specify "argument place holders" which are then subsituted by values given in the arguments array (5th parameter to the xslt_process() function). The following is an example of processing XML and XSLT into a result variable without the use of files at all.
Exemplo 3. Using the xslt_process() to transform a variable containing XML data and a variable containing XSL data into a variable containing the resulting XML data
|
Finally, the last argument to the xslt_process() function represents an array for any top-level parameters that you want to pass to the XSLT document. These parameters can then be accessed within your XSL files using the <xsl:param name="parameter_name"> instruction. The parameters must be UTF-8 encoded and their values will be interpreted as strings by the Sablotron processor. In other words - you cannot pass node-sets as parameters to the XSLT document.
Nota: Please note that file:// is needed in front of path if you use Windows.
Sets the base URI for all XSLT transformations, the base URI is used with Xpath instructions to resolve document() and other commands which access external resources. It is also used to resolve URIs for the <xsl:include> and <xsl:import> elements.
As of 4.3, the default base URI is the directory of the executing script. In effect, it is the directory name value of the __FILE__ constant. Prior to 4.3, the default base URI was less predictable.
Nota: Please note that file:// is needed in front of path if you use Windows.
Set the output encoding for the XSLT transformations. When using the Sablotron backend this option is only available when you compile Sablotron with encoding support.
Set an error handler function for the XSLT processor given by xh, this function will be called whenever an error occurs in the XSLT transformation (this function is also called for notices).
A reference to the XSLT parser.
This parameter is either a boolean value which toggles logging on and off, or a string containing the logfile in which log errors too.
This function allows you to set the file in which you want XSLT log messages to, XSLT log messages are different than error messages, in that log messages are not actually error messages but rather messages related to the state of the XSLT processor. They are useful for debugging XSLT, when something goes wrong.
By default logging is disabled, in order to enable logging you must first call xslt_set_log() with a boolean parameter which enables logging, then if you want to set the log file to debug to, you must then pass it a string containing the filename:
Nota: Please note that file:// is needed in front of path if you use Windows.
Set SAX handlers on the resource handle given by xh. SAX handlers should be a two dimensional array with the format (all top level elements are optional):
array( [document] => array( start document handler, end document handler ), [element] => array( start element handler, end element handler ), [namespace] => array( start namespace handler, end namespace handler ), [comment] => comment handler, [pi] => processing instruction handler, [character] => character data handler ) |
(PHP 4 >= 4.0.6)
xslt_set_sax_handlers -- Set the SAX handlers to be called when the XML document gets processed
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Set Scheme handlers on the resource handle given by xh. Scheme handlers should be an array with the format (all elements are optional):
This extension offers a PHP interface to the YAZ toolkit that implements the Z39.50 Protocol for Information Retrieval. With this extension you can easily implement a Z39.50 origin (client) that searches or scans Z39.50 targets (servers) in parallel.
The module hides most of the complexity of Z39.50 so it should be fairly easy to use. It supports persistent stateless connections very similar to those offered by the various RDB APIs that are available for PHP. This means that sessions are stateless but shared amongst users, thus saving the connect and initialize phase steps in most cases.
YAZ is available at http://www.indexdata.dk/yaz/. You can find news information, example scripts, etc. for this extension at http://www.indexdata.dk/phpyaz/.
Compile YAZ (ANSI/NISO Z39.50 support) and install it. Build PHP with your favourite modules and add option --with-yaz[=DIR]. Your task is roughly the following:
O comportamento dessas funções podem ser modificado pelas configurações do php.ini.
Tabela 1. YAZ configuration options
Name | Default | Changeable |
---|---|---|
yaz.max_links | "100" | PHP_INI_ALL |
yaz.log_file | "" | PHP_INI_ALL |
PHP/YAZ keeps track of connections with targets (Z-Associations). A resource represents a connection to a target.
Exemplo 1. Parallel searching using YAZ() The script below demonstrates the parallel searching feature of the API. When invoked with no arguments it prints a query form; else (arguments are supplied) it searches the targets as given in array host.
|
Returns additional error message for target (last request). An empty string is returned if last operation was a success or if no additional information was provided by the target.
This function configures the CCL query parser for a target with definitions of access points (CCL qualifiers) and their mapping to RPN. To map a specific CCL query to RPN afterwards call the yaz_ccl_parse() function. Each index of the array config is the name of a CCL field and the corresponding value holds a string that specifies a mapping to RPN. The mapping is a sequence of attribute-type, attribute-value pairs. Attribute-type and attribute-value is separated by an equal sign (=). Each pair is separated by white space.
Exemplo 1. CCL configuration In the example below, the CCL parser is configured to support three CCL fields: ti, au and isbn. Each field is mapped to their BIB-1 equivalent. It is assumed that variable $id is the connection ID.
|
This function invokes a CCL parser. It converts a given CCL FIND query to an RPN query which may be passed to the yaz_search() function to perform a search. To define a set of valid CCL fields call yaz_ccl_conf() prior to this function. If the supplied query was successfully converted to RPN, this function returns TRUE, and the index rpn of the supplied array result holds a valid RPN query. If the query could not be converted (because of invalid syntax, unknown field, etc.) this function returns FALSE and three indexes are set in the resulting array to indicate the cause of failure: errorcodeCCL error code (integer), errorstringCCL error string, and errorposapproximate position in query of failure (integer is character position).
Exemplo 1. CCL Parsing We'll try to search using CCL. In the example below, $ccl is a CCL query.
|
Closes connection given by id. The id is a connection resource as returned by a previous yaz_connect() call.
This function returns a connection resource on success; zero on failure.
yaz_connect() prepares for a connection to a Z39.50 target. The zurl argument takes the form host[:port][/database]. If port is omitted 210 is used. If database is omitted Default is used. This function is non-blocking and doesn't attempt to establish a socket - it merely prepares a connect to be performed later when yaz_wait() is called.
If the second argument, options, is given as a string it is treated as the Z39.50 V2 authentication string (OpenAuth).
If options is given as an array the contents of the array serves as options. Note that array options are only supported for PHP 4.1.0 and later.
yaz_connect() options
Username for authentication.
Group for authentication.
Password for authentication.
Cookie for session (YAZ proxy).
Proxy for connection (YAZ proxy).
A boolean. If TRUE the connection is persistent; If FALSE the connection is not persistent. By default connections are persistent.
A boolean. If TRUE piggyback is enabled for searches; If FALSE piggyback is disabled. By default piggyback is enabled. Enabling piggyback is more efficient and usually saves a network-round-trip for first time fetches of records. However, a few Z39.50 targets doesn't support piggyback or they ignore element set names. For those, piggyback should be disabled.
Nota: The use of a proxy often improves performance. A Z39.50 proxy is part of the free YAZ++ package.
This function specifies one or more databases to be used in search, retrieval, etc. - overriding databases specified in call to yaz_connect(). Multiple databases are separated by a plus sign +.
This function allows you to use different sets of databases within a session.
Returns TRUE on success; FALSE on error.
This function sets the element set name for retrieval. Call this function before yaz_search() or yaz_present() to specify the element set name for records to be retrieved. Most servers support F (for full records) and B (for brief records).
Returns TRUE on success; FALSE on error.
Returns error for target (last request). The error code is either a Z39.50 diagnostic code (usually a Bib-1 diagnostic) or a client side error code which is generated by PHP/YAZ itself, such as "Connect failed", "Init Rejected", etc.
yaz_errno() should be called after network activity for each target - (after yaz_wait() returns) to determine the success or failure of the last operation (e.g. search). To get a text description of the error, call yaz_error().
Returns error text message for target (last request). An empty string is returned if last operation was a success.
yaz_error() returns an english text message corresponding to the last error number as returned by yaz_errno().
Returns value of option with the name specified. If option is unset, an empty string is returned.
See description of yaz_set_option() for available options.
This function prepares for an Extended Services request using the Profile for the Use of Z39.50 Item Order Extended Service to Transport ILL (Profile/1). See this and the specification. The args parameter must be a hash array with information about the Item Order request to be sent. The key of the hash is the name of the corresponding ASN.1 tag path. For example, the ISBN below the Item-ID has the key item-id,ISBN.
The ILL-Request parameters are:
protocol-version-num
transaction-id,initial-requester-id,person-or-institution-symbol,person
transaction-id,initial-requester-id,person-or-institution-symbol,institution
transaction-id,initial-requester-id,name-of-person-or-institution,name-of-person
transaction-id,initial-requester-id,name-of-person-or-institution,name-of-institution
transaction-id,transaction-group-qualifier
transaction-id,transaction-qualifier
transaction-id,sub-transaction-qualifier
service-date-time,this,date
service-date-time,this,time
service-date-time,original,date
service-date-time,original,time
requester-id,person-or-institution-symbol,person
requester-id,person-or-institution-symbol,institution
requester-id,name-of-person-or-institution,name-of-person
requester-id,name-of-person-or-institution,name-of-institution
responder-id,person-or-institution-symbol,person
responder-id,person-or-institution-symbol,institution
responder-id,name-of-person-or-institution,name-of-person
responder-id,name-of-person-or-institution,name-of-institution
transaction-type
delivery-address,postal-address,name-of-person-or-institution,name-of-person
delivery-address,postal-address,name-of-person-or-institution,name-of-institution
delivery-address,postal-address,extended-postal-delivery-address
delivery-address,postal-address,street-and-number
delivery-address,postal-address,post-office-box
delivery-address,postal-address,city
delivery-address,postal-address,region
delivery-address,postal-address,country
delivery-address,postal-address,postal-code
delivery-address,electronic-address,telecom-service-identifier
delivery-address,electronic-address,telecom-service-addreess
billing-address,postal-address,name-of-person-or-institution,name-of-person
billing-address,postal-address,name-of-person-or-institution,name-of-institution
billing-address,postal-address,extended-postal-delivery-address
billing-address,postal-address,street-and-number
billing-address,postal-address,post-office-box
billing-address,postal-address,city
billing-address,postal-address,region
billing-address,postal-address,country
billing-address,postal-address,postal-code
billing-address,electronic-address,telecom-service-identifier
billing-address,electronic-address,telecom-service-addreess
ill-service-type
requester-optional-messages,can-send-RECEIVED
requester-optional-messages,can-send-RETURNED
requester-optional-messages,requester-SHIPPED
requester-optional-messages,requester-CHECKED-IN
search-type,level-of-service
search-type,need-before-date
search-type,expiry-date
search-type,expiry-flag
place-on-hold
client-id,client-name
client-id,client-status
client-id,client-identifier
item-id,item-type
item-id,call-number
item-id,author
item-id,title
item-id,sub-title
item-id,sponsoring-body
item-id,place-of-publication
item-id,publisher
item-id,series-title-number
item-id,volume-issue
item-id,edition
item-id,publication-date
item-id,publication-date-of-component
item-id,author-of-article
item-id,title-of-article
item-id,pagination
item-id,ISBN
item-id,ISSN
item-id,additional-no-letters
item-id,verification-reference-source
copyright-complicance
retry-flag
forward-flag
requester-note
forward-note
There are also a few parameters that are part of the Extended Services Request package and the ItemOrder package:
package-name
user-id
contact-name
contact-phone
contact-email
itemorder-item
This function prepares for retrieval of records after a successful search. The yaz_range() should be called prior to this function to specify the range of records to be retrieved.
This function should be called before either yaz_search() or yaz_present() to specify a range of records to be retrieved. The start specifies position of first record to be retrieved and number is the number records. Records in a result set are numbered 1, 2, ... $hits where $hits is the count returned by yaz_hits().
Returns TRUE on success; FALSE on error.
Returns record at position pos or empty string if no record exists at given position.
The yaz_record() function inspects a record in the current result set at the position specified. If no database record exists at the given position an empty string is returned. The type specifies the form of the returned record.
If type is "string" the record is returned in a string representation suitable for printing (for XML and SUTRS). If type is "array" the record is returned as an array representation (for structured records). If type is "raw" the record is returned in its original raw form.
Records in a result set are numbered 1, 2, ... $hits where $hits is the count returned by yaz_hits().
yaz_scan_result() returns terms and associated information as received from the target in the last performed yaz_scan(). This function returns an array (0..n-1) where n is the number of terms returned. Each value is a pair where first item is term, second item is result-count. If the result is given it will be modified to hold additional information taken from the Scan Response: number (number of entries returned), stepsize (Step-size), position (position of term), status (Scan Status).
This function prepares for a Z39.50 Scan Request. Argument id specifies connection. Starting term point for the scan is given by startterm. The form in which is the starting term is specified is given by type. Currently type rpn is supported. The optional flags specifies additional information to control the behaviour of the scan request. Three indexes are currently read from the flags: number (number of terms requested), position (preferred position of term) and stepSize (preferred step size). To actually tranfer the Scan Request to the target and receive the Scan Response, yaz_wait() must be called. Upon completion of yaz_wait() call yaz_error() and yaz_scan_result() to handle the response.
The syntax of startterm is similar to the RPN query as described in yaz_search(). The startterm consists of zero or more @attr-operator specifications, then followed by exactly one token.
Exemplo 1. PHP function that scans titles
|
The schema must be specified as an OID (Object Identifier) in a raw dot-notation (like 1.2.840.10003.13.4) or as one of the known registered schemas: GILS-schema, Holdings, Zthes, ... This function should be called before yaz_search() or yaz_present().
yaz_search() prepares for a search on the connection given by id. The type represents the query type - only "rpn" is supported now in which case the third argument specifies a Type-1 query in prefix query notation. Like yaz_connect() this function is non-blocking and only prepares for a search to be executed later when yaz_wait() is called.
The RPN query is a textual represenation of the Type-1 query as defined by the Z39.50 standard. However, in the text representation as used by YAZ a prefix notation is used, that is the operater precedes the operands. The query string is a sequence of tokens where white space is ignored is ignored unless surrounded by double quotes. Tokens beginning with an at-character (@) are considered operators, otherwise they are treated as search terms.
Tabela 1. RPN Operators
Construct | Description |
---|---|
@and query1 query2 | intersection of query1 and query2 |
@or query1 query2 | union of query1 and query2 |
@not query1 query2 | query1 and not query2 |
@set name | result set reference |
@attrset set query | specifies attribute-set for query. This construction is only allowed once - in the beginning of the whole query |
@attr [set] type=value query | applies attribute to query. The type and value are integers specifying the attribute-type and attribute-value respectively. The set, if given, specifies the attribute-set. |
Exemplo 1. Query Examples You can search for simple terms, like this
The Query
This query applies two attributes for the same phrase.
This query
Another, more complex, one:
|
You can find information about attributes at the Z39.50 Maintenance Agency site.
Nota: If you would like to use a more friendly notation, use the CCL parser - functions yaz_ccl_conf() and yaz_ccl_parse().
Sets option name to value.
Tabela 1. PYP/YAZ Connection Options
Name | Description |
---|---|
implementationName | implementation name of target |
implementationVersion | implementation version of target |
implementationId | implementation ID of target |
schema | schema for retrieval. By default, no schema is used. Setting this option is equivalent to using function yaz_schema() |
preferredRecordSyntax | record syntax for retrieval. By default, no syntax is used. Setting this option is equivalent to using function yaz_syntax() |
start | offset for first record to be retrieved via yaz_search() or yaz_present(). Records are numbered from zero and upwards. Setting this option in combination with option count has the same effect as calling yaz_range() except that records are numbered from 1 in yaz_range() |
count | maximum number of records to be retrieved via yaz_search() or yaz_present(). |
elementSetName | element-set-name for retrieval. Setting this option is equivalent to calling yaz_element(). |
This function sets sorting criteria and enables Z39.50 Sort. Call this function before yaz_search(). Using this function alone doesn't have any effect. When in conjunction with yaz_search(), a Z39.50 Sort will be sent after a search response has been received and before any records are retrieved with Z39.50 Present. The criteria takes the form
field1 flags1 field2 flags2 ...
where field1 specifies primary attributes for sort, field2 seconds, etc.. The field specifies either numerical attribute combinations consisting of type=value pairs separated by comma (e.g. 1=4,2=1) ; or the field may specify a plain string criteria (e.g. title. The flags is a sequnce of the following characters which may not be separated by any white space.
Sort Flags
Sort ascending
Sort descending
Case insensitive sorting
Case sensitive sorting
The syntax must be specified as an OID (Object Identifier) in a raw dot-notation (like 1.2.840.10003.5.10) or as one of the known registered record syntaxes (sutrs, usmarc, grs1, xml, etc.). This function should be called before yaz_search() or yaz_present().
This function carries out networked (blocked) activity for outstanding requests which have been prepared by the functions yaz_connect(), yaz_search(), yaz_present(), yaz_scan() and yaz_itemorder(). yaz_wait() returns when all targets have either completed all requests or aborted (in case of errors).
If the options array is given that holds options that change the behaviour of yaz_wait().
Sets timeout in seconds. If a target hasn't responded within the timeout it is considered dead and yaz_wait() returns. The default value for timeout is 15 seconds.
NIS (formerly called Yellow Pages) allows network management of important administrative files (e.g. the password file). For more information refer to the NIS manpage and The Linux NIS(YP)/NYS/NIS+ HOWTO. There is also a book called Managing NFS and NIS by Hal Stern.
Nota: This extension is not available on Windows platforms.
None besides functions from standard Unix libraries which are always available (either libc or libnsl, configure will detect which one to use).
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.
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
Atenção |
Esta função não está documentada, somente a lista de argumentos está disponível. |
yp_err_string() returns the error message associated with the previous operation. Useful to indicate what exactly went wrong.
See also yp_errno().
yp_errno() returns the error code of the previous operation.
Possible errors are:
1 args to function are bad |
2 RPC failure - domain has been unbound |
3 can't bind to server on this domain |
4 no such map in server's domain |
5 no such key in map |
6 internal yp server or client error |
7 resource allocation failure |
8 no more records in map database |
9 can't communicate with portmapper |
10 can't communicate with ypbind |
11 can't communicate with ypserv |
12 local domain name not set |
13 yp database is bad |
14 yp version mismatch |
15 access violation |
16 database busy |
See also yp_err_string().
yp_first() returns the first key-value pair from the named map in the named domain, otherwise FALSE.
See also yp-get-default-domain()
yp_get_default_domain() returns the default domain of the node or FALSE. Can be used as the domain parameter for successive NIS calls.
A NIS domain can be described a group of NIS maps. Every host that needs to look up information binds itself to a certain domain. Refer to the documents mentioned at the beginning for more detailed information.
yp_master() returns the machine name of the master NIS server for a map.
See also yp-get-default-domain().
yp_match() returns the value associated with the passed key out of the specified map or FALSE. This key must be exact.
In this case this could be: joe:##joe:11111:100:Joe User:/home/j/joe:/usr/local/bin/bash
See also yp-get-default-domain()
yp_next() returns the next key-value pair in the named map after the specified key or FALSE.
See also yp-get-default-domain().
yp_order() returns the order number for a map or FALSE.
See also yp-get-default-domain().
This module enables you to transparently read ZIP compressed archives and the files inside them.
This module uses the functions of the ZZIPlib library by Guido Draheim. You need ZZIPlib version >= 0.10.6.
Note that ZZIPlib only provides a subset of functions provided in a full implementation of the ZIP compression algorithm and can only read ZIP file archives. A normal ZIP utility is needed to create the ZIP file archives read by this library.
Zip support in PHP is not enabled by default. You will need to use the --with-zip[=DIR] configuration option when compiling PHP to enable zip support.
Nota: Zip support before PHP 4.1.0 is experimental. This section reflects the Zip extension as it exists in PHP 4.1.0 and later.
This example opens a ZIP file archive, reads each file in the archive and prints out its contents. The test2.zip archive used in this example is one of the test archives in the ZZIPlib source distribution.
Exemplo 1. Zip Usage Example
|
Closes a zip file archive. The parameter zip must be a zip archive previously opened by zip_open().
This function has no return value.
See also zip_open() and zip_read().
Closes a directory entry specified by zip_entry. The parameter zip_entry must be a valid directory entry opened by zip_entry_open().
This function has no return value.
See also zip_entry_open() and zip_entry_read().
Returns the compressed size of the directory entry specified by zip_entry. The parameter zip_entry is a valid directory entry returned by zip_read().
See also zip_open() and zip_read().
Returns the compression method of the directory entry specified by zip_entry. The parameter zip_entry is a valid directory entry returned by zip_read().
See also zip_open() and zip_read().
Returns the actual size of the directory entry specified by zip_entry. The parameter zip_entry is a valid directory entry returned by zip_read().
See also zip_open() and zip_read().
Returns the name of the directory entry specified by zip_entry. The parameter zip_entry is a valid directory entry returned by zip_read().
See also zip_open() and zip_read().
Opens a directory entry in a zip file for reading. The parameter zip is a valid resource handle returned by zip_open(). The parameter zip_entry is a directory entry resource returned by zip_read(). The optional parameter mode can be any of the modes specified in the documentaion for fopen().
Nota: Currently, mode is ignored and is always "rb". This is due to the fact that zip support in PHP is read only access. Please see fopen() for an explanation of various modes, including "rb".
Retorna TRUE em caso de sucesso ou FALSE em falhas.
Nota: Unlike fopen() and other similar functions, the return value of zip_entry_open() only indicates the result of the operation and is not needed for reading or closing the directory entry.
See also zip_entry_read() and zip_entry_close().
Reads up to length bytes from an open directory entry. If length is not specified, then zip_entry_read() will attempt to read 1024 bytes. The parameter zip_entry is a valid directory entry returned by zip_read().
Nota: The length parameter should be the uncompressed length you wish to read.
Returns the data read, or FALSE if the end of the file is reached.
See also zip_entry_open(), zip_entry_close() and zip_entry_filesize().
Opens a new zip archive for reading. The filename parameter is the filename of the zip archive to open.
Returns a resource handle for later use with zip_read() and zip_close() or returns FALSE if filename does not exist.
See also zip_read() and zip_close().
Reads the next entry in a zip file archive. The parameter zip must be a zip archive previously opened by zip_open().
Returns a directory entry resource for later use with the zip_entry_...() functions.
See also zip_open(), zip_close(), zip_entry_open(), and zip_entry_read().
Este módulo lhe possibilita ler e gerar transparentemente arquivos comprimidos do tipo gzip (.gz), através de muitas das funções filesystem nas quais funcionam com arquivos gzip comprimidos (e arquivos não comprimidos também, mas não com sockets).
Nota: A Versão 4.0.4 introduziu a função fopen-wrapper para arquivos .gz, então você pode usar o prefixo 'zlib:' especial para acessar arquivos comprimidos transparentemente usando as funções normais de acesso a arquivos f*() se você concatenar o nome do arquivo e ou seu caminho com o prefixo 'zlib:' quando usar a função fopen().
Na versão 4.3.0, este prefixo especial foi mudado para 'zlib://' para previnir ambiguidades com nome de arquivos contendo ':'.
Esta facilidade requer uma biblioteca em tempo de execução que provê a função fopencookie(). Em meu conhecimento atual a GNU libc é a única bliblioteca que provê esta facilidade.
Este módulo usa as funções da zlib por Jean-loup Gailly e Mark Adler. Você terá que usar uma versão zlib >= à 1.0.9 com este módulo.
O comportamento dessas funções podem ser modificado pelas configurações do php.ini.
A extensão zlib oferece a opção de comprimir transparentemente suas páginas em tempo real, se o navegador requisitante suportar isto. Então existem três opções no arquivo de configuração php.ini.
Tabela 1. Opções de Configuração da Zlib
Nome | Padrão | Modificável |
---|---|---|
zlib.output_compression | "Off" | PHP_INI_ALL |
zlib.output_compression_level | "-1" | PHP_INI_ALL |
zlib.output_handler | "" | PHP_INI_ALL |
Aqui está uma breve explicação das diretrizes de configuração.
Serve para comprimir páginas de modo transparente. Se esta opção for mudada para "On" no php.ini ou na configuração do Apache, as páginas serão comprimidas se o navegador enviar um cabeçalho "Accept-Encoding: gzip" ou "deflate". "Content-Encoding: gzip" (respectivamente "deflate") e cabeçalhos "Vary: Accept-Encoding" serão adicionados para a saida.
Você pode usar a função ini_set() para desabilitar isto em seu script se os cabeçalhos ainda não foram enviados. Se você enviar um cabeçalho à saída "Content-Type: image/" a compressão será desabilitada, também (para corrigir um defeito do Netscape). Você pode reabilitar isto, se você adicionar a função "ini_set('zlib.output_compression', 'On')" depois da chamada do cabeçalho que que foi adicionado o content-type da imagem.
Esta opção também aceita valores inteiros em vez de valores booleanos "On"/"Off", usando isto você pode configurar o tamanho do buffer de saída (o padrão é 4KB).
Nota: output_handler deve estar vazio se a diretriz estiver configurada em 'On'! Em vez disto você deve usar zlib.output_handler.
Nível de compressão usado para as saídas.
Você não pode especificar tratamentos adicionais de saída se zlib.output_compression for ativado. Esta configuração faz o mesmo que a output_handler mas em uma ordem diferente.
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.
Este exemplo abre um arquivo temporário e gera uma string teste dentro dele, então ela mostra o conteúdo deste arquivo duas vezes.
Exemplo 1. Pequeno Exemplo das funções Zlib
|
The gz-file pointed to by zp is closed.
Retorna TRUE em caso de sucesso ou FALSE em falhas.
The gz-file pointer must be valid, and must point to a file successfully opened by gzopen().
This function returns a compressed version of the input data using the ZLIB data format, or FALSE if an error is encountered. The optional parameter level can be given as 0 for no compression up to 9 for maximum compression.
For details on the ZLIB compression algorithm see the document "ZLIB Compressed Data Format Specification version 3.3" (RFC 1950).
Nota: This is not the same as gzip compression, which includes some header data. See gzencode() for gzip compression.
See also gzdeflate(), gzinflate(), gzuncompress(), gzencode().
This function returns a compressed version of the input data using the DEFLATE data format, or FALSE if an error is encountered. The optional parameter level can be given as 0 for no compression up to 9 for maximum compression.
For details on the DEFLATE compression algorithm see the document "DEFLATE Compressed Data Format Specification version 1.3" (RFC 1951).
See also gzinflate(), gzcompress(), gzuncompress(), gzencode().
This function returns a compressed version of the input data compatible with the output of the gzip program, or FALSE if an error is encountered. The optional parameter level can be given as 0 for no compression up to 9 for maximum compression, if not given the default compression level will be the default compression level of the zlib library.
You can also give FORCE_GZIP (the default) or FORCE_DEFLATE as optional third paramter encoding_mode. If you use FORCE_DEFLATE, you get a standard zlib deflated string (inclusive zlib headers) after the gzip file header but without the trailing crc32 checksum.
Nota: level was added in PHP 4.2, before PHP 4.2 gzencode() only had the data and (optional) encoding_mode parameters..
The resulting data contains the appropriate headers and data structure to make a standard .gz file, e.g.:
For more information on the GZIP file format, see the document: GZIP file format specification version 4.3 (RFC 1952).
See also gzcompress(). gzuncompress(), gzdeflate(), gzinflate().
Returns TRUE if the gz-file pointer is at EOF or an error occurs; otherwise returns FALSE.
The gz-file pointer must be valid, and must point to a file successfully opened by gzopen().
Identical to readgzfile(), except that gzfile() returns the file in an array.
You can use the optional second parameter and set it to "1", if you want to search for the file in the include_path, too.
See also readgzfile(), and gzopen().
Returns a string containing a single (uncompressed) character read from the file pointed to by zp. Returns FALSE on EOF (as does gzeof()).
The gz-file pointer must be valid, and must point to a file successfully opened by gzopen().
Returns a (uncompressed) string of up to length - 1 bytes read from the file pointed to by fp. Reading ends when length - 1 bytes have been read, on a newline, or on EOF (whichever comes first).
If an error occurs, returns FALSE.
The file pointer must be valid, and must point to a file successfully opened by gzopen().
Identical to gzgets(), except that gzgetss() attempts to strip any HTML and PHP tags from the text it reads.
You can use the optional third parameter to specify tags which should not be stripped.
Nota: Allowable_tags was added in PHP 3.0.13, PHP4B3.
See also gzgets(), gzopen(), and strip_tags().
This function takes data compressed by gzdeflate() and returns the original uncompressed data or FALSE on error. The function will return an error if the uncompressed data is more than 32768 times the length of the compressed input data or more than the optional parameter length.
See also gzcompress(). gzuncompress(), gzdeflate(), gzencode().
Opens a gzip (.gz) file for reading or writing. The mode parameter is as in fopen() ("rb" or "wb") but can also include a compression level ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for Huffman only compression as in "wb1h". (See the description of deflateInit2 in zlib.h for more information about the strategy parameter.)
gzopen() can be used to read a file which is not in gzip format; in this case gzread() will directly read from the file without decompression.
gzopen() returns a file pointer to the file opened, after that, everything you read from this file descriptor will be transparently decompressed and what you write gets compressed.
If the open fails, the function returns FALSE.
You can use the optional third parameter and set it to "1", if you want to search for the file in the include_path, too.
See also gzclose().
Reads to EOF on the given gz-file pointer and writes the (uncompressed) results to standard output.
If an error occurs, returns FALSE.
The file pointer must be valid, and must point to a file successfully opened by gzopen().
The gz-file is closed when gzpassthru() is done reading it (leaving zp useless).
gzputs() is an alias to gzwrite(), and is identical in every way.
gzread() reads up to length bytes from the gz-file pointer referenced by zp. Reading stops when length (uncompressed) bytes have been read or EOF is reached, whichever comes first.
// get contents of a gz-file into a string $filename = "/usr/local/something.txt.gz"; $zd = gzopen ($filename, "r"); $contents = gzread ($zd, 10000); gzclose ($zd); |
See also gzwrite(), gzopen(), gzgets(), gzgetss(), gzfile(), and gzpassthru().
Sets the file position indicator for zp to the beginning of the file stream.
If an error occurs, returns 0.
The file pointer must be valid, and must point to a file successfully opened by gzopen().
Sets the file position indicator for the file referenced by zp to offset bytes into the file stream. Equivalent to calling (in C) gzseek( zp, offset, SEEK_SET ).
If the file is opened for reading, this function is emulated but can be extremely slow. If the file is opened for writing, only forward seeks are supported; gzseek then compresses a sequence of zeroes up to the new starting position.
Upon success, returns 0; otherwise, returns -1. Note that seeking past EOF is not considered an error.
See also gztell() and gzrewind().
Returns the position of the file pointer referenced by zp; i.e., its offset into the file stream.
If an error occurs, returns FALSE.
The file pointer must be valid, and must point to a file successfully opened by gzopen().
See also gzopen(), gzseek() and gzrewind().
This function takes data compressed by gzcompress() and returns the original uncompressed data or FALSE on error. The function will return an error if the uncompressed data is more than 32768 times the length of the compressed input data or more than the optional parameter length.
See also gzdeflate(), gzinflate(), gzcompress(), gzencode().
gzwrite() writes the contents of string to the gz-file stream pointed to by zp. If the length argument is given, writing will stop after length (uncompressed) bytes have been written or the end of string is reached, whichever comes first.
gzwrite() returns the number of (uncompressed) bytes written to the gz-file stream pointed to by zp.
Note that if the length argument is given, then the magic_quotes_runtime configuration option will be ignored and no slashes will be stripped from string.
Reads a file, decompresses it and writes it to standard output.
readgzfile() can be used to read a file which is not in gzip format; in this case readgzfile() will directly read from the file without decompression.
Returns the number of (uncompressed) bytes read from the file. If an error occurs, FALSE is returned and unless the function was called as @readgzfile, an error message is printed.
The file filename will be opened from the filesystem and its contents written to standard output.
You can use the optional second parameter and set it to "1", if you want to search for the file in the include_path, too.
See also gzpassthru(), gzfile(), and gzopen().
Sometimes, PHP "as is" simply isn't enough. Although these cases are rare for the average user, professional applications will soon lead PHP to the edge of its capabilities, in terms of either speed or functionality. New functionality cannot always be implemented natively due to language restrictions and inconveniences that arise when having to carry around a huge library of default code appended to every single script, so another method needs to be found for overcoming these eventual lacks in PHP.
As soon as this point is reached, it's time to touch the heart of PHP and take a look at its core, the C code that makes PHP go.
"Extending PHP" is easier said than done. PHP has evolved to a full-fledged tool consisting of a few megabytes of source code, and to hack a system like this quite a few things have to be learned and considered. When structuring this chapter, we finally decided on the "learn by doing" approach. This is not the most scientific and professional approach, but the method that's the most fun and gives the best end results. In the following sections, you'll learn quickly how to get the most basic extensions to work almost instantly. After that, you'll learn about Zend's advanced API functionality. The alternative would have been to try to impart the functionality, design, tips, tricks, etc. as a whole, all at once, thus giving a complete look at the big picture before doing anything practical. Although this is the "better" method, as no dirty hacks have to be made, it can be very frustrating as well as energy- and time-consuming, which is why we've decided on the direct approach.
Note that even though this chapter tries to impart as much knowledge as possible about the inner workings of PHP, it's impossible to really give a complete guide to extending PHP that works 100% of the time in all cases. PHP is such a huge and complex package that its inner workings can only be understood if you make yourself familiar with it by practicing, so we encourage you to work with the source.
The name Zend refers to the language engine, PHP's core. The term PHP refers to the complete system as it appears from the outside. This might sound a bit confusing at first, but it's not that complicated (see Figura 24-1). To implement a Web script interpreter, you need three parts:
The interpreter part analyzes the input code, translates it, and executes it.
The functionality part implements the functionality of the language (its functions, etc.).
The interface part talks to the Web server, etc.
The following sections discuss where PHP can be extended and how it's done.
As shown in Figura 24-1 above, PHP can be extended primarily at three points: external modules, built-in modules, and the Zend engine. The following sections discuss these options.
External modules can be loaded at script runtime using the function dl(). This function loads a shared object from disk and makes its functionality available to the script to which it's being bound. After the script is terminated, the external module is discarded from memory. This method has both advantages and disadvantages, as described in the following table:
Advantages | Disadvantages |
External modules don't require recompiling of PHP. | The shared objects need to be loaded every time a script is being executed (every hit), which is very slow. |
The size of PHP remains small by "outsourcing" certain functionality. | External additional files clutter up the disk. |
Every script that wants to use an external module's functionality has to specifically include a call to dl(), or the extension tag in php.ini needs to be modified (which is not always a suitable solution). |
Third parties might consider using the extension tag in php.ini to create additional external modules to PHP. These external modules are completely detached from the main package, which is a very handy feature in commercial environments. Commercial distributors can simply ship disks or archives containing only their additional modules, without the need to create fixed and solid PHP binaries that don't allow other modules to be bound to them.
Built-in modules are compiled directly into PHP and carried around with every PHP process; their functionality is instantly available to every script that's being run. Like external modules, built-in modules have advantages and disadvantages, as described in the following table:
Built-in modules are best when you have a solid library of functions that remains relatively unchanged, requires better than poor-to-average performance, or is used frequently by many scripts on your site. The need to recompile PHP is quickly compensated by the benefit in speed and ease of use. However, built-in modules are not ideal when rapid development of small additions is required.Of course, extensions can also be implemented directly in the Zend engine. This strategy is good if you need a change in the language behavior or require special functions to be built directly into the language core. In general, however, modifications to the Zend engine should be avoided. Changes here result in incompatibilities with the rest of the world, and hardly anyone will ever adapt to specially patched Zend engines. Modifications can't be detached from the main PHP sources and are overridden with the next update using the "official" source repositories. Therefore, this method is generally considered bad practice and, due to its rarity, is not covered in this book.
Nota: Prior to working through the rest of this chapter, you should retrieve clean, unmodified source trees of your favorite Web server. We're working with Apache (available at http://www.apache.org/) and, of course, with PHP (available at http://www.php.net/ - does it need to be said?).
Make sure that you can compile a working PHP environment by yourself! We won't go into this issue here, however, as you should already have this most basic ability when studying this chapter.
Before we start discussing code issues, you should familiarize yourself with the source tree to be able to quickly navigate through PHP's files. This is a must-have ability to implement and debug extensions.
The following table describes the contents of the major directories.
Directory | Contents |
php4 | Main PHP source files and main header files; here you'll find all of PHP's API definitions, macros, etc. (important). Everything else is below this directory. |
php4/ext | Repository for dynamic and built-in modules; by default, these are the "official" PHP modules that have been integrated into the main source tree. From PHP 4.0, it's possible to compile these standard extensions as dynamic loadable modules (at least, those that support it). |
php4/main | This directory contains the main php macros and definitions. (important) |
php4/pear | Directory for the PHP Extension and Application Repository. This directory contains core PEAR files. |
php4/sapi | Contains the code for the different server abstraction layers. |
php4/TSRM | Location of the "Thread Safe Resource Manager" (TSRM) for Zend and PHP. |
php4/Zend | Location of the Zend Engine files; here you'll find all of Zend's API definitions, macros, etc. (important). |
Discussing all the files included in the PHP package is beyond the scope of this chapter. However, you should take a close look at the following files:
php4/main/php.h, located in the main PHP directory. This file contains most of PHP's macro and API definitions.
php4/Zend/zend.h, located in the main Zend directory. This file contains most of Zend's macros and definitions.
php4/Zend/zend_API.h, also located in the Zend directory, which defines Zend's API.
Zend is built using certain conventions; to avoid breaking its standards, you should follow the rules described in the following sections.
For almost every important task, Zend ships predefined macros that are extremely handy. The tables and figures in the following sections describe most of the basic functions, structures, and macros. The macro definitions can be found mainly in zend.h and zend_API.h. We suggest that you take a close look at these files after having studied this chapter. (Although you can go ahead and read them now, not everything will make sense to you yet.)
Resource management is a crucial issue, especially in server software. One of the most valuable resources is memory, and memory management should be handled with extreme care. Memory management has been partially abstracted in Zend, and you should stick to this abstraction for obvious reasons: Due to the abstraction, Zend gets full control over all memory allocations. Zend is able to determine whether a block is in use, automatically freeing unused blocks and blocks with lost references, and thus prevent memory leaks. The functions to be used are described in the following table:
Function | Description |
emalloc() | Serves as replacement for malloc(). |
efree() | Serves as replacement for free(). |
estrdup() | Serves as replacement for strdup(). |
estrndup() | Serves as replacement for strndup(). Faster than estrdup() and binary-safe. This is the recommended function to use if you know the string length prior to duplicating it. |
ecalloc() | Serves as replacement for calloc(). |
erealloc() | Serves as replacement for realloc(). |
Atenção |
To allocate resident memory that survives termination of the current script, you can use malloc() and free(). This should only be done with extreme care, however, and only in conjunction with demands of the Zend API; otherwise, you risk memory leaks. |
The following directory and file functions should be used in Zend modules. They behave exactly like their C counterparts, but provide virtual working directory support on the thread level.
Strings are handled a bit differently by the Zend engine than other values such as integers, Booleans, etc., which don't require additional memory allocation for storing their values. If you want to return a string from a function, introduce a new string variable to the symbol table, or do something similar, you have to make sure that the memory the string will be occupying has previously been allocated, using the aforementioned e*() functions for allocation. (This might not make much sense to you yet; just keep it somewhere in your head for now - we'll get back to it shortly.)
Complex types such as arrays and objects require different treatment. Zend features a single API for these types - they're stored using hash tables.
Nota: To reduce complexity in the following source examples, we're only working with simple types such as integers at first. A discussion about creating more advanced types follows later in this chapter.
PHP 4 features an automatic build system that's very flexible. All modules reside in a subdirectory of the ext directory. In addition to its own sources, each module consists of a config.m4 file, for extension configuration. (for example, see http://www.gnu.org/manual/m4/html_mono/m4.html)
All these stub files are generated automatically, along with .cvsignore, by a little shell script named ext_skel that resides in the ext directory. As argument it takes the name of the module that you want to create. The shell script then creates a directory of the same name, along with the appropriate stub files.
Step by step, the process looks like this:
:~/cvs/php4/ext:> ./ext_skel --extname=my_module Creating directory my_module Creating basic files: config.m4 .cvsignore my_module.c php_my_module.h CREDITS EXPERIMENTAL tests/001.phpt my_module.php [done]. To use your new extension, you will have to execute the following steps: 1. $ cd .. 2. $ vi ext/my_module/config.m4 3. $ ./buildconf 4. $ ./configure --[with|enable]-my_module 5. $ make 6. $ ./php -f ext/my_module/my_module.php 7. $ vi ext/my_module/my_module.c 8. $ make Repeat steps 3-6 until you are satisfied with ext/my_module/config.m4 and step 6 confirms that your module is compiled into PHP. Then, start writing code and repeat the last two steps as often as necessary. |
The default config.m4 shown in Exemplo 27-1 is a bit more complex:
Exemplo 27-1. The default config.m4.
|
If you're unfamiliar with M4 files (now is certainly a good time to get familiar), this might be a bit confusing at first; but it's actually quite easy.
Note: Everything prefixed with dnl is treated as a comment and is not parsed.
The config.m4 file is responsible for parsing the command-line options passed to configure at configuration time. This means that it has to check for required external files and do similar configuration and setup tasks.
The default file creates two configuration directives in the configure script: --with-my_module and --enable-my_module. Use the first option when referring external files (such as the --with-apache directive that refers to the Apache directory). Use the second option when the user simply has to decide whether to enable your extension. Regardless of which option you use, you should uncomment the other, unnecessary one; that is, if you're using --enable-my_module, you should remove support for --with-my_module, and vice versa.
By default, the config.m4 file created by ext_skel accepts both directives and automatically enables your extension. Enabling the extension is done by using the PHP_EXTENSION macro. To change the default behavior to include your module into the PHP binary when desired by the user (by explicitly specifying --enable-my_module or --with-my_module), change the test for $PHP_MY_MODULE to == "yes":
if test "$PHP_MY_MODULE" == "yes"; then dnl Action.. PHP_EXTENSION(my_module, $ext_shared) fi |
Note: Be sure to run buildconf every time you change config.m4!
We'll go into more details on the M4 macros available to your configuration scripts later in this chapter. For now, we'll simply use the default files.
We'll start with the creation of a very simple extension at first, which basically does nothing more than implement a function that returns the integer it receives as parameter. Exemplo 28-1 shows the source.
Exemplo 28-1. A simple extension.
|
This code contains a complete PHP module. We'll explain the source code in detail shortly, but first we'd like to discuss the build process. (This will allow the impatient to experiment before we dive into API discussions.)
Nota: The example source makes use of some features introduced with the Zend version used in PHP 4.1.0 and above, it won't compile with older PHP 4.0.x versions.
There are basically two ways to compile modules:
Use the provided "make" mechanism in the ext directory, which also allows building of dynamic loadable modules.
Compile the sources manually.
The second method is good for those who (for some reason) don't have the full PHP source tree available, don't have access to all files, or just like to juggle with their keyboard. These cases should be extremely rare, but for the sake of completeness we'll also describe this method.
Compiling Using Make. To compile the sample sources using the standard mechanism, copy all their subdirectories to the ext directory of your PHP source tree. Then run buildconf, which will create an updated configure script containing appropriate options for the new extension. By default, all the sample sources are disabled, so you don't have to fear breaking your build process.
After you run buildconf, configure --help shows the following additional modules:
--enable-array_experiments BOOK: Enables array experiments --enable-call_userland BOOK: Enables userland module --enable-cross_conversion BOOK: Enables cross-conversion module --enable-first_module BOOK: Enables first module --enable-infoprint BOOK: Enables infoprint module --enable-reference_test BOOK: Enables reference test module --enable-resource_test BOOK: Enables resource test module --enable-variable_creation BOOK: Enables variable-creation module |
The module shown earlier in Exemplo 28-1 can be enabled with --enable-first_module or --enable-first_module=yes.
Compiling Manually. To compile your modules manually, you need the following commands:
The command to compile the module simply instructs the compiler to generate position-independent code (-fpic shouldn't be omitted) and additionally defines the constant COMPILE_DL to tell the module code that it's compiled as a dynamically loadable module (the test module above checks for this; we'll discuss it shortly). After these options, it specifies a number of standard include paths that should be used as the minimal set to compile the source files.Note: All include paths in the example are relative to the directory ext. If you're compiling from another directory, change the pathnames accordingly. Required items are the PHP directory, the Zend directory, and (if necessary), the directory in which your module resides.
The link command is also a plain vanilla command instructing linkage as a dynamic module.
You can include optimization options in the compilation command, although these have been omitted in this example (but some are included in the makefile template described in an earlier section).
Note: Compiling and linking manually as a static module into the PHP binary involves very long instructions and thus is not discussed here. (It's not very efficient to type all those commands.)
Depending on the build process you selected, you should either end up with a new PHP binary to be linked into your Web server (or run as CGI), or with an .so (shared object) file. If you compiled the example file first_module.c as a shared object, your result file should be first_module.so. To use it, you first have to copy it to a place from which it's accessible to PHP. For a simple test procedure, you can copy it to your htdocs directory and try it with the source in Exemplo 29-1. If you compiled it into the PHP binary, omit the call to dl(), as the module's functionality is instantly available to your scripts.
Atenção |
For security reasons, you should not put your dynamic modules into publicly accessible directories. Even though it can be done and it simplifies testing, you should put them into a separate directory in production environments. |
Calling this PHP file in your Web browser should give you the output shown in Figura 29-1.
If required, the dynamic loadable module is loaded by calling the dl() function. This function looks for the specified shared object, loads it, and makes its functions available to PHP. The module exports the function first_module(), which accepts a single parameter, converts it to an integer, and returns the result of the conversion.
If you've gotten this far, congratulations! You just built your first extension to PHP.
Actually, not much troubleshooting can be done when compiling static or dynamic modules. The only problem that could arise is that the compiler will complain about missing definitions or something similar. In this case, make sure that all header files are available and that you specified their path correctly in the compilation command. To be sure that everything is located correctly, extract a clean PHP source tree and use the automatic build in the ext directory with the fresh files; this will guarantee a safe compilation environment. If this fails, try manual compilation.
PHP might also complain about missing functions in your module. (This shouldn't happen with the sample sources if you didn't modify them.) If the names of external functions you're trying to access from your module are misspelled, they'll remain as "unlinked symbols" in the symbol table. During dynamic loading and linkage by PHP, they won't resolve because of the typing errors - there are no corresponding symbols in the main binary. Look for incorrect declarations in your module file or incorrectly written external references. Note that this problem is specific to dynamic loadable modules; it doesn't occur with static modules. Errors in static modules show up at compile time.
Now that you've got a safe build environment and you're able to include the modules into PHP files, it's time to discuss how everything works.
All PHP modules follow a common structure:
Header file inclusions (to include all required macros, API definitions, etc.)
C declaration of exported functions (required to declare the Zend function block)
Declaration of the Zend function block
Declaration of the Zend module block
Implementation of get_module()
Implementation of all exported functions
The only header file you really have to include for your modules is php.h, located in the PHP directory. This file makes all macros and API definitions required to build new modules available to your code.
Tip: It's good practice to create a separate header file for your module that contains module-specific definitions. This header file should contain all the forward definitions for exported functions and include php.h. If you created your module using ext_skel you already have such a header file prepared.
To declare functions that are to be exported (i.e., made available to PHP as new native functions), Zend provides a set of macros. A sample declaration looks like this:
ZEND_FUNCTION ( my_function ); |
ZEND_FUNCTION declares a new C function that complies with Zend's internal API. This means that the function is of type void and accepts INTERNAL_FUNCTION_PARAMETERS (another macro) as parameters. Additionally, it prefixes the function name with zif. The immediately expanded version of the above definitions would look like this:
void zif_my_function ( INTERNAL_FUNCTION_PARAMETERS ); |
void zif_my_function( int ht , zval * return_value , zval * this_ptr , int return_value_used , zend_executor_globals * executor_globals ); |
Since the interpreter and executor core have been separated from the main PHP package, a second API defining macros and function sets has evolved: the Zend API. As the Zend API now handles quite a few of the responsibilities that previously belonged to PHP, a lot of PHP functions have been reduced to macros aliasing to calls into the Zend API. The recommended practice is to use the Zend API wherever possible, as the old API is only preserved for compatibility reasons. For example, the types zval and pval are identical. zval is Zend's definition; pval is PHP's definition (actually, pval is an alias for zval now). As the macro INTERNAL_FUNCTION_PARAMETERS is a Zend macro, the above declaration contains zval. When writing code, you should always use zval to conform to the new Zend API.
The parameter list of this declaration is very important; you should keep these parameters in mind (see Tabela 31-1 for descriptions).
Tabela 31-1. Zend's Parameters to Functions Called from PHP
Parameter | Description |
ht | The number of arguments passed to the Zend function. You should not touch this directly, but instead use ZEND_NUM_ARGS() to obtain the value. |
return_value | This variable is used to pass any return values of your function back to PHP. Access to this variable is best done using the predefined macros. For a description of these see below. |
this_ptr | Using this variable, you can gain access to the object in which your function is contained, if it's used within an object. Use the function getThis() to obtain this pointer. |
return_value_used | This flag indicates whether an eventual return value from this function will actually be used by the calling script. 0 indicates that the return value is not used; 1 indicates that the caller expects a return value. Evaluation of this flag can be done to verify correct usage of the function as well as speed optimizations in case returning a value requires expensive operations (for an example, see how array.c makes use of this). |
executor_globals | This variable points to global settings of the Zend engine. You'll find this useful when creating new variables, for example (more about this later). The executor globals can also be introduced to your function by using the macro TSRMLS_FETCH(). |
Now that you have declared the functions to be exported, you also have to introduce them to Zend. Introducing the list of functions is done by using an array of zend_function_entry. This array consecutively contains all functions that are to be made available externally, with the function's name as it should appear in PHP and its name as defined in the C source. Internally, zend_function_entry is defined as shown in Exemplo 31-1.
Exemplo 31-1. Internal declaration of zend_function_entry.
|
zend_function_entry firstmod_functions[] = { ZEND_FE(first_module, NULL) {NULL, NULL, NULL} }; |
Nota: You cannot use the predefined macros for the end marker, as these would try to refer to a function named "NULL"!
The macro ZEND_FE (short for 'Zend Function Entry') simply expands to a structure entry in zend_function_entry. Note that these macros introduce a special naming scheme to your functions - your C functions will be prefixed with zif_, meaning that ZEND_FE(first_module) will refer to a C function zif_first_module(). If you want to mix macro usage with hand-coded entries (not a good practice), keep this in mind.
Tip: Compilation errors that refer to functions named zif_*() relate to functions defined with ZEND_FE.
Tabela 31-2 shows a list of all the macros that you can use to define functions.
Tabela 31-2. Macros for Defining Functions
Macro Name | Description |
ZEND_FE(name, arg_types) | Defines a function entry of the name name in zend_function_entry. Requires a corresponding C function. arg_types needs to be set to NULL. This function uses automatic C function name generation by prefixing the PHP function name with zif_. For example, ZEND_FE("first_module", NULL) introduces a function first_module() to PHP and links it to the C function zif_first_module(). Use in conjunction with ZEND_FUNCTION. |
ZEND_NAMED_FE(php_name, name, arg_types) | Defines a function that will be available to PHP by the name php_name and links it to the corresponding C function name. arg_types needs to be set to NULL. Use this function if you don't want the automatic name prefixing introduced by ZEND_FE. Use in conjunction with ZEND_NAMED_FUNCTION. |
ZEND_FALIAS(name, alias, arg_types) | Defines an alias named alias for name. arg_types needs to be set to NULL. Doesn't require a corresponding C function; refers to the alias target instead. |
PHP_FE(name, arg_types) | Old PHP API equivalent of ZEND_FE. |
PHP_NAMED_FE(runtime_name, name, arg_types) | Old PHP API equivalent of ZEND_NAMED_FE. |
Note: You can't use ZEND_FE in conjunction with PHP_FUNCTION, or PHP_FE in conjunction with ZEND_FUNCTION. However, it's perfectly legal to mix ZEND_FE and ZEND_FUNCTION with PHP_FE and PHP_FUNCTION when staying with the same macro set for each function to be declared. But mixing is not recommended; instead, you're advised to use the ZEND_* macros only.
This block is stored in the structure zend_module_entry and contains all necessary information to describe the contents of this module to Zend. You can see the internal definition of this module in Exemplo 31-2.
Exemplo 31-2. Internal declaration of zend_module_entry.
|
In our example, this structure is implemented as follows:
zend_module_entry firstmod_module_entry = { STANDARD_MODULE_HEADER, "First Module", firstmod_functions, NULL, NULL, NULL, NULL, NULL, NO_VERSION_YET, STANDARD_MODULE_PROPERTIES, }; |
For reference purposes, you can find a list of the macros involved in declared startup and shutdown functions in Tabela 31-3. These are not used in our basic example yet, but will be demonstrated later on. You should make use of these macros to declare your startup and shutdown functions, as these require special arguments to be passed (INIT_FUNC_ARGS and SHUTDOWN_FUNC_ARGS), which are automatically included into the function declaration when using the predefined macros. If you declare your functions manually and the PHP developers decide that a change in the argument list is necessary, you'll have to change your module sources to remain compatible.
Tabela 31-3. Macros to Declare Startup and Shutdown Functions
Macro | Description |
ZEND_MINIT(module) | Declares a function for module startup. The generated name will be zend_minit_<module> (for example, zend_minit_first_module). Use in conjunction with ZEND_MINIT_FUNCTION. |
ZEND_MSHUTDOWN(module) | Declares a function for module shutdown. The generated name will be zend_mshutdown_<module> (for example, zend_mshutdown_first_module). Use in conjunction with ZEND_MSHUTDOWN_FUNCTION. |
ZEND_RINIT(module) | Declares a function for request startup. The generated name will be zend_rinit_<module> (for example, zend_rinit_first_module). Use in conjunction with ZEND_RINIT_FUNCTION. |
ZEND_RSHUTDOWN(module) | Declares a function for request shutdown. The generated name will be zend_rshutdown_<module> (for example, zend_rshutdown_first_module). Use in conjunction with ZEND_RSHUTDOWN_FUNCTION. |
ZEND_MINFO(module) | Declares a function for printing module information, used when phpinfo() is called. The generated name will be zend_info_<module> (for example, zend_info_first_module). Use in conjunction with ZEND_MINFO_FUNCTION. |
This function is special to all dynamic loadable modules. Take a look at the creation via the ZEND_GET_MODULE macro first:
#if COMPILE_DL_FIRSTMOD ZEND_GET_MODULE(firstmod) #endif |
The function implementation is surrounded by a conditional compilation statement. This is needed since the function get_module() is only required if your module is built as a dynamic extension. By specifying a definition of COMPILE_DL_FIRSTMOD in the compiler command (see above for a discussion of the compilation instructions required to build a dynamic extension), you can instruct your module whether you intend to build it as a dynamic extension or as a built-in module. If you want a built-in module, the implementation of get_module() is simply left out.
get_module() is called by Zend at load time of the module. You can think of it as being invoked by the dl() call in your script. Its purpose is to pass the module information block back to Zend in order to inform the engine about the module contents.
If you don't implement a get_module() function in your dynamic loadable module, Zend will compliment you with an error message when trying to access it.
Implementing the exported functions is the final step. The example function in first_module looks like this:
ZEND_FUNCTION(first_module) { long parameter; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", ¶meter) == FAILURE) { return; } RETURN_LONG(parameter); } |
After the declaration, code for checking and retrieving the function's arguments, argument conversion, and return value generation follows (more on this later).
That's it, basically - there's nothing more to implementing PHP modules. Built-in modules are structured similarly to dynamic modules, so, equipped with the information presented in the previous sections, you'll be able to fight the odds when encountering PHP module source files.
Now, in the following sections, read on about how to make use of PHP's internals to build powerful extensions.
One of the most important issues for language extensions is accepting and dealing with data passed via arguments. Most extensions are built to deal with specific input data (or require parameters to perform their specific actions), and function arguments are the only real way to exchange data between the PHP level and the C level. Of course, there's also the possibility of exchanging data using predefined global values (which is also discussed later), but this should be avoided by all means, as it's extremely bad practice.
PHP doesn't make use of any formal function declarations; this is why call syntax is always completely dynamic and never checked for errors. Checking for correct call syntax is left to the user code. For example, it's possible to call a function using only one argument at one time and four arguments the next time - both invocations are syntactically absolutely correct.
Since PHP doesn't have formal function definitions with support for call syntax checking, and since PHP features variable arguments, sometimes you need to find out with how many arguments your function has been called. You can use the ZEND_NUM_ARGS macro in this case. In previous versions of PHP, this macro retrieved the number of arguments with which the function has been called based on the function's hash table entry, ht, which is passed in the INTERNAL_FUNCTION_PARAMETERS list. As ht itself now contains the number of arguments that have been passed to the function, ZEND_NUM_ARGS has been stripped down to a dummy macro (see its definition in zend_API.h). But it's still good practice to use it, to remain compatible with future changes in the call interface. Note: The old PHP equivalent of this macro is ARG_COUNT.
The following code checks for the correct number of arguments:
if(ZEND_NUM_ARGS() != 2) WRONG_PARAM_COUNT; |
This macro prints a default error message and then returns to the caller. Its definition can also be found in zend_API.h and looks like this:
ZEND_API void wrong_param_count(void); #define WRONG_PARAM_COUNT { wrong_param_count(); return; } |
New parameter parsing API: This chapter documents the new Zend parameter parsing API introduced by Andrei Zmievski. It was introduced in the development stage between PHP 4.0.6 and 4.1.0 .
Parsing parameters is a very common operation and it may get a bit tedious. It would also be nice to have standardized error checking and error messages. Since PHP 4.1.0, there is a way to do just that by using the new parameter parsing API. It greatly simplifies the process of receiving parameteres, but it has a drawback in that it can't be used for functions that expect variable number of parameters. But since the vast majority of functions do not fall into those categories, this parsing API is recommended as the new standard way.
The prototype for parameter parsing function looks like this:
int zend_parse_parameters(int num_args TSRMLS_DC, char *type_spec, ...); |
zend_parse_parameters() also performs type conversions whenever possible, so that you always receive the data in the format you asked for. Any type of scalar can be converted to another one, but conversions between complex types (arrays, objects, and resources) and scalar types are not allowed.
If the parameters could be obtained successfully and there were no errors during type conversion, the function will return SUCCESS, otherwise it will return FAILURE. The function will output informative error messages, if the number of received parameters does not match the requested number, or if type conversion could not be performed.
Here are some sample error messages:
Warning - ini_get_all() requires at most 1 parameter, 2 given Warning - wddx_deserialize() expects parameter 1 to be string, array given |
Here is the full list of type specifiers:
l - long
d - double
s - string (with possible null bytes) and its length
b - boolean
r - resource, stored in zval*
a - array, stored in zval*
o - object (of any class), stored in zval*
O - object (of class specified by class entry), stored in zval*
z - the actual zval*
| - indicates that the remaining parameters are optional. The storage variables corresponding to these parameters should be initialized to default values by the extension, since they will not be touched by the parsing function if the parameters are not passed.
/ - the parsing function will call SEPARATE_ZVAL_IF_NOT_REF() on the parameter it follows, to provide a copy of the parameter, unless it's a reference.
! - the parameter it follows can be of specified type or NULL (only applies to a, o, O, r, and z). If NULL value is passed by the user, the storage pointer will be set to NULL.
The best way to illustrate the usage of this function is through examples:
/* Gets a long, a string and its length, and a zval. */ long l; char *s; int s_len; zval *param; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "lsz", &l, &s, &s_len, ¶m) == FAILURE) { return; } /* Gets an object of class specified by my_ce, and an optional double. */ zval *obj; double d = 0.5; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O|d", &obj, my_ce, &d) == FAILURE) { return; } /* Gets an object or null, and an array. If null is passed for object, obj will be set to NULL. */ zval *obj; zval *arr; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "O!a", &obj, &arr) == FAILURE) { return; } /* Gets a separated array. */ zval *arr; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a/", &arr) == FAILURE) { return; } /* Get only the first three parameters (useful for varargs functions). */ zval *z; zend_bool b; zval *r; if (zend_parse_parameters(3, "zbr!", &z, &b, &r) == FAILURE) { return; } |
Note that in the last example we pass 3 for the number of received parameters, instead of ZEND_NUM_ARGS(). What this lets us do is receive the least number of parameters if our function expects a variable number of them. Of course, if you want to operate on the rest of the parameters, you will have to use zend_get_parameters_array_ex() to obtain them.
The parsing function has an extended version that allows for an additional flags argument that controls its actions.
int zend_parse_parameters_ex(int flags, int num_args TSRMLS_DC, char *type_spec, ...); |
The only flag you can pass currently is ZEND_PARSE_PARAMS_QUIET, which instructs the function to not output any error messages during its operation. This is useful for functions that expect several sets of completely different arguments, but you will have to output your own error messages.
For example, here is how you would get either a set of three longs or a string:
long l1, l2, l3; char *s; if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, "lll", &l1, &l2, &l3) == SUCCESS) { /* manipulate longs */ } else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), "s", &s, &s_len) == SUCCESS) { /* manipulate string */ } else { php_error(E_WARNING, "%s() takes either three long values or a string as argument", get_active_function_name(TSRMLS_C)); return; } |
With all the abovementioned ways of receiving function parameters you should have a good handle on this process. For even more example, look through the source code for extensions that are shipped with PHP - they illustrate every conceivable situation.
Deprecated parameter parsing API: This API is deprecated and superseded by the new ZEND parameter parsing API.
After having checked the number of arguments, you need to get access to the arguments themselves. This is done with the help of zend_get_parameters_ex():
zval **parameter; if(zend_get_parameters_ex(1, ¶meter) != SUCCESS) WRONG_PARAM_COUNT; |
zend_get_parameters_ex() accepts at least two arguments. The first argument is the number of arguments to retrieve (which should match the number of arguments with which the function has been called; this is why it's important to check for correct call syntax). The second argument (and all following arguments) are pointers to pointers to pointers to zvals. (Confusing, isn't it?) All these pointers are required because Zend works internally with **zval; to adjust a local **zval in our function,zend_get_parameters_ex() requires a pointer to it.
The return value of zend_get_parameters_ex() can either be SUCCESS or FAILURE, indicating (unsurprisingly) success or failure of the argument processing. A failure is most likely related to an incorrect number of arguments being specified, in which case you should exit with WRONG_PARAM_COUNT.
To retrieve more than one argument, you can use a similar snippet:
zval **param1, **param2, **param3, **param4; if(zend_get_parameters_ex(4, ¶m1, ¶m2, ¶m3, ¶m4) != SUCCESS) WRONG_PARAM_COUNT; |
zend_get_parameters_ex() only checks whether you're trying to retrieve too many parameters. If the function is called with five arguments, but you're only retrieving three of them with zend_get_parameters_ex(), you won't get an error but will get the first three parameters instead. Subsequent calls of zend_get_parameters_ex() won't retrieve the remaining arguments, but will get the same arguments again.
If your function is meant to accept a variable number of arguments, the snippets just described are sometimes suboptimal solutions. You have to create a line calling zend_get_parameters_ex() for every possible number of arguments, which is often unsatisfying.
For this case, you can use the function zend_get_parameters_array_ex(), which accepts the number of parameters to retrieve and an array in which to store them:
zval **parameter_array[4]; /* get the number of arguments */ argument_count = ZEND_NUM_ARGS(); /* see if it satisfies our minimal request (2 arguments) */ /* and our maximal acceptance (4 arguments) */ if(argument_count < 2 || argument_count > 5) WRONG_PARAM_COUNT; /* argument count is correct, now retrieve arguments */ if(zend_get_parameters_array_ex(argument_count, parameter_array) != SUCCESS) WRONG_PARAM_COUNT; |
A very clever implementation of this can be found in the code handling PHP's fsockopen() located in ext/standard/fsock.c, as shown in Exemplo 32-1. Don't worry if you don't know all the functions used in this source yet; we'll get to them shortly.
Exemplo 32-1. PHP's implementation of variable arguments in fsockopen().
|
fsockopen() accepts two, three, four, or five parameters. After the obligatory variable declarations, the function checks for the correct range of arguments. Then it uses a fall-through mechanism in a switch() statement to deal with all arguments. The switch() statement starts with the maximum number of arguments being passed (five). After that, it automatically processes the case of four arguments being passed, then three, by omitting the otherwise obligatory break keyword in all stages. After having processed the last case, it exits the switch() statement and does the minimal argument processing needed if the function is invoked with only two arguments.
This multiple-stage type of processing, similar to a stairway, allows convenient processing of a variable number of arguments.
To access arguments, it's necessary for each argument to have a clearly defined type. Again, PHP's extremely dynamic nature introduces some quirks. Because PHP never does any kind of type checking, it's possible for a caller to pass any kind of data to your functions, whether you want it or not. If you expect an integer, for example, the caller might pass an array, and vice versa - PHP simply won't notice.
To work around this, you have to use a set of API functions to force a type conversion on every argument that's being passed (see Tabela 32-1).
Note: All conversion functions expect a **zval as parameter.
Tabela 32-1. Argument Conversion Functions
Function | Description |
convert_to_boolean_ex() | Forces conversion to a Boolean type. Boolean values remain untouched. Longs, doubles, and strings containing 0 as well as NULL values will result in Boolean 0 (FALSE). Arrays and objects are converted based on the number of entries or properties, respectively, that they have. Empty arrays and objects are converted to FALSE; otherwise, to TRUE. All other values result in a Boolean 1 (TRUE). |
convert_to_long_ex() | Forces conversion to a long, the default integer type. NULL values, Booleans, resources, and of course longs remain untouched. Doubles are truncated. Strings containing an integer are converted to their corresponding numeric representation, otherwise resulting in 0. Arrays and objects are converted to 0 if empty, 1 otherwise. |
convert_to_double_ex() | Forces conversion to a double, the default floating-point type. NULL values, Booleans, resources, longs, and of course doubles remain untouched. Strings containing a number are converted to their corresponding numeric representation, otherwise resulting in 0.0. Arrays and objects are converted to 0.0 if empty, 1.0 otherwise. |
convert_to_string_ex() | Forces conversion to a string. Strings remain untouched. NULL values are converted to an empty string. Booleans containing TRUE are converted to "1", otherwise resulting in an empty string. Longs and doubles are converted to their corresponding string representation. Arrays are converted to the string "Array" and objects to the string "Object". |
convert_to_array_ex(value) | Forces conversion to an array. Arrays remain untouched. Objects are converted to an array by assigning all their properties to the array table. All property names are used as keys, property contents as values. NULL values are converted to an empty array. All other values are converted to an array that contains the specific source value in the element with the key 0. |
convert_to_object_ex(value) | Forces conversion to an object. Objects remain untouched. NULL values are converted to an empty object. Arrays are converted to objects by introducing their keys as properties into the objects and their values as corresponding property contents in the object. All other types result in an object with the property scalar , having the corresponding source value as content. |
convert_to_null_ex(value) | Forces the type to become a NULL value, meaning empty. |
Nota: You can find a demonstration of the behavior in cross_conversion.php on the accompanying CD-ROM. Figura 32-2 shows the output.
Using these functions on your arguments will ensure type safety for all data that's passed to you. If the supplied type doesn't match the required type, PHP forces dummy contents on the resulting value (empty strings, arrays, or objects, 0 for numeric values, FALSE for Booleans) to ensure a defined state.
Following is a quote from the sample module discussed previously, which makes use of the conversion functions:
zval **parameter; if((ZEND_NUM_ARGS() != 1) || (zend_get_parameters_ex(1, ¶meter) != SUCCESS)) { WRONG_PARAM_COUNT; } convert_to_long_ex(parameter); RETURN_LONG(Z_LVAL_P(parameter)); |
Exemplo 32-2. PHP/Zend zval type definition.
|
Actually, pval (defined in php.h) is only an alias of zval (defined in zend.h), which in turn refers to _zval_struct. This is a most interesting structure. _zval_struct is the "master" structure, containing the value structure, type, and reference information. The substructure zvalue_value is a union that contains the variable's contents. Depending on the variable's type, you'll have to access different members of this union. For a description of both structures, see Tabela 32-2, Tabela 32-3 and Tabela 32-4.
Tabela 32-2. Zend zval Structure
Entry | Description |
value | Union containing this variable's contents. See Tabela 32-3 for a description. |
type | Contains this variable's type. For a list of available types, see Tabela 32-4. |
is_ref | 0 means that this variable is not a reference; 1 means that this variable is a reference to another variable. |
refcount | The number of references that exist for this variable. For every new reference to the value stored in this variable, this counter is increased by 1. For every lost reference, this counter is decreased by 1. When the reference counter reaches 0, no references exist to this value anymore, which causes automatic freeing of the value. |
Tabela 32-3. Zend zvalue_value Structure
Entry | Description |
lval | Use this property if the variable is of the type IS_LONG, IS_BOOLEAN, or IS_RESOURCE. |
dval | Use this property if the variable is of the type IS_DOUBLE. |
str | This structure can be used to access variables of the type IS_STRING. The member len contains the string length; the member val points to the string itself. Zend uses C strings; thus, the string length contains a trailing 0x00. |
ht | This entry points to the variable's hash table entry if the variable is an array. |
obj | Use this property if the variable is of the type IS_OBJECT. |
Tabela 32-4. Zend Variable Type Constants
Constant | Description |
IS_NULL | Denotes a NULL (empty) value. |
IS_LONG | A long (integer) value. |
IS_DOUBLE | A double (floating point) value. |
IS_STRING | A string. |
IS_ARRAY | Denotes an array. |
IS_OBJECT | An object. |
IS_BOOL | A Boolean value. |
IS_RESOURCE | A resource (for a discussion of resources, see the appropriate section below). |
IS_CONSTANT | A constant (defined) value. |
To access a long you access zval.value.lval, to access a double you use zval.value.dval, and so on. Because all values are stored in a union, trying to access data with incorrect union members results in meaningless output.
Accessing arrays and objects is a bit more complicated and is discussed later.
If your function accepts arguments passed by reference that you intend to modify, you need to take some precautions.
What we didn't say yet is that under the circumstances presented so far, you don't have write access to any zval containers designating function parameters that have been passed to you. Of course, you can change any zval containers that you created within your function, but you mustn't change any zvals that refer to Zend-internal data!
We've only discussed the so-called *_ex() API so far. You may have noticed that the API functions we've used are called zend_get_parameters_ex() instead of zend_get_parameters(), convert_to_long_ex() instead of convert_to_long(), etc. The *_ex() functions form the so-called new "extended" Zend API. They give a minor speed increase over the old API, but as a tradeoff are only meant for providing read-only access.
Because Zend works internally with references, different variables may reference the same value. Write access to a zval container requires this container to contain an isolated value, meaning a value that's not referenced by any other containers. If a zval container were referenced by other containers and you changed the referenced zval, you would automatically change the contents of the other containers referencing this zval (because they'd simply point to the changed value and thus change their own value as well).
zend_get_parameters_ex() doesn't care about this situation, but simply returns a pointer to the desired zval containers, whether they consist of references or not. Its corresponding function in the traditional API, zend_get_parameters(), immediately checks for referenced values. If it finds a reference, it creates a new, isolated zval container; copies the referenced data into this newly allocated space; and then returns a pointer to the new, isolated value.
This action is called zval separation (or pval separation). Because the *_ex() API doesn't perform zval separation, it's considerably faster, while at the same time disabling write access.
To change parameters, however, write access is required. Zend deals with this situation in a special way: Whenever a parameter to a function is passed by reference, it performs automatic zval separation. This means that whenever you're calling a function like this in PHP, Zend will automatically ensure that $parameter is being passed as an isolated value, rendering it to a write-safe state:
my_function(&$parameter); |
But this is not the case with regular parameters! All other parameters that are not passed by reference are in a read-only state.
This requires you to make sure that you're really working with a reference - otherwise you might produce unwanted results. To check for a parameter being passed by reference, you can use the macro PZVAL_IS_REF. This macro accepts a zval* to check if it is a reference or not. Examples are given in in Exemplo 32-3.
Exemplo 32-3. Testing for referenced parameter passing.
|
You might run into a situation in which you need write access to a parameter that's retrieved with zend_get_parameters_ex() but not passed by reference. For this case, you can use the macro SEPARATE_ZVAL, which does a zval separation on the provided container. The newly generated zval is detached from internal data and has only a local scope, meaning that it can be changed or destroyed without implying global changes in the script context:
zval **parameter; /* retrieve parameter */ zend_get_parameters_ex(1, ¶meter); /* at this stage, <parameter> still is connected */ /* to Zend's internal data buffers */ /* make <parameter> write-safe */ SEPARATE_ZVAL(parameter); /* now we can safely modify <parameter> */ /* without implying global changes */ |
Note: As you can easily work around the lack of write access in the "traditional" API (with zend_get_parameters() and so on), this API seems to be obsolete, and is not discussed further in this chapter.
When exchanging data from your own extensions with PHP scripts, one of the most important issues is the creation of variables. This section shows you how to deal with the variable types that PHP supports.
To create new variables that can be seen "from the outside" by the executing script, you need to allocate a new zval container, fill this container with meaningful values, and then introduce it to Zend's internal symbol table. This basic process is common to all variable creations:
zval *new_variable; /* allocate and initialize new container */ MAKE_STD_ZVAL(new_variable); /* set type and variable contents here, see the following sections */ /* introduce this variable by the name "new_variable_name" into the symbol table */ ZEND_SET_SYMBOL(EG(active_symbol_table), "new_variable_name", new_variable); /* the variable is now accessible to the script by using $new_variable_name */ |
The macro MAKE_STD_ZVAL allocates a new zval container using ALLOC_ZVAL and initializes it using INIT_ZVAL. As implemented in Zend at the time of this writing, initializing means setting the reference count to 1 and clearing the is_ref flag, but this process could be extended later - this is why it's a good idea to keep using MAKE_STD_ZVAL instead of only using ALLOC_ZVAL. If you want to optimize for speed (and you don't have to explicitly initialize the zval container here), you can use ALLOC_ZVAL, but this isn't recommended because it doesn't ensure data integrity.
ZEND_SET_SYMBOL takes care of introducing the new variable to Zend's symbol table. This macro checks whether the value already exists in the symbol table and converts the new symbol to a reference if so (with automatic deallocation of the old zval container). This is the preferred method if speed is not a crucial issue and you'd like to keep memory usage low.
Note that ZEND_SET_SYMBOL makes use of the Zend executor globals via the macro EG. By specifying EG(active_symbol_table), you get access to the currently active symbol table, dealing with the active, local scope. The local scope may differ depending on whether the function was invoked from within a function.
If you need to optimize for speed and don't care about optimal memory usage, you can omit the check for an existing variable with the same value and instead force insertion into the symbol table by using zend_hash_update():
zval *new_variable; /* allocate and initialize new container */ MAKE_STD_ZVAL(new_variable); /* set type and variable contents here, see the following sections */ /* introduce this variable by the name "new_variable_name" into the symbol table */ zend_hash_update( EG(active_symbol_table), "new_variable_name", strlen("new_variable_name") + 1, &new_variable, sizeof(zval *), NULL ); |
The variables generated with the snippet above will always be of local scope, so they reside in the context in which the function has been called. To create new variables in the global scope, use the same method but refer to another symbol table:
zval *new_variable; // allocate and initialize new container MAKE_STD_ZVAL(new_variable); // // set type and variable contents here // // introduce this variable by the name "new_variable_name" into the global symbol table ZEND_SET_SYMBOL(&EG(symbol_table), "new_variable_name", new_variable); |
Note: The active_symbol_table variable is a pointer, but symbol_table is not. This is why you have to use EG(active_symbol_table) and &EG(symbol_table) as parameters to ZEND_SET_SYMBOL - it requires a pointer.
Similarly, to get a more efficient version, you can hardcode the symbol table update:
zval *new_variable; // allocate and initialize new container MAKE_STD_ZVAL(new_variable); // // set type and variable contents here // // introduce this variable by the name "new_variable_name" into the global symbol table zend_hash_update( &EG(symbol_table), "new_variable_name", strlen("new_variable_name") + 1, &new_variable, sizeof(zval *), NULL ); |
Note: You can see that the global variable is actually not accessible from within the function. This is because it's not imported into the local scope using global $global_variable; in the PHP source.
Exemplo 33-1. Creating variables with different scopes.
|
Now let's get to the assignment of data to variables, starting with longs. Longs are PHP's integers and are very simple to store. Looking at the zval.value container structure discussed earlier in this chapter, you can see that the long data type is directly contained in the union, namely in the lval field. The corresponding type value for longs is IS_LONG (see Exemplo 33-2).
zval *new_long; MAKE_STD_ZVAL(new_long); ZVAL_LONG(new_long, 10); |
Doubles are PHP's floats and are as easy to assign as longs, because their value is also contained directly in the union. The member in the zval.value container is dval; the corresponding type is IS_DOUBLE.
zval *new_double; MAKE_STD_ZVAL(new_double); new_double->type = IS_DOUBLE; new_double->value.dval = 3.45; |
zval *new_double; MAKE_STD_ZVAL(new_double); ZVAL_DOUBLE(new_double, 3.45); |
Strings need slightly more effort. As mentioned earlier, all strings that will be associated with Zend's internal data structures need to be allocated using Zend's own memory-management functions. Referencing of static strings or strings allocated with standard routines is not allowed. To assign strings, you have to access the structure str in the zval.value container. The corresponding type is IS_STRING:
zval *new_string; char *string_contents = "This is a new string variable"; MAKE_STD_ZVAL(new_string); new_string->type = IS_STRING; new_string->value.str.len = strlen(string_contents); new_string->value.str.val = estrdup(string_contents); |
zval *new_string; char *string_contents = "This is a new string variable"; MAKE_STD_ZVAL(new_string); ZVAL_STRING(new_string, string_contents, 1); |
If you want to truncate the string at a certain position or you already know its length, you can use ZVAL_STRINGL(zval, string, length, duplicate), which accepts an explicit string length to be set for the new string. This macro is faster than ZVAL_STRING and also binary-safe.
To create empty strings, set the string length to 0 and use empty_string as contents:
new_string->type = IS_STRING; new_string->value.str.len = 0; new_string->value.str.val = empty_string; |
MAKE_STD_ZVAL(new_string); ZVAL_EMPTY_STRING(new_string); |
Booleans are created just like longs, but have the type IS_BOOL. Allowed values in lval are 0 and 1:
zval *new_bool; MAKE_STD_ZVAL(new_bool); new_bool->type = IS_BOOL; new_bool->value.lval = 1; |
Arrays are stored using Zend's internal hash tables, which can be accessed using the zend_hash_*() API. For every array that you want to create, you need a new hash table handle, which will be stored in the ht member of the zval.value container.
There's a whole API solely for the creation of arrays, which is extremely handy. To start a new array, you call array_init().
zval *new_array; MAKE_STD_ZVAL(new_array); array_init(new_array); |
To add new elements to the array, you can use numerous functions, depending on what you want to do. Tabela 33-1, Tabela 33-2 and Tabela 33-3 describe these functions. All functions return FAILURE on failure and SUCCESS on success.
Tabela 33-1. Zend's API for Associative Arrays
Function | Description |
add_assoc_long(zval *array, char *key, long n);() | Adds an element of type long. |
add_assoc_unset(zval *array, char *key);() | Adds an unset element. |
add_assoc_bool(zval *array, char *key, int b);() | Adds a Boolean element. |
add_assoc_resource(zval *array, char *key, int r);() | Adds a resource to the array. |
add_assoc_double(zval *array, char *key, double d);() | Adds a floating-point value. |
add_assoc_string(zval *array, char *key, char *str, int duplicate);() | Adds a string to the array. The flag duplicate specifies whether the string contents have to be copied to Zend internal memory. |
add_assoc_stringl(zval *array, char *key, char *str, uint length, int duplicate); () | Adds a string with the desired length length to the array. Otherwise, behaves like add_assoc_string(). |
add_assoc_zval(zval *array, char *key, zval *value);() | Adds a zval to the array. Useful for adding other arrays, objects, streams, etc... |
Tabela 33-2. Zend's API for Indexed Arrays, Part 1
Function | Description |
add_index_long(zval *array, uint idx, long n);() | Adds an element of type long. |
add_index_unset(zval *array, uint idx);() | Adds an unset element. |
add_index_bool(zval *array, uint idx, int b);() | Adds a Boolean element. |
add_index_resource(zval *array, uint idx, int r);() | Adds a resource to the array. |
add_index_double(zval *array, uint idx, double d);() | Adds a floating-point value. |
add_index_string(zval *array, uint idx, char *str, int duplicate);() | Adds a string to the array. The flag duplicate specifies whether the string contents have to be copied to Zend internal memory. |
add_index_stringl(zval *array, uint idx, char *str, uint length, int duplicate);() | Adds a string with the desired length length to the array. This function is faster and binary-safe. Otherwise, behaves like add_index_string()(). |
add_index_zval(zval *array, uint idx, zval *value);() | Adds a zval to the array. Useful for adding other arrays, objects, streams, etc... |
Tabela 33-3. Zend's API for Indexed Arrays, Part 2
Function | Description |
add_next_index_long(zval *array, long n);() | Adds an element of type long. |
add_next_index_unset(zval *array);() | Adds an unset element. |
add_next_index_bool(zval *array, int b);() | Adds a Boolean element. |
add_next_index_resource(zval *array, int r);() | Adds a resource to the array. |
add_next_index_double(zval *array, double d);() | Adds a floating-point value. |
add_next_index_string(zval *array, char *str, int duplicate);() | Adds a string to the array. The flag duplicate specifies whether the string contents have to be copied to Zend internal memory. |
add_next_index_stringl(zval *array, char *str, uint length, int duplicate);() | Adds a string with the desired length length to the array. This function is faster and binary-safe. Otherwise, behaves like add_index_string()(). |
add_next_index_zval(zval *array, zval *value);() | Adds a zval to the array. Useful for adding other arrays, objects, streams, etc... |
All these functions provide a handy abstraction to Zend's internal hash API. Of course, you can also use the hash functions directly - for example, if you already have a zval container allocated that you want to insert into an array. This is done using zend_hash_update()() for associative arrays (see Exemplo 33-3) and zend_hash_index_update() for indexed arrays (see Exemplo 33-4):
Exemplo 33-3. Adding an element to an associative array.
|
Exemplo 33-4. Adding an element to an indexed array.
|
To emulate the functionality of add_next_index_*(), you can use this:
zend_hash_next_index_insert(ht, zval **new_element, sizeof(zval *), NULL) |
Note: To return arrays from a function, use array_init() and all following actions on the predefined variable return_value (given as argument to your exported function; see the earlier discussion of the call interface). You do not have to use MAKE_STD_ZVAL on this.
Tip: To avoid having to write new_array->value.ht every time, you can use HASH_OF(new_array), which is also recommended for compatibility and style reasons.
Since objects can be converted to arrays (and vice versa), you might have already guessed that they have a lot of similarities to arrays in PHP. Objects are maintained with the same hash functions, but there's a different API for creating them.
To initialize an object, you use the function object_init():
zval *new_object; MAKE_STD_ZVAL(new_object); if(object_init(new_object) != SUCCESS) { // do error handling here } |
Tabela 33-4. Zend's API for Object Creation
Function | Description |
add_property_long(zval *object, char *key, long l);() | Adds a long to the object. |
add_property_unset(zval *object, char *key);() | Adds an unset property to the object. |
add_property_bool(zval *object, char *key, int b);() | Adds a Boolean to the object. |
add_property_resource(zval *object, char *key, long r);() | Adds a resource to the object. |
add_property_double(zval *object, char *key, double d);() | Adds a double to the object. |
add_property_string(zval *object, char *key, char *str, int duplicate);() | Adds a string to the object. |
add_property_stringl(zval *object, char *key, char *str, uint length, int duplicate);() | Adds a string of the specified length to the object. This function is faster than add_property_string() and also binary-safe. |
add_property_zval(zval *obect, char *key, zval *container):() | Adds a zval container to the object. This is useful if you have to add properties which aren't simple types like integers or strings but arrays or other objects. |
Resources are a special kind of data type in PHP. The term resources doesn't really refer to any special kind of data, but to an abstraction method for maintaining any kind of information. Resources are kept in a special resource list within Zend. Each entry in the list has a correspondending type definition that denotes the kind of resource to which it refers. Zend then internally manages all references to this resource. Access to a resource is never possible directly - only via a provided API. As soon as all references to a specific resource are lost, a corresponding shutdown function is called.
For example, resources are used to store database links and file descriptors. The de facto standard implementation can be found in the MySQL module, but other modules such as the Oracle module also make use of resources.
Nota: In fact, a resource can be a pointer to anything you need to handle in your functions (e.g. pointer to a structure) and the user only has to pass a single resource variable to your function.
To create a new resource you need to register a resource destruction handler for it. Since you can store any kind of data as a resource, Zend needs to know how to free this resource if its not longer needed. This works by registering your own resource destruction handler to Zend which in turn gets called by Zend whenever your resource can be freed (whether manually or automatically). Registering your resource handler within Zend returns you the resource type handle for that resource. This handle is needed whenever you want to access a resource of this type later and is most of time stored in a global static variable within your extension. There is no need to worry about thread safety here because you only register your resource handler once during module initialization.
The Zend function to register your resource handler is defined as:
ZEND_API int zend_register_list_destructors_ex(rsrc_dtor_func_t ld, rsrc_dtor_func_t pld, char *type_name, int module_number); |
There are two different kinds of resource destruction handlers you can pass to this function: a handler for normal resources and a handler for persistent resources. Persistent resources are for example used for database connection. When registering a resource, either of these handlers must be given. For the other handler just pass NULL.
zend_register_list_destructors_ex() accepts the following parameters:
ld | Normal resource destruction handler callback |
pld | Pesistent resource destruction handler callback |
type_name | A string specifying the name of your resource. It's always a good thing to specify an unique name within PHP for the resource type so when the user for example calls var_dump($resource); he also gets the name of the resource. |
module_number | The module_number is automatically available in your PHP_MINIT_FUNCTION function and therefore you just pass it over. |
The resource destruction handler (either normal or persistent resources) has the following prototype:
void resource_destruction_handler(zend_rsrc_list_entry *rsrc TSRMLS_DC); |
typedef struct _zend_rsrc_list_entry { void *ptr; int type; int refcount; } zend_rsrc_list_entry; |
Now we know how to start things, we define our own resource we want register within Zend. It is only a simple structure with two integer members:
typedef struct { int resource_link; int resource_type; } my_resource; |
void my_destruction_handler(zend_rsrc_list_entry *rsrc TSRMLS_DC) { // You most likely cast the void pointer to your structure type my_resource *my_rsrc = (my_resource *) rsrc->ptr; // Now do whatever needs to be done with you resource. Closing // Files, Sockets, freeing additional memory, etc. // Also, don't forget to actually free the memory for your resource too! do_whatever_needs_to_be_done_with_the_resource(my_rsrc); } |
Nota: One important thing to mention: If your resource is a rather complex structure which also contains pointers to memory you allocated during runtime you have to free them before freeing the resource itself!
Now that we have defined
what our resource is and
our resource destruction handler
create a global variable within the extension holding the resource ID so it can be accessed from every function which needs it
define the resource name
write the resource destruction handler
and finally register the handler
// Somewhere in your extension, define the variable for your registered resources. // If you wondered what 'le' stands for: it simply means 'list entry'. static int le_myresource; // It's nice to define your resource name somewhere #define le_myresource_name "My type of resource" [...] // Now actually define our resource destruction handler void my_destruction_handler(zend_rsrc_list_entry *rsrc TSRMLS_DC) { my_resource *my_rsrc = (my_resource *) rsrc->ptr; do_whatever_needs_to_be_done_with_the_resource(my_rsrc); } [...] PHP_MINIT_FUNCTION(my_extension) { // Note that 'module_number' is already provided through the // PHP_MINIT_FUNCTION() function definition. le_myresource = zend_register_resource_destructors_ex(my_destruction_handler, NULL, le_myresource_name, module_number); // You can register additional resources, initialize // your global vars, constants, whatever. } |
To actually register a new resource you use can either use the zend_register_resource() function or the ZEND_REGISTER_RESOURE() macro, both defined in zend_list.h . Although the arguments for both map 1:1 it's a good idea to always use macros to be upwards compatible:
int ZEND_REGISTER_RESOURCE(zval *rsrc_result, void *rsrc_pointer, int rsrc_type); |
rsrc_result | This is an already initialized zval * container. |
rsrc_pointer | Your resource pointer you want to store. |
rsrc_type | The type which you received when you registered the resource destruction handler. If you followed the naming scheme this would be le_myresource. |
What is really going on when you register a new resource is it gets inserted in an internal list in Zend and the result is just stored in the given zval * container:
rsrc_id = zend_list_insert(rsrc_pointer, rsrc_type); if (rsrc_result) { rsrc_result->value.lval = rsrc_id; rsrc_result->type = IS_RESOURCE; } return rsrc_id; |
RETURN_RESOURCE(rsrc_id) |
Nota: It is common practice that if you want to return the resource immidiately to the user you specify the return_value as the zval * container.
Zend now keeps track of all references to this resource. As soon as all references to the resource are lost, the destructor that you previously registered for this resource is called. The nice thing about this setup is that you don't have to worry about memory leakages introduced by allocations in your module - just register all memory allocations that your calling script will refer to as resources. As soon as the script decides it doesn't need them anymore, Zend will find out and tell you.
Now that the user got his resource, at some point he is passing it back to one of your functions. The value.lval inside the zval * container contains the key to your resource and thus can be used to fetch the resource with the following macro: ZEND_FETCH_RESOURCE:
ZEND_FETCH_RESOURCE(rsrc, rsrc_type, rsrc_id, default_rsrc_id, resource_type_name, resource_type) |
rsrc | This is your pointer which will point to your previously registered resource. |
rsrc_type | This is the typecast argument for your pointer, e.g. myresource *. |
rsrc_id | This is the address of the zval *container the user passed to your function, e.g. &z_resource if zval *z_resource is given. |
default_rsrc_id | This integer specifies the default resource ID if no resource could be fetched or -1. |
resource_type_name | This is the name of the requested resource. It's a string and is used when the resource can't be found or is invalid to form a meaningful error message. |
resource_type | The resource_type you got back when registering the resource destruction handler. In our example this was le_myresource. |
To force removal of a resource from the list, use the function zend_list_delete(). You can also force the reference count to increase if you know that you're creating another reference for a previously allocated value (for example, if you're automatically reusing a default database link). For this case, use the function zend_list_addref(). To search for previously allocated resource entries, use zend_list_find(). The complete API can be found in zend_list.h.
In addition to the macros discussed earlier, a few macros allow easy creation of simple global variables. These are nice to know in case you want to introduce global flags, for example. This is somewhat bad practice, but Table Tabela 33-5 describes macros that do exactly this task. They don't need any zval allocation; you simply have to supply a variable name and value.
Tabela 33-5. Macros for Global Variable Creation
Macro | Description |
SET_VAR_STRING(name, value) | Creates a new string. |
SET_VAR_STRINGL(name, value, length) | Creates a new string of the specified length. This macro is faster than SET_VAR_STRING and also binary-safe. |
SET_VAR_LONG(name, value) | Creates a new long. |
SET_VAR_DOUBLE(name, value) | Creates a new double. |
Zend supports the creation of true constants (as opposed to regular variables). Constants are accessed without the typical dollar sign ($) prefix and are available in all scopes. Examples include TRUE and FALSE, to name just two.
To create your own constants, you can use the macros in Tabela 33-6. All the macros create a constant with the specified name and value.
You can also specify flags for each constant:
CONST_CS - This constant's name is to be treated as case sensitive.
CONST_PERSISTENT - This constant is persistent and won't be "forgotten" when the current process carrying this constant shuts down.
// register a new constant of type "long" REGISTER_LONG_CONSTANT("NEW_MEANINGFUL_CONSTANT", 324, CONST_CS | CONST_PERSISTENT); |
Tabela 33-6. Macros for Creating Constants
Macro | Description |
REGISTER_LONG_CONSTANT(name, value, flags) REGISTER_MAIN_LONG_CONSTANT(name, value, flags) | Registers a new constant of type long. |
REGISTER_DOUBLE_CONSTANT(name, value, flags) REGISTER_MAIN_DOUBLE_CONSTANT(name, value, flags) | Registers a new constant of type double. |
REGISTER_STRING_CONSTANT(name, value, flags) REGISTER_MAIN_STRING_CONSTANT(name, value, flags) | Registers a new constant of type string. The specified string must reside in Zend's internal memory. |
REGISTER_STRINGL_CONSTANT(name, value, length, flags) REGISTER_MAIN_STRINGL_CONSTANT(name, value, length, flags) | Registers a new constant of type string. The string length is explicitly set to length. The specified string must reside in Zend's internal memory. |
Sooner or later, you may need to assign the contents of one zval container to another. This is easier said than done, since the zval container doesn't contain only type information, but also references to places in Zend's internal data. For example, depending on their size, arrays and objects may be nested with lots of hash table entries. By assigning one zval to another, you avoid duplicating the hash table entries, using only a reference to them (at most).
To copy this complex kind of data, use the copy constructor. Copy constructors are typically defined in languages that support operator overloading, with the express purpose of copying complex types. If you define an object in such a language, you have the possibility of overloading the "=" operator, which is usually responsible for assigning the contents of the lvalue (result of the evaluation of the left side of the operator) to the rvalue (same for the right side).
Overloading means assigning a different meaning to this operator, and is usually used to assign a function call to an operator. Whenever this operator would be used on such an object in a program, this function would be called with the lvalue and rvalue as parameters. Equipped with that information, it can perform the operation it intends the "=" operator to have (usually an extended form of copying).
This same form of "extended copying" is also necessary for PHP's zval containers. Again, in the case of an array, this extended copying would imply re-creation of all hash table entries relating to this array. For strings, proper memory allocation would have to be assured, and so on.
Zend ships with such a function, called zend_copy_ctor() (the previous PHP equivalent was pval_copy_constructor()).
A most useful demonstration is a function that accepts a complex type as argument, modifies it, and then returns the argument:
zval *parameter; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", ¶meter) == FAILURE) return; } // do modifications to the parameter here // now we want to return the modified container: *return_value == *parameter; zval_copy_ctor(return_value); |
The first part of the function is plain-vanilla argument retrieval. After the (left out) modifications, however, it gets interesting: The container of parameter is assigned to the (predefined) return_value container. Now, in order to effectively duplicate its contents, the copy constructor is called. The copy constructor works directly with the supplied argument, and the standard return values are FAILURE on failure and SUCCESS on success.
If you omit the call to the copy constructor in this example, both parameter and return_value would point to the same internal data, meaning that return_value would be an illegal additional reference to the same data structures. Whenever changes occurred in the data that parameter points to, return_value might be affected. Thus, in order to create separate copies, the copy constructor must be used.
The copy constructor's counterpart in the Zend API, the destructor zval_dtor(), does the opposite of the constructor.
Returning values from your functions to PHP was described briefly in an earlier section; this section gives the details. Return values are passed via the return_value variable, which is passed to your functions as argument. The return_value argument consists of a zval container (see the earlier discussion of the call interface) that you can freely modify. The container itself is already allocated, so you don't have to run MAKE_STD_ZVAL on it. Instead, you can access its members directly.
To make returning values from functions easier and to prevent hassles with accessing the internal structures of the zval container, a set of predefined macros is available (as usual). These macros automatically set the correspondent type and value, as described in Tabela 35-1 and Tabela 35-2.
Nota: The macros in Tabela 35-1 automatically return from your function, those in Tabela 35-2 only set the return value; they don't return from your function.
Tabela 35-1. Predefined Macros for Returning Values from a Function
Macro | Description |
RETURN_RESOURCE(resource) | Returns a resource. |
RETURN_BOOL(bool) | Returns a Boolean. |
RETURN_NULL() | Returns nothing (a NULL value). |
RETURN_LONG(long) | Returns a long. |
RETURN_DOUBLE(double) | Returns a double. |
RETURN_STRING(string, duplicate) | Returns a string. The duplicate flag indicates whether the string should be duplicated using estrdup(). |
RETURN_STRINGL(string, length, duplicate) | Returns a string of the specified length; otherwise, behaves like RETURN_STRING. This macro is faster and binary-safe, however. |
RETURN_EMPTY_STRING() | Returns an empty string. |
RETURN_FALSE | Returns Boolean false. |
RETURN_TRUE | Returns Boolean true. |
Tabela 35-2. Predefined Macros for Setting the Return Value of a Function
Macro | Description |
RETVAL_RESOURCE(resource) | Sets the return value to the specified resource. |
RETVAL_BOOL(bool) | Sets the return value to the specified Boolean value. |
RETVAL_NULL | Sets the return value to NULL. |
RETVAL_LONG(long) | Sets the return value to the specified long. |
RETVAL_DOUBLE(double) | Sets the return value to the specified double. |
RETVAL_STRING(string, duplicate) | Sets the return value to the specified string and duplicates it to Zend internal memory if desired (see also RETURN_STRING). |
RETVAL_STRINGL(string, length, duplicate) | Sets the return value to the specified string and forces the length to become length (see also RETVAL_STRING). This macro is faster and binary-safe, and should be used whenever the string length is known. |
RETVAL_EMPTY_STRING | Sets the return value to an empty string. |
RETVAL_FALSE | Sets the return value to Boolean false. |
RETVAL_TRUE | Sets the return value to Boolean true. |
Complex types such as arrays and objects can be returned by using array_init() and object_init(), as well as the corresponding hash functions on return_value. Since these types cannot be constructed of trivial information, there are no predefined macros for them.
Often it's necessary to print messages to the output stream from your module, just as print() would be used within a script. PHP offers functions for most generic tasks, such as printing warning messages, generating output for phpinfo(), and so on. The following sections provide more details. Examples of these functions can be found on the CD-ROM.
zend_printf() works like the standard printf(), except that it prints to Zend's output stream.
zend_error() can be used to generate error messages. This function accepts two arguments; the first is the error type (see zend_errors.h), and the second is the error message.
zend_error(E_WARNING, "This function has been called with empty arguments"); |
Tabela 36-1. Zend's Predefined Error Messages.
Error | Description |
E_ERROR | Signals an error and terminates execution of the script immediately . |
E_WARNING | Signals a generic warning. Execution continues. |
E_PARSE | Signals a parser error. Execution continues. |
E_NOTICE | Signals a notice. Execution continues. Note that by default the display of this type of error messages is turned off in php.ini. |
E_CORE_ERROR | Internal error by the core; shouldn't be used by user-written modules. |
E_COMPILE_ERROR | Internal error by the compiler; shouldn't be used by user-written modules. |
E_COMPILE_WARNING | Internal warning by the compiler; shouldn't be used by user-written modules. |
After creating a real module, you'll want to show information about the module in phpinfo() (in addition to the module name, which appears in the module list by default). PHP allows you to create your own section in the phpinfo() output with the ZEND_MINFO() function. This function should be placed in the module descriptor block (discussed earlier) and is always called whenever a script calls phpinfo().
PHP automatically prints a section in phpinfo() for you if you specify the ZEND_MINFO function, including the module name in the heading. Everything else must be formatted and printed by you.
Typically, you can print an HTML table header using php_info_print_table_start() and then use the standard functions php_info_print_table_header() and php_info_print_table_row(). As arguments, both take the number of columns (as integers) and the column contents (as strings). Exemplo 36-1 shows a source example and its output. To print the table footer, use php_info_print_table_end().
Exemplo 36-1. Source code and screenshot for output in phpinfo().
|
You can also print execution information, such as the current file being executed. The name of the function currently being executed can be retrieved using the function get_active_function_name(). This function returns a pointer to the function name and doesn't accept any arguments. To retrieve the name of the file currently being executed, use zend_get_executed_filename(). This function accesses the executor globals, which are passed to it using the TSRMLS_C macro. The executor globals are automatically available to every function that's called directly by Zend (they're part of the INTERNAL_FUNCTION_PARAMETERS described earlier in this chapter). If you want to access the executor globals in another function that doesn't have them available automatically, call the macro TSRMLS_FETCH() once in that function; this will introduce them to your local scope.
Finally, the line number currently being executed can be retrieved using the function zend_get_executed_lineno(). This function also requires the executor globals as arguments. For examples of these functions, see Exemplo 36-2.
Exemplo 36-2. Printing execution information.
|
Startup and shutdown functions can be used for one-time initialization and deinitialization of your modules. As discussed earlier in this chapter (see the description of the Zend module descriptor block), there are module, and request startup and shutdown events.
The module startup and shutdown functions are called whenever a module is loaded and needs initialization; the request startup and shutdown functions are called every time a request is processed (meaning that a file is being executed).
For dynamic extensions, module and request startup/shutdown events happen at the same time.
Declaration and implementation of these functions can be done with macros; see the earlier section "Declaration of the Zend Module Block" for details.
You can call user functions from your own modules, which is very handy when implementing callbacks; for example, for array walking, searching, or simply for event-based programs.
User functions can be called with the function call_user_function_ex(). It requires a hash value for the function table you want to access, a pointer to an object (if you want to call a method), the function name, return value, number of arguments, argument array, and a flag indicating whether you want to perform zval separation.
ZEND_API int call_user_function_ex(HashTable *function_table, zval *object, zval *function_name, zval **retval_ptr_ptr, int param_count, zval **params[], int no_separation); |
Note that you don't have to specify both function_table and object; either will do. If you want to call a method, you have to supply the object that contains this method, in which case call_user_function()automatically sets the function table to this object's function table. Otherwise, you only need to specify function_table and can set object to NULL.
Usually, the default function table is the "root" function table containing all function entries. This function table is part of the compiler globals and can be accessed using the macro CG. To introduce the compiler globals to your function, call the macro TSRMLS_FETCH once.
The function name is specified in a zval container. This might be a bit surprising at first, but is quite a logical step, since most of the time you'll accept function names as parameters from calling functions within your script, which in turn are contained in zval containers again. Thus, you only have to pass your arguments through to this function. This zval must be of type IS_STRING.
The next argument consists of a pointer to the return value. You don't have to allocate memory for this container; the function will do so by itself. However, you have to destroy this container (using zval_dtor()) afterward!
Next is the parameter count as integer and an array containing all necessary parameters. The last argument specifies whether the function should perform zval separation - this should always be set to 0. If set to 1, the function consumes less memory but fails if any of the parameters need separation.
Exemplo 38-1 shows a small demonstration of calling a user function. The code calls a function that's supplied to it as argument and directly passes this function's return value through as its own return value. Note the use of the constructor and destructor calls at the end - it might not be necessary to do it this way here (since they should be separate values, the assignment might be safe), but this is bulletproof.
Exemplo 38-1. Calling user functions.
|
<?php dl("call_userland.so"); function test_function() { print("We are in the test function!<br>"); return("hello"); } $return_value = call_userland("test_function"); print("Return value: \"$return_value\"<br>"); ?> |
PHP 4 features a redesigned initialization file support. It's now possible to specify default initialization entries directly in your code, read and change these values at runtime, and create message handlers for change notifications.
To create an .ini section in your own module, use the macros PHP_INI_BEGIN() to mark the beginning of such a section and PHP_INI_END() to mark its end. In between you can use PHP_INI_ENTRY() to create entries.
PHP_INI_BEGIN() PHP_INI_ENTRY("first_ini_entry", "has_string_value", PHP_INI_ALL, NULL) PHP_INI_ENTRY("second_ini_entry", "2", PHP_INI_SYSTEM, OnChangeSecond) PHP_INI_ENTRY("third_ini_entry", "xyz", PHP_INI_USER, NULL) PHP_INI_END() |
The permissions are grouped into three sections:PHP_INI_SYSTEM allows a change only directly in the php.ini file; PHP_INI_USER allows a change to be overridden by a user at runtime using additional configuration files, such as .htaccess; and PHP_INI_ALL allows changes to be made without restrictions. There's also a fourth level, PHP_INI_PERDIR, for which we couldn't verify its behavior yet.
The fourth parameter consists of a pointer to a change-notification handler. Whenever one of these initialization entries is changed, this handler is called. Such a handler can be declared using the PHP_INI_MH macro:
PHP_INI_MH(OnChangeSecond); // handler for ini-entry "second_ini_entry" // specify ini-entries here PHP_INI_MH(OnChangeSecond) { zend_printf("Message caught, our ini entry has been changed to %s<br>", new_value); return(SUCCESS); } |
#define PHP_INI_MH(name) int name(php_ini_entry *entry, char *new_value, uint new_value_length, void *mh_arg1, void *mh_arg2, void *mh_arg3) |
The change-notification handlers should be used to cache initialization entries locally for faster access or to perform certain tasks that are required if a value changes. For example, if a constant connection to a certain host is required by a module and someone changes the hostname, automatically terminate the old connection and attempt a new one.
Access to initialization entries can also be handled with the macros shown in Tabela 39-1.
Tabela 39-1. Macros to Access Initialization Entries in PHP
Macro | Description |
INI_INT(name) | Returns the current value of entry name as integer (long). |
INI_FLT(name) | Returns the current value of entry name as float (double). |
INI_STR(name) | Returns the current value of entry name as string. Note: This string is not duplicated, but instead points to internal data. Further access requires duplication to local memory. |
INI_BOOL(name) | Returns the current value of entry name as Boolean (defined as zend_bool, which currently means unsigned char). |
INI_ORIG_INT(name) | Returns the original value of entry name as integer (long). |
INI_ORIG_FLT(name) | Returns the original value of entry name as float (double). |
INI_ORIG_STR(name) | Returns the original value of entry name as string. Note: This string is not duplicated, but instead points to internal data. Further access requires duplication to local memory. |
INI_ORIG_BOOL(name) | Returns the original value of entry name as Boolean (defined as zend_bool, which currently means unsigned char). |
Finally, you have to introduce your initialization entries to PHP. This can be done in the module startup and shutdown functions, using the macros REGISTER_INI_ENTRIES() and UNREGISTER_INI_ENTRIES():
ZEND_MINIT_FUNCTION(mymodule) { REGISTER_INI_ENTRIES(); } ZEND_MSHUTDOWN_FUNCTION(mymodule) { UNREGISTER_INI_ENTRIES(); } |
You've learned a lot about PHP. You now know how to create dynamic loadable modules and statically linked extensions. You've learned how PHP and Zend deal with internal storage of variables and how you can create and access these variables. You know quite a set of tool functions that do a lot of routine tasks such as printing informational texts, automatically introducing variables to the symbol table, and so on.
Even though this chapter often had a mostly "referential" character, we hope that it gave you insight on how to start writing your own extensions. For the sake of space, we had to leave out a lot; we suggest that you take the time to study the header files and some modules (especially the ones in the ext/standard directory and the MySQL module, as these implement commonly known functionality). This will give you an idea of how other people have used the API functions - particularly those that didn't make it into this chapter.
The file config.m4 is processed by buildconf and must contain all the instructions to be executed during configuration. For example, these can include tests for required external files, such as header files, libraries, and so on. PHP defines a set of macros that can be used in this process, the most useful of which are described in Tabela 41-1.
Tabela 41-1. M4 Macros for config.m4
Macro | Description |
AC_MSG_CHECKING(message) | Prints a "checking <message>" text during configure. |
AC_MSG_RESULT(value) | Gives the result to AC_MSG_CHECKING; should specify either yes or no as value. |
AC_MSG_ERROR(message) | Prints message as error message during configure and aborts the script. |
AC_DEFINE(name,value,description) | Adds #define to php_config.h with the value of value and a comment that says description (this is useful for conditional compilation of your module). |
AC_ADD_INCLUDE(path) | Adds a compiler include path; for example, used if the module needs to add search paths for header files. |
AC_ADD_LIBRARY_WITH_PATH(libraryname,librarypath) | Specifies an additional library to link. |
AC_ARG_WITH(modulename,description,unconditionaltest,conditionaltest) | Quite a powerful macro, adding the module with description to the configure --help output. PHP checks whether the option --with-<modulename> is given to the configure script. If so, it runs the script unconditionaltest (for example, --with-myext=yes), in which case the value of the option is contained in the variable $withval. Otherwise, it executes conditionaltest. |
PHP_EXTENSION(modulename, [shared]) | This macro is a must to call for PHP to configure your extension. You can supply a second argument in addition to your module name, indicating whether you intend compilation as a shared module. This will result in a definition at compile time for your source as COMPILE_DL_<modulename>. |
A set of macros was introduced into Zend's API that simplify access to zval containers (see Tabela 42-1).
Tabela 42-1. API Macros for Accessing zval Containers
Macro | Refers to |
Z_LVAL(zval) | (zval).value.lval |
Z_DVAL(zval) | (zval).value.dval |
Z_STRVAL(zval) | (zval).value.str.val |
Z_STRLEN(zval) | (zval).value.str.len |
Z_ARRVAL(zval) | (zval).value.ht |
Z_LVAL_P(zval) | (*zval).value.lval |
Z_DVAL_P(zval) | (*zval).value.dval |
Z_STRVAL_P(zval_p) | (*zval).value.str.val |
Z_STRLEN_P(zval_p) | (*zval).value.str.len |
Z_ARRVAL_P(zval_p) | (*zval).value.ht |
Z_LVAL_PP(zval_pp) | (**zval).value.lval |
Z_DVAL_PP(zval_pp) | (**zval).value.dval |
Z_STRVAL_PP(zval_pp) | (**zval).value.str.val |
Z_STRLEN_PP(zval_pp) | (**zval).value.str.len |
Z_ARRVAL_PP(zval_pp) | (**zval).value.ht |
The PHP Streams API introduces a unified approach to the handling of files and sockets in PHP extension. Using a single API with standard functions for common operations, the streams API allows your extension to access files, sockets, URLs, memory and script-defined objects. Streams is a run-time extensible API that allows dynamically loaded modules (and scripts!) to register new streams.
The aim of the Streams API is to make it comfortable for developers to open files, urls and other streamable data sources with a unified API that is easy to understand. The API is more or less based on the ANSI C stdio family of functions (with identical semantics for most of the main functions), so C programmers will have a feeling of familiarity with streams.
The streams API operates on a couple of different levels: at the base level, the API defines php_stream objects to represent streamable data sources. On a slightly higher level, the API defines php_stream_wrapper objects which "wrap" around the lower level API to provide support for retrieving data and meta-data from URLs.
Streams can be cast (converted) into other types of file-handles, so that they can be used with third-party libraries without a great deal of trouble. This allows those libraries to access data directly from URL sources. If your system has the fopencookie() or funopen() function, you can even pass any PHP stream to any library that uses ANSI stdio!
Nota: The functions in this chapter are for use in the PHP source code and are not PHP functions. Userland stream functions can be found in the Stream Reference.
Using streams is very much like using ANSI stdio functions. The main difference is in how you obtain the stream handle to begin with. In most cases, you will use php_stream_open_wrapper() to obtain the stream handle. This function works very much like fopen, as can be seen from the example below:
Exemplo 43-1. simple stream example that displays the PHP home page
|
The table below shows the Streams equivalents of the more common ANSI stdio functions. Unless noted otherwise, the semantics of the functions are identical.
Tabela 43-1. ANSI stdio equivalent functions in the Streams API
ANSI Stdio Function | PHP Streams Function | Notes |
---|---|---|
fopen | php_stream_open_wrapper | Streams includes additional parameters |
fclose | php_stream_close | |
fgets | php_stream_gets | |
fread | php_stream_read | The nmemb parameter is assumed to have a value of 1, so the prototype looks more like read(2) |
fwrite | php_stream_write | The nmemb parameter is assumed to have a value of 1, so the prototype looks more like write(2) |
fseek | php_stream_seek | |
ftell | php_stream_tell | |
rewind | php_stream_rewind | |
feof | php_stream_eof | |
fgetc | php_stream_getc | |
fputc | php_stream_putc | |
fflush | php_stream_flush | |
puts | php_stream_puts | Same semantics as puts, NOT fputs |
fstat | php_stream_stat | Streams has a richer stat structure |
All streams are registered as resources when they are created. This ensures that they will be properly cleaned up even if there is some fatal error. All of the filesystem functions in PHP operate on streams resources - that means that your extensions can accept regular PHP file pointers as parameters to, and return streams from their functions. The streams API makes this process as painless as possible:
Exemplo 43-2. How to accept a stream as a parameter
|
Exemplo 43-3. How to return a stream from a function
|
Since streams are automatically cleaned up, it's tempting to think that we can get away with being sloppy programmers and not bother to close the streams when we are done with them. Although such an approach might work, it is not a good idea for a number of reasons: streams hold locks on system resources while they are open, so leaving a file open after you have finished with it could prevent other processes from accessing it. If a script deals with a large number of files, the accumulation of the resources used, both in terms of memory and the sheer number of open files, can cause web server requests to fail. Sounds bad, doesn't it? The streams API includes some magic that helps you to keep your code clean - if a stream is not closed by your code when it should be, you will find some helpful debugging information in you web server error log.
Nota: Always use a debug build of PHP when developing an extension (--enable-debug when running configure), as a lot of effort has been made to warn you about memory and stream leaks.
In some cases, it is useful to keep a stream open for the duration of a request, to act as a log or trace file for example. Writing the code to safely clean up such a stream is not difficult, but it's several lines of code that are not strictly needed. To save yourself the touble of writing the code, you can mark a stream as being OK for auto cleanup. What this means is that the streams API will not emit a warning when it is time to auto-cleanup a stream. To do this, you can use php_stream_auto_cleanup().
(no version information, might be only in CVS)
php_stream_stat_path -- Gets the status for a file or URLphp_stream_stat_path() examines the file or URL specified by path and returns information such as file size, access and creation times and so on. The return value is 0 on success, -1 on error. For more information about the information returned, see php_stream_statbuf.
(no version information, might be only in CVS)
php_stream_stat -- Gets the status for the underlying storage associated with a streamphp_stream_stat() examines the storage to which stream is bound, and returns information such as file size, access and creation times and so on. The return value is 0 on success, -1 on error. For more information about the information returned, see php_stream_statbuf.
(no version information, might be only in CVS)
php_stream_open_wrapper -- Opens a stream on a file or URLphp_stream_open_wrapper() opens a stream on the file, URL or other wrapped resource specified by path. Depending on the value of mode, the stream may be opened for reading, writing, appending or combinations of those. See the table below for the different modes that can be used; in addition to the characters listed below, you may include the character 'b' either as the second or last character in the mode string. The presence of the 'b' character informs the relevant stream implementation to open the stream in a binary safe mode.
The 'b' character is ignored on all POSIX conforming systems which treat binary and text files in the same way. It is a good idea to specify the 'b' character whenever your stream is accessing data where the full 8 bits are important, so that your code will work when compiled on a system where the 'b' flag is important.
Any local files created by the streams API will have their initial permissions set according to the operating system defaults - under UNIX based systems this means that the umask of the process will be used. Under Windows, the file will be owned by the creating process. Any remote files will be created according to the URL wrapper that was used to open the file, and the credentials supplied to the remote server.
Open text file for reading. The stream is positioned at the beginning of the file.
Open text file for reading and writing. The stream is positioned at the beginning of the file.
Truncate the file to zero length or create text file for writing. The stream is positioned at the beginning of the file.
Open text file for reading and writing. The file is created if it does not exist, otherwise it is truncated. The stream is positioned at the beginning of the file.
Open for writing. The file is created if it does not exist. The stream is positioned at the end of the file.
Open text file for reading and writing. The file is created if it does not exist. The stream is positioned at the end of the file.
options affects how the path/URL of the stream is interpreted, safe mode checks and actions taken if there is an error during opening of the stream. See Stream open options for more information about options.
If opened is not NULL, it will be set to a string containing the name of the actual file/resource that was opened. This is important when the options include USE_PATH, which causes the include_path to be searched for the file. You, the caller, are responsible for calling efree() on the filename returned in this parameter.
Nota: If you specified STREAM_MUST_SEEK in options, the path returned in opened may not be the name of the actual stream that was returned to you. It will, however, be the name of the original resource from which the seekable stream was manufactured.
(no version information, might be only in CVS)
php_stream_read -- Read a number of bytes from a stream into a bufferphp_stream_read() reads up to count bytes of data from stream and copies them into the buffer buf.
php_stream_read() returns the number of bytes that were read successfully. There is no distinction between a failed read or an end-of-file condition - use php_stream_eof() to test for an EOF.
The internal position of the stream is advanced by the number of bytes that were read, so that subsequent reads will continue reading from that point.
If less than count bytes are available to be read, this call will block (or wait) until the required number are available, depending on the blocking status of the stream. By default, a stream is opened in blocking mode. When reading from regular files, the blocking mode will not usually make any difference: when the stream reaches the EOF php_stream_read() will return a value less than count, and 0 on subsequent reads.
(no version information, might be only in CVS)
php_stream_write -- Write a number of bytes from a buffer to a streamphp_stream_write() writes count bytes of data from buf into stream.
php_stream_write() returns the number of bytes that were read successfully. If there was an error, the number of bytes written will be less than count.
The internal position of the stream is advanced by the number of bytes that were written, so that subsequent writes will continue writing from that point.
(no version information, might be only in CVS)
php_stream_eof -- Check for an end-of-file condition on a streamphp_stream_eof() checks for an end-of-file condition on stream.
php_stream_read() returns the 1 to indicate EOF, 0 if there is no EOF and -1 to indicate an error.
php_stream_getc() reads a single character from stream and returns it as an unsigned char cast as an int, or EOF if the end-of-file is reached, or an error occurred.
php_stream_getc() may block in the same way as php_stream_read() blocks.
The internal position of the stream is advanced by 1 if successful.
(no version information, might be only in CVS)
php_stream_gets -- Read a line of data from a stream into a bufferphp_stream_gets() reads up to count-1 bytes of data from stream and copies them into the buffer buf. Reading stops after an EOF or a newline. If a newline is read, it is stored in buf as part of the returned data. A NUL terminating character is stored as the last character in the buffer.
php_stream_read() returns buf when successful or NULL otherwise.
The internal position of the stream is advanced by the number of bytes that were read, so that subsequent reads will continue reading from that point.
This function may block in the same way as php_stream_read().
php_stream_close() safely closes stream and releases the resources associated with it. After stream has been closed, it's value is undefined and should not be used.
php_stream_close() returns 0 if the stream was closed or EOF to indicate an error. Regardless of the success of the call, stream is undefined and should not be used after a call to this function.
php_stream_flush() causes any data held in write buffers in stream to be committed to the underlying storage.
php_stream_flush() returns 0 if the buffers were flushed, or if the buffers did not need to be flushed, but returns EOF to indicate an error.
php_stream_seek() repositions the internal position of stream. The new position is determined by adding the offset to the position indicated by whence. If whence is set to SEEK_SET, SEEK_CUR or SEEK_END the offset is relative to the start of the stream, the current position or the end of the stream, respectively.
php_stream_seek() returns 0 on success, but -1 if there was an error.
Nota: Not all streams support seeking, although the streams API will emulate a seek if whence is set to SEEK_CUR and offset is positive, by calling php_stream_read() to read (and discard) offset bytes.
The emulation is only applied when the underlying stream implementation does not support seeking. If the stream is (for example) a file based stream that is wrapping a non-seekable pipe, the streams api will not apply emulation because the file based stream implements a seek operation; the seek will fail and an error result will be returned to the caller.
php_stream_tell() returns the internal position of stream, relative to the start of the stream. If there is an error, -1 is returned.
(no version information, might be only in CVS)
php_stream_copy_to_stream -- Copy data from one stream to anotherphp_stream_copy_to_stream() attempts to read up to maxlen bytes of data from src and write them to dest, and returns the number of bytes that were successfully copied.
If you want to copy all remaining data from the src stream, pass the constant PHP_STREAM_COPY_ALL as the value of maxlen.
Nota: This function will attempt to copy the data in the most efficient manner, using memory mapped files when possible.
(no version information, might be only in CVS)
php_stream_copy_to_mem -- Copy data from stream and into an allocated bufferphp_stream_copy_to_mem() allocates a buffer maxlen+1 bytes in length using pemalloc() (passing persistent). It then reads maxlen bytes from src and stores them in the allocated buffer.
The allocated buffer is returned in buf, and the number of bytes successfully read. You, the caller, are responsible for freeing the buffer by passing it and persistent to pefree().
If you want to copy all remaining data from the src stream, pass the constant PHP_STREAM_COPY_ALL as the value of maxlen.
Nota: This function will attempt to copy the data in the most efficient manner, using memory mapped files when possible.
(no version information, might be only in CVS)
php_stream_make_seekable -- Convert a stream into a stream is seekablephp_stream_make_seekable() checks if origstream is seekable. If it is not, it will copy the data into a new temporary stream. If successful, newstream is always set to the stream that is valid to use, even if the original stream was seekable.
flags allows you to specify your preference for the seekeable stream that is returned: use PHP_STREAM_NO_PREFERENCE to use the default seekable stream (which uses a dynamically expanding memory buffer, but switches to temporary file backed storage when the stream size becomes large), or use PHP_STREAM_PREFER_STDIO to use "regular" temporary file backed storage.
Tabela 43-1. php_stream_make_seekable() return values
Value | Meaning |
---|---|
PHP_STREAM_UNCHANGED | Original stream was seekable anyway. newstream is set to the value of origstream. |
PHP_STREAM_RELEASED | Original stream was not seekable and has been released. newstream is set to the new seekable stream. You should not access origstream anymore. |
PHP_STREAM_FAILED | An error occurred while attempting conversion. newstream is set to NULL; origstream is still valid. |
PHP_STREAM_CRITICAL | An error occurred while attempting conversion that has left origstream in an indeterminate state. newstream is set to NULL and it is highly recommended that you close origstream. |
Nota: If you need to seek and write to the stream, it does not make sense to use this function, because the stream it returns is not guaranteed to be bound to the same resource as the original stream.
Nota: If you only need to seek forwards, there is no need to call this function, as the streams API will emulate forward seeks when the whence parameter is SEEK_CUR.
Nota: If origstream is network based, this function will block until the whole contents have been downloaded.
Nota: NEVER call this function with an origstream that is reference by a file pointer in a PHP script! This function may cause the underlying stream to be closed which could cause a crash when the script next accesses the file pointer!
Nota: In many cases, this function can only succeed when origstream is a newly opened stream with no data buffered in the stream layer. For that reason, and because this function is complicated to use correctly, it is recommended that you use php_stream_open_wrapper() and pass in PHP_STREAM_MUST_SEEK in your options instead of calling this function directly.
(no version information, might be only in CVS)
php_stream_cast -- Convert a stream into another form, such as a FILE* or socketphp_stream_cast() attempts to convert stream into a resource indicated by castas. If ret is NULL, the stream is queried to find out if such a conversion is possible, without actually performing the conversion (however, some internal stream state *might* be changed in this case). If flags is set to REPORT_ERRORS, an error message will be displayed is there is an error during conversion.
Nota: This function returns SUCCESS for success or FAILURE for failure. Be warned that you must explicitly compare the return value with SUCCESS or FAILURE because of the underlying values of those constants. A simple boolean expression will not be interpreted as you intended.
Tabela 43-1. Resource types for castas
Value | Meaning |
---|---|
PHP_STREAM_AS_STDIO | Requests an ANSI FILE* that represents the stream |
PHP_STREAM_AS_FD | Requests a POSIX file descriptor that represents the stream |
PHP_STREAM_AS_SOCKETD | Requests a network socket descriptor that represents the stream |
In addition to the basic resource types above, the conversion process can be altered by using the following flags by using the OR operator to combine the resource type with one or more of the following values:
Tabela 43-2. Resource types for castas
Value | Meaning |
---|---|
PHP_STREAM_CAST_TRY_HARD | Tries as hard as possible, at the expense of additional resources, to ensure that the conversion succeeds |
PHP_STREAM_CAST_RELEASE | Informs the streams API that some other code (possibly a third party library) will be responsible for closing the underlying handle/resource. This causes the stream to be closed in such a way the underlying handle is preserved and returned in ret. If this function succeeds, stream should be considered closed and should no longer be used. |
Nota: If your system supports fopencookie() (systems using glibc 2 or later), the streams API will always be able to synthesize an ANSI FILE* pointer over any stream. While this is tremendously useful for passing any PHP stream to any third-party libraries, such behaviour is not portable. You are requested to consider the portability implications before distributing you extension. If the fopencookie synthesis is not desireable, you should query the stream to see if it naturally supports FILE* by using php_stream_is()
Nota: If you ask a socket based stream for a FILE*, the streams API will use fdopen() to create it for you. Be warned that doing do may cause data that was buffered in the streams layer to be lost if you intermix streams API calls with ANSI stdio calls.
See also php_stream_is() and php_stream_can_cast().
(no version information, might be only in CVS)
php_stream_can_cast -- Determines if a stream can be converted into another form, such as a FILE* or socketThis function is equivalent to calling php_stream_cast() with ret set to NULL and flags set to 0. It returns SUCCESS if the stream can be converted into the form requested, or FAILURE if the conversion cannot be performed.
Nota: Although this function will not perform the conversion, some internal stream state *might* be changed by this call.
Nota: You must explicity compare the return value of this function with one of the constants, as described in php_stream_cast().
See also php_stream_cast() and php_stream_is().
(no version information, might be only in CVS)
php_stream_is_persistent -- Determines if a stream is a persistent streamphp_stream_is_persistent() returns 1 if the stream is a persistent stream, 0 otherwise.
(no version information, might be only in CVS)
php_stream_is -- Determines if a stream is of a particular typephp_stream_is() returns 1 if stream is of the type specified by istype, or 0 otherwise.
Tabela 43-1. Values for istype
Value | Meaning |
---|---|
PHP_STREAM_IS_STDIO | The stream is implemented using the stdio implementation |
PHP_STREAM_IS_SOCKET | The stream is implemented using the network stream implementation |
PHP_STREAM_IS_USERSPACE | The stream is implemented using the userspace object implementation |
PHP_STREAM_IS_MEMORY | The stream is implemented using the grow-on-demand memory stream implementation |
Nota: The PHP_STREAM_IS_XXX "constants" are actually defined as pointers to the underlying stream operations structure. If your extension (or some other extension) defines additional streams, it should also declare a PHP_STREAM_IS_XXX constant in it's header file that you can use as the basis of this comparison.
Nota: This function is implemented as a simple (and fast) pointer comparision, and does not change the stream state in any way.
See also php_stream_cast() and php_stream_can_cast().
(no version information, might be only in CVS)
php_stream_passthru -- Outputs all remaining data from a streamphp_stream_passthru() outputs all remaining data from stream to the active output buffer and returns the number of bytes output. If buffering is disabled, the data is written straight to the output, which is the browser making the request in the case of PHP on a web server, or stdout for CLI based PHP. This function will use memory mapped files if possible to help improve performance.
(no version information, might be only in CVS)
php_register_url_stream_wrapper -- Registers a wrapper with the Streams APIphp_register_url_stream_wrapper() registers wrapper as the handler for the protocol specified by protocol.
Nota: If you call this function from a loadable module, you *MUST* call php_unregister_url_stream_wrapper() in your module shutdown function, otherwise PHP will crash.
(no version information, might be only in CVS)
php_unregister_url_stream_wrapper -- Un-registers a wrapper from the Streams APIphp_unregister_url_stream_wrapper() unregisters the wrapper associated with protocol.
(no version information, might be only in CVS)
php_stream_open_wrapper_ex -- Opens a stream on a file or URL, specifying contextphp_stream_open_wrapper_ex() is exactly like php_stream_open_wrapper(), but allows you to specify a php_stream_context object using context. To find out more about stream contexts, see XXX
(no version information, might be only in CVS)
php_stream_open_wrapper_as_file -- Opens a stream on a file or URL, and converts to a FILE*php_stream_open_wrapper_as_file() is exactly like php_stream_open_wrapper(), but converts the stream into an ANSI stdio FILE* and returns that instead of the stream. This is a convenient shortcut for extensions that pass FILE* to third-party libraries.
The functions listed in this section work on local files, as well as remote files (provided that the wrapper supports this functionality!).
(no version information, might be only in CVS)
php_stream_opendir -- Open a directory for file enumerationphp_stream_opendir() returns a stream that can be used to list the files that are contained in the directory specified by path. This function is functionally equivalent to POSIX opendir(). Although this function returns a php_stream object, it is not recommended to try to use the functions from the common API on these streams.
(no version information, might be only in CVS)
php_stream_readdir -- Fetch the next directory entry from an opened dirphp_stream_readdir() reads the next directory entry from dirstream and stores it into ent. If the function succeeds, the return value is ent. If the function fails, the return value is NULL. See php_stream_dirent for more details about the information returned for each directory entry.
(no version information, might be only in CVS)
php_stream_rewinddir -- Rewind a directory stream to the first entryphp_stream_rewinddir() rewinds a directory stream to the first entry. Returns 0 on success, but -1 on failure.
(no version information, might be only in CVS)
php_stream_fopen_from_file -- Convert an ANSI FILE* into a streamphp_stream_fopen_from_file() returns a stream based on the file. mode must be the same as the mode used to open file, otherwise strange errors may occur when trying to write when the mode of the stream is different from the mode on the file.
(no version information, might be only in CVS)
php_stream_fopen_tmpfile -- Open a FILE* with tmpfile() and convert into a streamphp_stream_fopen_from_file() returns a stream based on a temporary file opened with a mode of "w+b". The temporary file will be deleted automatically when the stream is closed or the process terminates.
(no version information, might be only in CVS)
php_stream_fopen_temporary_file -- Generate a temporary file name and open a stream on itphp_stream_fopen_temporary_file() generates a temporary file name in the directory specified by dir and with a prefix of pfx. The generated file name is returns in the opened parameter, which you are responsible for cleaning up using efree(). A stream is opened on that generated filename in "w+b" mode. The file is NOT automatically deleted; you are responsible for unlinking or moving the file when you have finished with it.
(no version information, might be only in CVS)
php_stream_sock_open_from_socket -- Convert a socket descriptor into a streamphp_stream_sock_open_from_socket() returns a stream based on the socket. persistent is a flag that controls whether the stream is opened as a persistent stream. Generally speaking, this parameter will usually be 0.
(no version information, might be only in CVS)
php_stream_sock_open_host -- Open a connection to a host and return a streamphp_stream_sock_open_host() establishes a connect to the specified host and port. socktype specifies the connection semantics that should apply to the connection. Values for socktype are system dependent, but will usually include (at a minimum) SOCK_STREAM for sequenced, reliable, two-way connection based streams (TCP), or SOCK_DGRAM for connectionless, unreliable messages of a fixed maximum length (UDP).
persistent is a flag the controls whether the stream is opened as a persistent stream. Generally speaking, this parameter will usually be 0.
If not NULL, timeout specifies a maximum time to allow for the connection to be made. If the connection attempt takes longer than the timeout value, the connection attempt is aborted and NULL is returned to indicate that the stream could not be opened.
Nota: The timeout value does not include the time taken to perform a DNS lookup. The reason for this is because there is no portable way to implement a non-blocking DNS lookup.
The timeout only applies to the connection phase; if you need to set timeouts for subsequent read or write operations, you should use php_stream_sock_set_timeout() to configure the timeout duration for your stream once it has been opened.
The streams API places no restrictions on the values you use for socktype, but encourages you to consider the portability of values you choose before you release your extension.
(no version information, might be only in CVS)
php_stream_sock_open_unix -- Open a UNIX domain socket and convert into a streamphp_stream_sock_open_unix() attempts to open the UNIX domain socket specified by path. pathlen specifies the length of path. If timeout is not NULL, it specifies a timeout period for the connection attempt. persistent indicates if the stream should be opened as a persistent stream. Generally speaking, this parameter will usually be 0.
Nota: This function will not work under Windows, which does not implement unix domain sockets. A possible exception to this rule is if your PHP binary was built using cygwin. You are encouraged to consider this aspect of the portability of your extension before it's release.
Nota: This function treats path in a binary safe manner, suitable for use on systems with an abstract namespace (such as Linux), where the first character of path is a NUL character.
php_stream_dirent
char d_name[MAXPATHLEN] |
d_name holds the name of the file, relative to the directory being scanned.
typedef struct _php_stream_ops { /* all streams MUST implement these operations */ size_t (*write)(php_stream *stream, const char *buf, size_t count TSRMLS_DC); size_t (*read)(php_stream *stream, char *buf, size_t count TSRMLS_DC); int (*close)(php_stream *stream, int close_handle TSRMLS_DC); int (*flush)(php_stream *stream TSRMLS_DC); const char *label; /* name describing this class of stream */ /* these operations are optional, and may be set to NULL if the stream does not * support a particular operation */ int (*seek)(php_stream *stream, off_t offset, int whence TSRMLS_DC); char *(*gets)(php_stream *stream, char *buf, size_t size TSRMLS_DC); int (*cast)(php_stream *stream, int castas, void **ret TSRMLS_DC); int (*stat)(php_stream *stream, php_stream_statbuf *ssb TSRMLS_DC); } php_stream_ops; |
One or more of these values can be combined using the OR operator.
This is the default option for streams; it requests that the include_path is not to be searched for the requested file.
Requests that the include_path is to be searched for the requested file.
Requests that registered URL wrappers are to be ignored when opening the stream. Other non-URL wrappers will be taken into consideration when decoding the path. There is no opposite form for this flag; the streams API will use all registered wrappers by default.
On Windows systems, this is equivalent to IGNORE_URL. On all other systems, this flag has no effect.
Requests that the underlying stream implementation perform safe_mode checks on the file before opening the file. Omitting this flag will skip safe_mode checks and allow opening of any file that the PHP process has rights to access.
If this flag is set, and there was an error during the opening of the file or URL, the streams API will call the php_error function for you. This is useful because the path may contain username/password information that should not be displayed in the browser output (it would be a security risk to do so). When the streams API raises the error, it first strips username/password information from the path, making the error message safe to display in the browser.
This flag is useful when your extension really must be able to randomly seek around in a stream. Some streams may not be seekable in their native form, so this flag asks the streams API to check to see if the stream does support seeking. If it does not, it will copy the stream into temporary storage (which may be a temporary file or a memory stream) which does support seeking. Please note that this flag is not useful when you want to seek the stream and write to it, because the stream you are accessing might not be bound to the actual resource you requested.
Nota: If the requested resource is network based, this flag will cause the opener to block until the whole contents have been downloaded.
If your extension is using a third-party library that expects a FILE* or file descriptor, you can use this flag to request the streams API to open the resource but avoid buffering. You can then use php_stream_cast() to retrieve the FILE* or file descriptor that the library requires.
The is particularly useful when accessing HTTP URLs where the start of the actual stream data is found after an indeterminate offset into the stream.
Since this option disables buffering at the streams API level, you may experience lower performance when using streams functions on the stream; this is deemed acceptable because you have told streams that you will be using the functions to match the underlying stream implementation. Only use this option when you are sure you need it.
This section holds the most general questions about PHP: what it is and what it does.
From the preface of the manual:
PHP is an HTML-embedded scripting language. Much of its syntax is borrowed from C, Java and Perl with a couple of unique PHP-specific features thrown in. The goal of the language is to allow web developers to write dynamically generated pages quickly.
A nice introduction to PHP by Stig Sæther Bakken can be found here on the Zend website. Also, much of the PHP Conference Material is freely available.
PHP stands for PHP: Hypertext Preprocessor. This confuses many people because the first word of the acronym is the acronym. This type of acronym is called a recursive acronym. The curious can visit Free On-Line Dictionary of Computing for more information on recursive acronyms.
PHP/FI 2.0 is an early and no longer supported version of PHP. PHP 3 is the successor to PHP/FI 2.0 and is a lot nicer. PHP 4 is the current generation of PHP, which uses the Zend engine under the hood. PHP 5 uses Zend engine 2 which, among other things, offers many additional OOP features. PHP 5 is experimental.
Yes. See the INSTALL file that is included in the PHP 4 source distribution. Also, read the related appendix.
There are a couple of articles written on this by the authors of PHP 4. Here's a list of some of the more important new features:
Extended API module
Generalized build process under UNIX
Generic web server interface that also supports multi-threaded web servers
Improved syntax highlighter
Native HTTP session support
Output buffering support
More powerful configuration system
Reference counting
You should go to the PHP Bug Database and make sure the bug isn't a known bug. If you don't see it in the database, use the reporting form to report the bug. It is important to use the bug database instead of just sending an email to one of the mailing lists because the bug will have a tracking number assigned and it will then be possible for you to go back later and check on the status of the bug. The bug database can be found at http://bugs.php.net/.
This section holds questions about how to get in touch with the PHP community. The best way is the mailing lists.
Of course! There are many mailing lists for several subjects. A whole list of mailing lists can be found on our Support page.
The most general mailing list is php-general. To subscribe, send mail to php-general-subscribe@lists.php.net. You don't need to include anything special in the subject or body of the message. To unsubscribe, send mail to php-general-unsubscribe@lists.php.net.
You can also subscribe and unsubscribe using the web interface on our Support page.
There are countless of them around the world. We have links for example to some IRC servers and foreign language mailing lists on our Support page.
If you have problems subscribing to or unsubscribing from the php-general mailing list, it may be because the mailing list software can't figure out the correct mailing address to use. If your email address was joeblow@example.com, you can send your subscription request to php-general-subscribe-joeblow=example.com@lists.php.net, or your unsubscription request to php-general-unsubscribe-joeblow=example.com@lists.php.net. Use similar addresses for the other mailing lists.
Yes, you will find a list of archive sites on the Support page. The mailing list articles are also archived as news messages. You can access the news server at news://news.php.net/ with a news client. There is also an experimental web interface for the news server at http://news.php.net/
Since PHP is growing more and more popular by the day the traffic has increased on the php-general mailing list and as of now the list gets about 150 to 200 posts a day. Because of this it is in everyones interest that you use the list as a last resort when you have looked everywhere else.
Before you post to the list please have a look in this FAQ and the manual to see if you can find the help there. If there is nothing to be found there try out the mailing list archives (see above). If you're having problem with installing or configuring PHP please read through all included documentation and README's. If you still can't find any information that helps you out you're more than welcome to use the mailing list.
Before asking questions, you may want to read the paper on How To Ask Questions The Smart Way as this is a good idea for everyone.
Posts like "I can't get PHP up and running! Help me! What is wrong?" are of absolutely no use to anyone. If you're having problems getting PHP up and running you must include what operating system you are running on, what version of PHP you're trying to set up, how you got it (pre-compiled, CVS, RPMs and so on), what you have done so far, where you got stuck and the exact error message.
This goes for any other problem as well. You have to include information on what you have done, where you got stuck, what you're trying to do and, if applicable, exact error messages. If you're having problems with your source code you need to include the part of the code that isn't working. Do not include more code than necessary though! It makes the post hard to read and a lot of people might just skip it all together because of this. If you're unsure about how much information to include in the mail it's better that you include to much than to little.
Another important thing to remember is to summarize your problem on the subject line. A subject like "HELP MEEEE!!!" or "What is the problem here?" will be ignored by the majority of the readers.
And lastly, you're encouraged to read the paper on How To Ask Questions The Smart Way as this will be a great help for everyone, especially yourself.
This section has details about PHP download locations, and OS issues.
You can download PHP from any of the members of the PHP network of sites. These can be found at http://www.php.net/. You can also use anonymous CVS to get the absolute latest version of the source. For more information, go to http://cvs.php.net/.
We only distribute precompiled binaries for Windows systems, as we are not able to compile PHP for every major Linux/Unix platform with every extension combination. Also note, that many Linux distributions come with PHP built in these days. Windows binaries can be downloaded from our Downloads page, for Linux binaries, please visit your distributions website.
Nota: Those marked with * are not thread-safe libraries, and should not be used with PHP as a server module in the multi-threaded Windows web servers (IIS, Netscape). This does not matter in Unix environments, yet.
LDAP (Unix/Win) : Netscape Directory (LDAP) SDK 1.1.
Berkeley DB2 (Unix/Win) : http://www.sleepycat.com/.
Sybase-CT* (Linux, libc5) : Available locally.
You will need to follow instructions provided with the library. Some of these libraries are detected automatically when you run the 'configure' script of PHP (such as the GD library), and others you will have to enable using '--with-EXTENSION' options to 'configure'. Run 'configure --help' for a listing of these.
5. I got the latest version of the PHP source code from the CVS repository on my Windows machine, what do I need to compile it?
First, you will need Microsoft Visual C++ v6 (v5 may do it also, but we do it with v6), and you will need some support files. See the manual section about building PHP from source on Windows.
You can find a browscap.ini file at http://www.garykeith.com/browsers/downloads.asp.
This section holds common questions about relation between PHP and databases. Yes, PHP can access virtually any database available today.
On Windows machines, you can simply use the included ODBC support and the correct ODBC driver.
On Unix machines, you can use the Sybase-CT driver to access Microsoft SQL Servers because they are (at least mostly) protocol-compatible. Sybase has made a free version of the necessary libraries for Linux systems. For other Unix operating systems, you need to contact Sybase for the correct libraries. Also see the answer to the next question.
Yes. You already have all the tools you need if you are running entirely under Windows 9x/Me, or NT/2000, where you can use ODBC and Microsoft's ODBC drivers for Microsoft Access databases.
If you are running PHP on a Unix box and want to talk to MS Access on a Windows box you will need Unix ODBC drivers. OpenLink Software has Unix-based ODBC drivers that can do this. There is a free pilot program where you can download an evaluation copy that doesn't expire and prices start at $675 for the commercial supported version.
Another alternative is to use an SQL server that has Windows ODBC drivers and use that to store the data, which you can then access from Microsoft Access (using ODBC) and PHP (using the built in drivers), or to use an intermediary file format that Access and PHP both understand, such as flat files or dBase databases. On this point Tim Hayes from OpenLink software writes:
Using another database as an intermediary is not a good idea, when you can use ODBC from PHP straight to your database - i.e. with OpenLink's drivers. If you do need to use an intermediary file format, OpenLink have now released Virtuoso (a virtual database engine) for NT, Linux and other unix platforms. Please visit our website for a free download. |
One option that has proven successful is to use MySQL and its MyODBC drivers on Windows and synchronizing the databases. Steve Lawrence writes:
Install MySQL on your platform according to instructions with MySQL. Latest available from http://www.mysql.com/ (get it from your mirror!). No special configuration required except when you set up a database, and configure the user account, you should put % in the host field, or the host name of the Windows computer you wish to access MySQL with. Make a note of your server name, username, and password.
Download the MyODBC for Windows driver from the MySQL site. Latest release is myodbc-2_50_19-win95.zip (NT available too, as well as source code). Install it on your Windows machine. You can test the operation with the utilities included with this program.
Create a user or system dsn in your ODBC administrator, located in the control panel. Make up a dsn name, enter your hostname, user name, password, port, etc for you MySQL database configured in step 1.
Install Access with a full install, this makes sure you get the proper add-ins.. at the least you will need ODBC support and the linked table manager.
Now the fun part! Create a new access database. In the table window right click and select Link Tables, or under the file menu option, select Get External Data and then Link Tables. When the file browser box comes up, select files of type: ODBC. Select System dsn and the name of your dsn created in step 3. Select the table to link, press OK, and presto! You can now open the table and add/delete/edit data on your MySQL server! You can also build queries, import/export tables to MySQL, build forms and reports, etc.
Tips and Tricks:
You can construct your tables in Access and export them to MySQL, then link them back in. That makes table creation quick.
When creating tables in Access, you must have a primary key defined in order to have write access to the table in access. Make sure you create a primary key in MySQL before linking in access
If you change a table in MySQL, you have to re-link it in Access. Go to tools>add-ins>linked table manager, cruise to your ODBC DSN, and select the table to re-link from there. you can also move your dsn source around there, just hit the always prompt for new location checkbox before pressing OK.
3. I upgraded to PHP 4, and now mysql keeps telling me "Warning: MySQL: Unable to save result set in ...". What's up?
Most likely what has happened is, PHP 4 was compiled with the '--with-mysql' option, without specifying the path to MySQL. This means PHP is using its built-in MySQL client library. If your system is running applications, such as PHP 3 as a concurrent Apache module, or auth-mysql, that use other versions of MySQL clients, then there is a conflict between the two differing versions of those clients.
Recompiling PHP 4, and adding the path to MySQL to the flag, '--with-mysql=/your/path/to/mysql' usually solves the problem.
4. After installing shared MySQL support, Apache dumps core as soon as libphp4.so is loaded. Can this be fixed?
If your MySQL libs are linked against pthreads this will happen. Check using ldd. If they are, grab the MySQL tarball and compile from source, or recompile from the source rpm and remove the switch in the spec file that turns on the threaded client code. Either of these suggestions will fix this. Then recompile PHP with the new MySQL libs.
5. Why do I get an error that looks something like this: "Warning: 0 is not a MySQL result index in <file> on line <x>" or "Warning: Supplied argument is not a valid MySQL result resource in <file> on line <x>?
You are trying to use a result identifier that is 0. The 0 indicates that your query failed for some reason. You need to check for errors after submitting a query and before you attempt to use the returned result identifier. The proper way to do this is with code similar to the following:
$result = mysql_query("SELECT * FROM tables_priv"); if (!$result) { echo mysql_error(); exit; } |
$result = mysql_query("SELECT * FROM tables_priv") or die("Bad query: ".mysql_error()); |
This section holds common questions about the way to install PHP. PHP is available for almost any OS (except maybe for MacOS before OSX), and almost any web server.
To install PHP, follow the instructions in the INSTALL file located in the distribution. Windows users should also read the install.txt file. There are also some helpful hints for Windows users here.
[mybox:user /src/php4] root# apachectl configtest apachectl: /usr/local/apache/bin/httpd Undefined symbols: _compress _uncompress |
cgi error: The specified CGI application misbehaved by not returning a complete set of HTTP headers. The headers it did return are: |
By default on UNIX it should be in /usr/local/lib which is <install-path>/lib. Most people will want to change this at compile-time with the --with-config-file-path flag. You would, for example, set it with something like:
--with-config-file-path=/etc |
On Windows the default path for the php.ini file is the Windows directory. If you're using the Apache webserver, php.ini is first searched in the Apaches install directory, e.g. c:\program files\apache group\apache. This way you can have different php.ini files for different versions of Apache on the same machine.
See also the chapter about the configuration file.
2. Unix: I installed PHP, but every time I load a document, I get the message 'Document Contains No Data'! What's going on here?
This probably means that PHP is having some sort of problem and is core-dumping. Look in your server error log to see if this is the case, and then try to reproduce the problem with a small test case. If you know how to use 'gdb', it is very helpful when you can provide a backtrace with your bug report to help the developers pinpoint the problem. If you are using PHP as an Apache module try something like:
Stop your httpd processes
gdb httpd
Stop your httpd processes
> run -X -f /path/to/httpd.conf
Then fetch the URL causing the problem with your browser
> run -X -f /path/to/httpd.conf
If you are getting a core dump, gdb should inform you of this now
type: bt
You should include your backtrace in your bug report. This should be submitted to http://bugs.php.net/
If your script uses the regular expression functions (ereg() and friends), you should make sure that you compiled PHP and Apache with the same regular expression package. This should happen automatically with PHP and Apache 1.3.x
3. Unix: I installed PHP using RPMS, but Apache isn't processing the PHP pages! What's going on here?
Assuming you installed both Apache and PHP from RPM packages, you need to uncomment or add some or all of the following lines in your http.conf file:
# Extra Modules AddModule mod_php.c AddModule mod_php3.c AddModule mod_perl.c # Extra Modules LoadModule php_module modules/mod_php.so LoadModule php3_module modules/libphp3.so /* for PHP 3 */ LoadModule php4_module modules/libphp4.so /* for PHP 4 */ LoadModule perl_module modules/libperl.so |
AddType application/x-httpd-php3 .php3 /* for PHP 3 */ AddType application/x-httpd-php .php /* for PHP 4 */ |
4. Unix: I installed PHP 3 using RPMS, but it doesn't compile with the database support I need! What's going on here?
Due to the way PHP 3 built, it is not easy to build a complete flexible PHP RPM. This issue is addressed in PHP 4. For PHP 3, we currently suggest you use the mechanism described in the INSTALL.REDHAT file in the PHP distribution. If you insist on using an RPM version of PHP 3, read on...
The RPM packagers are setting up the RPMS to install without database support to simplify installations and because RPMS use /usr/ instead of the standard /usr/local/ directory for files. You need to tell the RPM spec file which databases to support and the location of the top-level of your database server.
This example will explain the process of adding support for the popular MySQL database server, using the mod installation for Apache.
Of course all of this information can be adjusted for any database server that PHP supports. We will assume you installed MySQL and Apache completely with RPMS for this example as well.
First remove mod_php3 :
rpm -e mod_php3 |
Then get the source rpm and INSTALL it, NOT --rebuild
rpm -Uvh mod_php3-3.0.5-2.src.rpm |
Then edit the /usr/src/redhat/SPECS/mod_php3.spec file
In the %build section add the database support you want, and the path.
For MySQL you would add
--with-mysql=/usr \ |
./configure --prefix=/usr \ --with-apxs=/usr/sbin/apxs \ --with-config-file-path=/usr/lib \ --enable-debug=no \ --enable-safe-mode \ --with-exec-dir=/usr/bin \ --with-mysql=/usr \ --with-system-regex |
Once this modification is made then build the binary rpm as follows:
rpm -bb /usr/src/redhat/SPECS/mod_php3.spec |
Then install the rpm
rpm -ivh /usr/src/redhat/RPMS/i386/mod_php3-3.0.5-2.i386.rpm |
5. Unix: I patched Apache with the FrontPage extensions patch, and suddenly PHP stopped working. Is PHP incompatible with the Apache FrontPage extensions?
No, PHP works fine with the FrontPage extensions. The problem is that the FrontPage patch modifies several Apache structures, that PHP relies on. Recompiling PHP (using 'make clean ; make') after the FP patch is applied would solve the problem.
6. Unix/Windows: I have installed PHP, but when I try to access a PHP script file via my browser, I get a blank screen.
Do a 'view source' in the web browser and you will probably find that you can see the source code of your PHP script. This means that the web server did not send the script to PHP for interpretation. Something is wrong with the server configuration - double check the server configuration against the PHP installation instructions.
7. Unix/Windows: I have installed PHP, but when try to access a PHP script file via my browser, I get a server 500 error.
Something went wrong when the server tried to run PHP. To get to see a sensible error message, from the command line, change to the directory containing the PHP executable (php.exe on Windows) and run php -i. If PHP has any problems running, then a suitable error message will be displayed which will give you a clue as to what needs to be done next. If you get a screen full of html codes (the output of the phpinfo() function) then PHP is working, and your problem may be related to your server configuration which you should double check.
8. Some operating systems: I have installed PHP without errors, but when I try to start apache I get undefined symbol errors:
[mybox:user /src/php4] root# apachectl configtest apachectl: /usr/local/apache/bin/httpd Undefined symbols: _compress _uncompress |
This has actually nothing to do with PHP, but with the MySQL client libraries. Some need --with-zlib, others do not. This is also covered in the MySQL FAQ.
9. Windows: I have installed PHP, but when I to access a PHP script file via my browser, I get the error:
cgi error: The specified CGI application misbehaved by not returning a complete set of HTTP headers. The headers it did return are: |
This error message means that PHP failed to output anything at all. To get to see a sensible error message, from the command line, change to the directory containing the PHP executable (php.exe on Windows) and run php -i. If PHP has any problems running, then a suitable error message will be displayed which will give you a clue as to what needs to be done next. If you get a screen full of html codes (the output of the phpinfo() function) then PHP is working.
Once PHP is working at the command line, try accessing the script via the browser again. If it still fails then it could be one of the following:
File permissions on your PHP script, php.exe, php4ts.dll, php.ini or any PHP extensions you are trying to load are such that the anonymous internet user ISUR_<machinename> cannot access them.
The script file does not exist (or possibly isn't where you think it is relative to your web root directory). Note that for IIS you can trap this error by ticking the 'check file exists' box when setting up the script mappings in the Internet Services Manager. If a script file does not exist then the server will return a 404 error instead. There is also the additional benefit that IIS will do any authentication required for you based on the NTLanMan permissions on your script file.
Make sure any user who needs to run a PHP script has the rights to run php.exe! IIS uses an anonymous user which is added at the time IIS is installed. This user needs rights to php.exe. Also, any authenticated user will also need rights to execute php.exe. And for IIS4 you need to tell it that PHP is a script engine. Also, you will want to read this faq.
11. When running PHP as CGI with IIS, PWS, OmniHTTPD or Xitami, I get the following error: Security Alert! PHP CGI cannot be accessed directly..
You must set the cgi.force_redirect directive to 0. It defaults to 1 so be sure the directive isn't commented out (with a ;). Like all directives, this is set in php.ini
Because the default is 1, it's critical that you're 100% sure that the correct php.ini file is being read. Read this faq for details.
12. How do I know if my php.ini is being found and read? It seems like it isn't as my changes aren't being implemented.
To be sure your php.ini is being read by PHP, make a call to phpinfo() and near the top will be a listing called Configuration File (php.ini). This will tell you where PHP is looking for php.ini and whether or not it's being read. If just a directory PATH exists than it's not being read and you should put your php.ini in that directory. If php.ini is included within the PATH than it is being read.
If php.ini is being read and you're running PHP as a module then be sure to restart PHP after making changes to php.ini
This section gathers most common errors that occur at build time.
1. I got the latest version of PHP using the anonymous CVS service, but there's no configure script!
You have to have the GNU autoconf package installed so you can generate the configure script from configure.in. Just run ./buildconf in the top-level directory after getting the sources from the CVS server. (Also, unless you run configure with the --enable-maintainer-mode option, the configure script will not automatically get rebuilt when the configure.in file is updated, so you should make sure to do that manually when you notice configure.in has changed. One symptom of this is finding things like @VARIABLE@ in your Makefile after configure or config.status is run.)
2. I'm having problems configuring PHP to work with Apache. It says it can't find httpd.h, but it's right where I said it is!
You need to tell the configure/setup script the location of the top-level of your Apache source tree. This means that you want to specify --with-apache=/path/to/apache and not --with-apache=/path/to/apache/src.
3. While configuring PHP (./configure), you come across an error similar to the following:
checking lex output file root... ./configure: lex: command not found configure: error: cannot find output from lex; giving up |
Be sure to read the installation instructions carefully and note that you need both flex and bison installed to compile PHP. Depending on your setup you will install bison and flex from either source or a package, such as a RPM.
4. When I try to start Apache, I get the the following message:
fatal: relocation error: file /path/to/libphp4.so: symbol ap_block_alarms: referenced symbol not found |
This error usually comes up when one compiles the Apache core program as a DSO library for shared usage. Try to reconfigure apache, making sure to use at least the following flags:
--enable-shared=max --enable-rule=SHARED_CORE |
For more information, read the top-level Apache INSTALL file or the Apache DSO manual page.
5. When I run configure, it says that it can't find the include files or library for GD, gdbm, or some other package!
You can make the configure script looks for header files and libraries in non-standard locations by specifying additional flags to pass to the C preprocessor and linker, such as:
CPPFLAGS=-I/path/to/include LDFLAGS=-L/path/to/library ./configure |
env CPPFLAGS=-I/path/to/include LDFLAGS=-L/path/to/library ./configure |
6. When it is compiling the file language-parser.tab.c, it gives me errors that say yytname undeclared.
You need to update your version of Bison. You can find the latest version at ftp://ftp.gnu.org/pub/gnu/bison/.
7. When I run make, it seems to run fine but then fails when it tries to link the final application complaining that it can't find some files.
Some old versions of make that don't correctly put the compiled versions of the files in the functions directory into that same directory. Try running cp *.o functions and then re-running make to see if that helps. If it does, you should really upgrade to a recent version of GNU make.
Take a look at the link line and make sure that all of the appropriate libraries are being included at the end. Common ones that you might have missed are '-ldl' and any libraries required for any database support you included.
If you're linking with Apache 1.2.x, did you remember to add the appropriate information to the EXTRA_LIBS line of the Configuration file and re-rerun Apache's Configure script? See the INSTALL file that comes with the distribution for more information.
Some people have also reported that they had to add '-ldl' immediately following libphp4.a when linking with Apache.
This is actually quite easy. Follow these steps carefully:
Grab the latest Apache 1.3 distribution from http://www.apache.org/dist/.
Ungzip and untar it somewhere, for example /usr/local/src/apache-1.3.
Compile PHP by first running ./configure --with-apache=/<path>/apache-1.3 (substitute <path> for the actual path to your apache-1.3 directory.
Type make followed by make install to build PHP and copy the necessary files to the Apache distribution tree.
Change directories into to your /<path>/apache-1.3/src directory and edit the Configuration file. Add to the file: AddModule modules/php4/libphp4.a.
Type: ./Configure followed by make.
You should now have a PHP-enabled httpd binary!
Note: You can also use the new Apache ./configure script. See the instructions in the README.configure file which is part of your Apache distribution. Also have a look at the INSTALL file in the PHP distribution.
10. I have followed all the steps to install the Apache module version on UNIX, and my PHP scripts show up in my browser or I am being asked to save the file.
This means that the PHP module is not getting invoked for some reason. Three things to check before asking for further help:
Make sure that the httpd binary you are running is the actual new httpd binary you just built. To do this, try running: /path/to/binary/httpd -l
If you don't see mod_php4.c listed then you are not running the right binary. Find and install the correct binary.
Make sure you have added the correct Mime Type to one of your Apache .conf files. It should be: AddType application/x-httpd-php3 .php3 (for PHP 3)
or AddType application/x-httpd-php .php (for PHP 4)
Also make sure that this AddType line is not hidden away inside a <Virtualhost> or <Directory> block which would prevent it from applying to the location of your test script.
Finally, the default location of the Apache configuration files changed between Apache 1.2 and Apache 1.3. You should check to make sure that the configuration file you are adding the AddType line to is actually being read. You can put an obvious syntax error into your httpd.conf file or some other obvious change that will tell you if the file is being read correctly.
11. It says to use: --activate-module=src/modules/php4/libphp4.a, but that file doesn't exist, so I changed it to --activate-module=src/modules/php4/libmodphp4.a and it doesn't work!? What's going on?
Note that the libphp4.a file is not supposed to exist. The apache process will create it!
12. When I try to build Apache with PHP as a static module using --activate-module=src/modules/php4/libphp4.a it tells me that my compiler is not ANSI compliant.
This is a misleading error message from Apache that has been fixed in more recent versions.
There are three things to check here. First, for some reason when Apache builds the apxs Perl script, it sometimes ends up getting built without the proper compiler and flags variables. Find your apxs script (try the command which apxs, it's sometimes found in /usr/local/apache/bin/apxs or /usr/sbin/apxs. Open it and check for lines similar to these:
my $CFG_CFLAGS_SHLIB = ' '; # substituted via Makefile.tmpl my $CFG_LD_SHLIB = ' '; # substituted via Makefile.tmpl my $CFG_LDFLAGS_SHLIB = ' '; # substituted via Makefile.tmpl |
my $CFG_CFLAGS_SHLIB = '-fpic -DSHARED_MODULE'; # substituted via Makefile.tmpl my $CFG_LD_SHLIB = 'gcc'; # substituted via Makefile.tmpl my $CFG_LDFLAGS_SHLIB = q(-shared); # substituted via Makefile.tmpl |
my $CFG_LIBEXECDIR = 'modules'; # substituted via APACI install |
my $CFG_LIBEXECDIR = '/usr/lib/apache'; # substituted via APACI install |
During the make portion of installation, if you encounter problems that look similar to this:
microtime.c: In function `php_if_getrusage': microtime.c:94: storage size of `usg' isn't known microtime.c:97: `RUSAGE_SELF' undeclared (first use in this function) microtime.c:97: (Each undeclared identifier is reported only once microtime.c:97: for each function it appears in.) microtime.c:103: `RUSAGE_CHILDREN' undeclared (first use in this function) make[3]: *** [microtime.lo] Error 1 make[3]: Leaving directory `/home/master/php-4.0.1/ext/standard' make[2]: *** [all-recursive] Error 1 make[2]: Leaving directory `/home/master/php-4.0.1/ext/standard' make[1]: *** [all-recursive] Error 1 make[1]: Leaving directory `/home/master/php-4.0.1/ext' make: *** [all-recursive] Error 1 |
Your system is broken. You need to fix your /usr/include files by installing a glibc-devel package that matches your glibc. This has absolutely nothing to do with PHP. To prove this to yourself, try this simple test:
$ cat >test.c <<X #include <sys/resource.h> X $ gcc -E test.c >/dev/null |
15. I want to upgrade my PHP. Where can I find the ./configure line that was used to build my current PHP installation?
Either you look at config.nice file, in the source tree of your current PHP installation or, if this is not available, you simply run a
<?php phpinfo(); ?> |
This section gathers most common errors you can face, while writing PHP scripts.
function myfunc($argument) { echo $argument + 10; } $variable = 10; echo "myfunc($variable) = " . myfunc($variable); |
<pre> <?php echo "This should be the first line."; ?> <?php echo "This should show up after the new line above."; ?> </pre> |
1. I would like to write a generic PHP script that can handle data coming from any form. How do I know which POST method variables are available?
Make sure that the track_vars feature is enabled in your php.ini file. Since PHP 4.0.3, this feature is always on. When track_vars is on, it creates some associative arrays, the most important here is: $_POST (this used to be called $HTTP_POST_VARS in PHP versions prior 4.1.0). So, to write a generic script to handle POST method variables you would need something similar to the following:
foreach ($_POST as $var => $value) { echo "$var = $value<br>\n"; } |
2. I need to convert all single-quotes (') to a backslash followed by a single-quote. How can I do this with a regular expression?
First off, take a look at the addslashes() function. It will do exactly what you want. You should also have a look at the magic_quotes_gpc directive in your php.ini file.
4. Hey, what happened to my newlines?
<pre> <?php echo "This should be the first line."; ?> <?php echo "This should show up after the new line above."; ?> </pre> |
In PHP, the ending for a block of code is either "?>" or "?>\n" (where \n means a newline). So in the example above, the echoed sentences will be on one line, because PHP omits the newlines after the block ending. This means that you need to insert an extra newline after each block of PHP code to make it print out one newline.
Why does PHP do this? Because when formatting normal HTML, this usually makes your life easier because you don't want that newline, but you'd have to create extremely long lines or otherwise make the raw page source unreadable to achieve that effect.
5. I get the message 'Warning: Cannot send session cookie - headers already sent...' or 'Cannot add header information - headers already sent...'.
The functions header(), setcookie() and the session functions need to add headers to the output stream. But headers can only be sent before all other content, check if your script is sending headers after having already sent content.
The getallheaders() function will do this if you are running PHP as an Apache module. So, the following bit of code will show you all the request headers:
$headers = getallheaders(); foreach ($headers as $name => $content) { echo "headers[$name] = $content<br>\n"; } |
The security model of IIS is at fault here. This is a problem common to all CGI programs running under IIS. A workaround is to create a plain HTML file (not parsed by PHP) as the entry page into an authenticated directory. Then use a META tag to redirect to the PHP page, or have a link to the PHP page. PHP will then recognize the authentication correctly. With the ISAPI module, this is not a problem. This should not effect other NT web servers. For more information, see: http://support.microsoft.com/support/kb/articles/q160/4/22.asp.
8. My PHP script works on IE and Lynx, but on Netscape some of my output is missing. When I do a "View Source" I see the content in IE but not in Netscape.
Netscape is more strict regarding html tags (such as tables) then IE. Running your html output through a html validator, such as validator.w3.org, might be helpful. For example, a missing </table> might cause this.
Also, both IE and Lynx ignore any NULs (\0) in the HTML stream, Netscape does not. The best way to check for this is to compile the command line version of PHP (also known as the CGI version) and run your script from the command line. In *nix, pipe it through od -c and look for any \0 characters. If you are on Windows you need to find an editor or some other program that lets you look at binary files. When Netscape sees a NUL in a file it will typically not output anything else on that line whereas both IE and Lynx will.
You need to turn off the short tags by setting short_tags to 0 in your php.ini file, or by using the appropriate Apache directive. You could even use a <File> section to do this selectively.
10. How can I use PHP with FrontPage or some other HTML editor that insists on moving my code around?
One of the easiest things to do is to enable using ASP tags in your PHP code. This allows you to use the ASP-style <% and %> code delimiters. Some of the popular HTML editors handle those more intelligently (for now). To enable the ASP-style tags, you need to set the asp_tags php.ini variable, or use the appropriate Apache directive.
11. Where can I find a complete list of pre-set variables available to me, and why are these not documented in the PHP documentation?
The best way is to stick a <?php phpinfo(); ?> part on a page and load it up. This will show you all sorts of information about your PHP setup, including a list of both environment variables and also special variables set by your web server. This list can't really be documented in the PHP documentation because it will change from one server to another.
12. I'm trying to access one of the standard CGI variables (such as $DOCUMENT_ROOT or $HTTP_REFERER) in a user-defined function, and it can't seem to find it. What's wrong?
Environment variables are normal global variables, so you must either declare them as global variables in your function (by using "global $DOCUMENT_ROOT;", for example) or by using the global variable array (ie, "$GLOBALS["DOCUMENT_ROOT"]").
Nota: Since PHP 4.1.0 you can also use the superglobal array $_SERVER which is available in every function. For example, you can now use $_SERVER["DOCUMENT_ROOT"] instead of $DOCUMENT_ROOT.
PHP and HTML interact a lot: PHP can generate HTML, and HTML can pass information to PHP. Before reading these faqs, it's important you learn how to retrieve variables from outside of PHP. The manual page on this topic includes many examples as well. Pay close attention to what register_globals means to you too.
There are several stages for which encoding is important. Assuming that you have a string $data, which contains the string you want to pass on in a non-encoded way, these are the relevant stages:
HTML interpretation. In order to specify a random string, you must include it in double quotes, and htmlspecialchars() the whole value.
URL: A URL consists of several parts. If you want your data to be interpreted as one item, you must encode it with urlencode().
Nota: It is wrong to urlencode() $data, because it's the browsers responsibility to urlencode() the data. All popular browsers do that correctly. Note that this will happen regardless of the method (i.e., GET or POST). You'll only notice this in case of GET request though, because POST requests are usually hidden.
Nota: The data is shown in the browser as intended, because the browser will interpret the HTML escaped symbols.
Upon submitting, either via GET or POST, the data will be urlencoded by the browser for transferring, and directly urldecoded by PHP. So in the end, you don't need to do any urlencoding/urldecoding yourself, everything is handled automagically.
Nota: In fact you are faking a HTML GET request, therefore it's necessary to manually urlencode() the data.
Nota: You need to htmlspecialchars() the whole URL, because the URL occurs as value of an HTML-attribute. In this case, the browser will first un-htmlspecialchars() the value, and then pass the URL on. PHP will understand the URL correctly, because you urlencoded() the data.
You'll notice that the & in the URL is replaced by &. Although most browsers will recover if you forget this, this isn't always possible. So even if your URL is not dynamic, you need to htmlspecialchars() the URL.
2. I'm trying to use an <input type="image"> tag, but the $foo.x and $foo.y variables aren't available. $_GET['foo.x'] isn't existing either. Where are they?
When submitting a form, it is possible to use an image instead of the standard submit button with a tag like:
<input type="image" src="image.gif" name="foo"> |
Because foo.x and foo.y would make invalid variable names in PHP, they are automagically converted to foo_x and foo_y. That is, the periods are replaced with underscores. So, you'd access these variables like any other described within the section on retrieving variables from outside of PHP. For example, $_GET['foo_x'].
To get your <form> result sent as an array to your PHP script you name the <input>, <select> or <textarea> elements like this:
<input name="MyArray[]"> <input name="MyArray[]"> <input name="MyArray[]"> <input name="MyArray[]"> |
<input name="MyArray[]"> <input name="MyArray[]"> <input name="MyOtherArray[]"> <input name="MyOtherArray[]"> |
<input name="AnotherArray[]"> <input name="AnotherArray[]"> <input name="AnotherArray[email]"> <input name="AnotherArray[phone]"> |
Nota: Specifying an arrays key is optional in HTML. If you do not specify the keys, the array gets filled in the order the elements appear in the form. Our first example will contain keys 0, 1, 2 and 3.
See also Array Functions and Variables from outside PHP.
The select multiple tag in an HTML construct allows users to select multiple items from a list. These items are then passed to the action handler for the form. The problem is that they are all passed with the same widget name. ie.
<select name="var" multiple> |
var=option1 var=option2 var=option3 |
<select name="var[]" multiple> |
Note that if you are using JavaScript the [] on the element name might cause you problems when you try to refer to the element by name. Use it's numerical form element ID instead, or enclose the variable name in single quotes and use that as the index to the elements array, for example:
variable = documents.forms[0].elements['var[]']; |
PHP can be used to access COM and DCOM objects on Win32 platforms.
If this is a simple DLL there is no way yet to run it from PHP. If the DLL contains a COM server you may be able to access it if it implements the IDispatch interface.
There are dozens of VARIANT types and combinations of them. Most of them are already supported but a few still have to be implemented. Arrays are not completely supported. Only single dimensional indexed only arrays can be passed between PHP and COM. If you find other types that aren't supported, please report them as a bug (if not already reported) and provide as much information as available.
Generally it is, but as PHP is mostly used as a web scripting language it runs in the web servers context, thus visual objects will never appear on the servers desktop. If you use PHP for application scripting e.g. in conjunction with PHP-GTK there is no limitation in accessing and manipulating visual objects through COM.
No, you can't. COM instances are treated as resources and therefore they are only available in a single script's context.
Currently it's not possible to trap COM errors beside the ways provided by PHP itself (@, track_errors, ..), but we are thinking of a way to implement this.
No, unfortunately there is no such tool available for PHP.
7. What does 'Unable to obtain IDispatch interface for CLSID {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}' mean ?
This error can have multiple reasons:
the CLSID is wrong
the requested DLL is missing
the requested component doesn't implement the IDispatch interface
Exactly like you run local objects. You only have to pass the IP of the remote machine as second parameter to the COM constructor.
Make sure that you have set com.allow_dcom=true in your php.ini.
Edit your php.ini and set com.allow_dcom=true.
This has nothing to do with PHP. ActiveX objects are loaded on client side if they are requested by the HTML document. There is no relation to the PHP script and therefore there is no direct server side interaction possible.
This is possible with the help of monikers. If you want to get multiple references to the same word instance you can create that instance like shown:
$word = new COM("C:\docs\word.doc"); |
This will create a new instance if there is no running instance available or it will return a handle to the running instance, if available.
Starting in PHP 4.3.0, you can define an event sink and bind it as shown in the example below. You can use com_print_typeinfo() to have PHP generate a skeleton for the event sink class.
Exemplo 52-1. COM event sink example
|
13. I'm having problems when trying to invoke a method of a COM object which exposes more than one interface. What can I do ?
The answer is as simple as unsatisfying. I don't know exactly but i think you can do nothing. If someone has specific information about this, please let me know :)
COM+ extends COM by a framework for managing components through MTS and MSMQ but there is nothing special that PHP has to support to use such components.
15. If PHP can manipulate COM objects, can we imagine to use MTS to manage components resources, in conjunction with PHP ?
PHP itself doesn't handle transactions yet. Thus if an error occurs no rollback is initiated. If you use components that support transactions you will have to implement the transaction management yourself.
PHP is the best language for web programing, but what about other languages?
ASP is not really a language in itself, it's an acronym for Active Server Pages, the actual language used to program ASP with is Visual Basic Script or JScript. The biggest drawback of ASP is that it's a proprietary system that is natively used only on Microsoft Internet Information Server (IIS). This limits it's availability to Win32 based servers. There are a couple of projects in the works that allows ASP to run in other environments and webservers: InstantASP from Halcyon (commercial), Chili!Soft ASP from Chili!Soft (commercial) and OpenASP from ActiveScripting.org (free). ASP is said to be a slower and more cumbersome language than PHP, less stable as well. Some of the pros of ASP is that since it primarily uses VBScript it's relatively easy to pick up the language if you're already know how to program in Visual Basic. ASP support is also enabled by default in the IIS server making it easy to get up and running. The components built in ASP are really limited, so if you need to use "advanced" features like interacting with FTP servers, you need to buy additional components.
Yes, asp2php is the one most often referred to.
PHP is commonly said to be faster and more efficient for complex programming tasks and trying out new ideas. PHP is generally referred to as more stable and less resource intensive as well. Cold Fusion has better error handling, database abstraction and date parsing although database abstraction is addressed in PHP 4. Another thing that is listed as one of Cold Fusion's strengths is its excellent search engine, but it has been mentioned that a search engine is not something that should be included in a web scripting language. PHP runs on almost every platform there is; Cold Fusion is only available on Win32, Solaris, Linux and HP/UX. Cold Fusion has a good IDE and is generally easier to get started with, whereas PHP initially requires more programming knowledge. Cold Fusion is designed with non-programmers in mind, while PHP is focused on programmers.
A great summary by Michael J Sheldon on this topic has been posted to the PHP mailing list. A copy can be found here.
The biggest advantage of PHP over Perl is that PHP was designed for scripting for the web where Perl was designed to do a lot more and can because of this get very complicated. The flexibility / complexity of Perl makes it easier to write code that another author / coder has a hard time reading. PHP has a less confusing and stricter format without losing flexibility. PHP is easier to integrate into existing HTML than Perl. PHP has pretty much all the 'good' functionality of Perl: constructs, syntax and so on, without making it as complicated as Perl can be. Perl is a very tried and true language, it's been around since the late eighties, but PHP is maturing very quickly.
PHP has already a long history behind him: Legendary PHP 1.0, PHP/FI, PHP 3.0 and PHP 4.0.
PHP/FI 2.0 is no longer supported. Please see appropriate manual section for information about migration from PHP/FI 2.0.
If you are still working with PHP 2, we strongly recommend you to upgrade straight to PHP 4.
PHP has already a long history behind him : Legendary PHP 1.0, PHP/FI, PHP 3.0 and PHP 4.0.
PHP 4 was designed to be as compatible with earlier versions of PHP as possible and very little functionality was broken in the process. If you're really unsure about compatibility you should install PHP 4 in a test environment and run your scripts there.
Also see the appropriate migration appendix of this manual.
There can be some questions we can't put into other categories. Here you can find them.
The yellow pop-up windows on the old site were pretty cool, but were very difficult to maintain (since some companies seem to enjoy changing the way their browsers work with every new release).
All the code for previous versions of the website is still available through CVS. Specifically, the last version of shared.inc (that had all the Javascript and DHTML to do the popups) is available here.
If you don't have an archiver-tool to handle bz2 files download the commandline tool from Redhat (please find further information below).
If you would not like to use a command line tool, you can try free tools like Stuffit Expander, UltimateZip, 7-Zip, or Quick Zip. If you have tools like WinRAR or Power Archiver, you can easily decompress the bz2 files with it. If you use Windows Commander, a bz2 plugin for that program is available freely from the Windows Commander site.
The bzip2 commandline tool from Redhat:
Win2k Sp2 users grab the latest version 1.0.2, all other Windows user should grab version 1.00. After downloading rename the executable to bzip2.exe. For convenience put it into a directory in your path, e.g. C:\Windows where C represents your windows installation drive.
Note: lang stands for your language and x for the desired format, e.g.: pdf. To uncompress the php_manual_lang.x.bz2 follow these simple instructions:
open a command prompt window
cd to the folder where you stored the downloaded php_manual_lang.x.bz2
invoke bzip2 -d php_manual_lang.x.bz2, extracting php_manual_lang.x in the same folder
In case you downloaded the php_manual_lang.tar.bz2 with many html-files in it, the procedure is the same. The only difference is that you got a file php_manual_lang.tar. The tar format is known to be treated with most common archivers on Windows like e.g. WinZip.
O PHP percorreu um longo caminho ao nesses poucos anos. Criada para ser uma das mais poderosas e proeminentes linguagens da Web não foi uma tarefa fácil. Aqueles que se interessaram momentaneamente em ver como o PHP cresceu e se tornou o que é hoje, continue lendo.
O PHP sucede de um produto mais antigo, chamado PHP/FI. PHP/FI foi criado por Rasmus Lerdorf em 1995, inicialmente como simples scripts Perl como estatísticas de acesso para seu currículo online. Ele nomeou esta sério de script para 'Personal Home Page Tools'. Como mais funcionalidades foram requeridas, Rasmus escreveu uma implementação C muito maior, que era capaz de comunicar-se com base de dados, e possibilitava à usuários desenvolver simples aplicativos dinâmicos para Web. Rasmus decidiu disponibilizar o código fonte do PHP/FI para que todos pudessem ver, e também usá-lo, bem como fixar bugs e melhorar o código.
PHP/FI, que significa Personal Home Page / Forms Interpreter, incluía algumas funcionalidades básicas do PHP que nós conhecemos hoje. Ele usava variáveis no estilo Perl, interpretação automática de variáveis vindas de formulário e sintaxe embutida no HTML. A sua própria sintaxe era similar a do Perl, porém muito mais limitada, simples, e um pouco inconsistente.
Em 1997, PHP/FI 2.0, a segunda versão da implementação C, obteve milhares de usuários ao redor do mundo (estimado), com aproximadamente 50,000 domínios reportando que tinha PHP/FI 2.0 instalado, agarinhando 1% dos domínios da Internet. Enquanto isto havia milhares de pessoas contribuindo com pequenos códigos para o projeto, e ainda assim By 1997, PHP/FI 2.0, the second write-up of the C implementation, had a cult of several thousand users around the world (estimated), with approximately 50,000 domains reporting as having it installed, accounting for about 1% of the domains on the Internet. While there were several people contributing bits of code to this project, it was still at large a one-man project.
O PHP/FI 2.0 foi oficialmente lançado somente em Novembro de 1997, após perder a maior parte de sua vida em versões betas. Ele foi rapidamente substituído pelos alphas do PHP 3.0.
O PHP 3.0 foi a primeira versão que se assemelha ao PHP que nós conhecemos hoje. Ela foi criada por Andi Gutmans e Zeev Suraski em 1997 e foi totalmente reescrito, após eles descobrirem que o PHP/FI 2.0 poderia ajudá-los a desenvolver suas próprias aplicações de eCommerce. No esforço cooperativo e iniciativa de começar o PHP/FI à partir da base-usuário existente, Andi, Rasmus e Zeev decidiram cooperar e anunciar o PHP 3.0 como uma versão oficial de seu sucessor o PHP/FI 2.0, e o desenvolvimento do PHP/FI 2.0 foram descontinuados.
Uma das maiores características do PHP 3.0 era sua forte capacidade de extensibilidade. Além de oferecer aos usuários finais uma infraestrutura sólida para diversos bancos de dados, protocolos e APIs, o extensibilidade do PHP 3.0 atraí dezenas de desenvolvedores para se juntar e submeter novos módulos. Esta é a chave do tremendo sucesso do PHP 3.0. Outras características chaves introduzidas no PHP 3.0 foram o suporte à sintaxe para orientação à objetos e uma sintaxe muito mais poderosa e consistente.
A nova versão da linguagem foi realizada sob um novo nome, que removeu a impressão do limitado uso pessoal que o PHP/FI 2.0 prendeu. Ela foi nomeada simplesmente 'PHP', com o significado que é um acrônimo - PHP: Hypertext Preprocessor.
No final de 1998, o PHP obteve uma base the dezenas de milhares de usuários (estimativa) e centenas de milhares de Web sites relatando que o tinham instalado. Em seu pico, o PHP 3.0 foi instalado em aproximadamente 10% dos servidores Web da Internet.
O PHP 3.0 foi oficialmente lançado em Junho de 1998, depois de ter passado aproximadamente 9 meses em testes públicos.
No inverno de 1998, rapidamente após o PHP 3.0 ser oficialmente lançado, Andi Gutmans e Zeev Suraski começaram a reescrever o núcleo do PHP. Os objetivos do projeto eram melhorar a performance de aplicações complexas, e melhorar a modularidade do código base do PHP. Tais aplicações foram possíveis por causa das novas características do PHP 3.0 e o suporte a uma variadade de banco de dados de terceiros e APIs, mas o PHP 3.0 não foi projeto para trabalhar com aplicações muito complexas eficientemente.
A nova engine, dubbed 'Zend Engine' (conhecidos pelos seus primeiros nomes, Zeev e Andi), fazendo desse objetivo um sucesso, e foi introduzida em meados de 1999. PHP 4.0, baseado nesta engine, e acompanhado com uma série de novas características, foi oficialmente lançada em Maio de 2000, quase dois anos após o seu predecessor, o PHP 3.0. Além da altíssimo melhoramento da performance desta versão, o PHP 4.0 incluiu outras características chave como o suporte para muitos servidores WEb, sessões HTTP, buffer de saída, maneiras mais seguras de manipular input de usuários e muitas construções novas na linguagem.
PHP 4 é a última versão lanaçada do PHP. O trabalho já começou na modificação e melhoramento da Zend Engine para integrar novas características que foram designadas para o PHP 5.0.
Hoje, o PHP está começando a ser usado por centenas de milhares de desenvolvedores (estimativa), e muitos milhões de sites reportam que tem o PHP instalado, que explica os 20% de domínios da Internet.
O time de desenvolvimento do PHP contém dezenas de desenvolvedores, bem como dezenas de outros que trabalham com projetos relacionados ao PHP como o PEAR e a documentação do projeto.
O futuro do PHP é dirigido principalmente pelo seu núcleo, a Zend Engine. PHP 5 irá incluir a nova Zend Engine 2.0. Para obter mais informações sobre esta engine, veja esta página.
PEAR, o repositório da Extensão PHP e da Aplicação (originalmente, Extensão PHP e Repositório Add-on) são as versões das classes da fundação do PHP, e talvez cresçam no futuro para ser um dos caminhos chaves para distribuir o PHP em ambas extensões C e PHP entre os colaboradores.
O PEAR nasceu em discussões realizadas nas PHP Developers' Meeting-PMD (Reuniões dos Desenvolvedores do PHP-RDP) realizada em Janeiro de 2000 em Tel Aviv. Foi criada por Sitg S. Bakken, e é dedicada à sua primeira filha, Malin Bakken.
Desde o começo de 2000, o PEAR cresceu para ser um grande, e significativo projeto com um largo número de desenvolvedores trabalhando em executar tarefas comuns, funcionalidades reusáveis para o benefício de toda a comunidade PHP. Hoje em dia o PEAR incluí acesso à base de dados, cache de conteúdo, calculações matemáticas, eCommerce e muito mais.
A Iniciativa da Garantia de Qualidade do PHP foi criada no verão de 2000 em resposta às críticas sobre as versões do PHP não terem sido testadas o bastante para ambientes de produção. O time agora consiste em um grupo de desenvolvedores com um bom entendimento sobre o código base do PHP. Estes desenvolvedores gastam muito boa parte do tempo deles localizando e consertando bugs dentro do PHP. Além disso há muitos outros membros do time que são os que testam e fornecem o feedback destes consertos usando um larga variedade de plataformas.
O PHP-GTK é a solução PHP para aplicações GUI client side (lado-cliente). Andrei Zmievski recorda o processo de planejamento e criação do PHP-GTK:
A programação GUI sempre foi de meu interesse, e eu achei que o Gtk+ é uma ferramenta muito boa, exceto que a programação dela usa o C que algumas vezes é um tédio. Após testemunhar as implementações do PyGtk e GTK-Perl, eu decidi ver se o PHP poderia ter uma interface Gtk+. Começando em Agosto de 2000, eu comecei a ter um pouco mais de tempo livre que foi quando eu comecei a experimentar. Minha linha guia principal foi a implementação da interface PyGtk. James Henstridge, o autor do PyGtk, me ajudou muito durante os estágios iniciais.
Escrever as interfaces na mão para todas as funções do Gtk+ estava fora de questão, então eu tive uma idéia de criar um gerador de código, similar à como o PyGtk foi feito. O gerador de código é um programa PHP que lê uma série de arquivos .def contendo as classes Gtk+, constantes, e as informações dos métodos e geradores de código C que irão trabalhar com o PHP.O que não pode ser gerado automaticamente pode ser escrito em arquivos .overrides.
Trabalhando no gerador de código e na infraestrutura levou algum tempo, porque eu tinha pouco tempo para trabalhar no PHP-GTK durante o fim de 2000. Depois de eu mostrar o PHP-GTK ao Frank Kromann, ele se interessou e começou a me ajudar com o gerador de código e a implementação para Win32. Quando nós escrevemos o primeiro programa 'Hello World' e o rodamos, foi extremamente exitante. Levou mais alguns meses para deixar o projeto em uma condição apresentável e lançar a versão inicial realizada em 1 de Março de 2001. que logo foi apresentada no SlashDot.
Detetando que o PHP-GTK pode ser extensivo, eu decidi separar as listas de discussão e os repositórios CVS para isto, bem como o website gtk.php.net com ajuda de Colin Viebrock. A documentação também era necessária ser feita e James Moore veio me ajudar com isto.
Desde sua realização o PHP-GTK vem ganhando popularidade. Agora, nós temos nosso próprio time de documentação, o manual continua melhorando, as pessoas começam a escrever extensões para o PHP-GTK, e mais e mais aplicativos excitantes com ele.
O PHP cresceu, ele começou a ser reconhecido mundialmente como a plataforma mais popular. Uma das maneiras mais interessantes de ver esta tendência é observar os livros sobre PHP que surgirão ao longo dos anos.
Até onde nós sabemos, o primeiro livro dedicado ao PHP foi 'PHP- tvorba interaktivních internetových aplikací' - um livro Czech publicado em Abril de 1999, pela autora Jirka Kosek. No mês seguinte veio o livro Alemão escrito por Egon Schmid, Christian Cartus e Richard Blume. O primeiro livro em Inglês sobre PHP foi publicado logo depois, e foi chamado 'Core PHP Programming' por Leon Atkinson. Todos estes livros falavam sobre o PHP 3.0.
Quando estes livros eram os primeiros deste tipo - eles inspiraram um grande número de livros de outros autores e editoras. Há aproximadamente 40 livros em Inglês, 50 livros em Alemão, e uns 20 livros em Francês! Além disso, você pdoe encontrar livros sobre PHP em muitas outras línguas, incluindo Espanhol, Koreâno, Japonês e Hebrew.
Obviamente, este grande número de livros, escritos por diferentes autores, publicados por muitas editoras, e disponíveis em muitas línguas - é uma prova do sucesso mundial do PHP.
Até onde nós sabemos, o primeiro artigo sobre PHP foi publicado em uma revista parecida com a Computerworld na Czech em meados de 1998, e cobria o PHP 3.0. Como os livros, este foi um de uma sério de muitos artigos publicados sobre PHP em várias revistas proeminentes.
Artigos sobre PHP apareceram no Dr. Dobbs, Empresas de Linux, Revistas de Linux e em muitos outros lugares. Artigos sobre migração de aplicações baseadas em ASP para PHP rodando Windows foram publicadas mesmo na Microsoft e até mesmo na MSDN!
PHP 4 and the integrated Zend engine have greatly improved PHP's performance and capabilities, but great care has been taken to break as little existing code as possible. So migrating your code from PHP 3 to 4 should be much easier than migrating from PHP/FI 2 to PHP 3. A lot of existing PHP 3 code should be ready to run without changes, but you should still know about the few differences and take care to test your code before switching versions in production environments. The following should give you some hints about what to look for.
Recent operating systems provide the ability to perform versioning and scoping. This features make it possible to let PHP 3 and PHP 4 run as concurrent modules in one Apache server.
This feature is known to work on the following platforms:
Linux with recent binutils (binutils 2.9.1.0.25 tested)
Solaris 2.5 or better
FreeBSD (3.2, 4.0 tested)
To enable it, configure PHP3 and PHP4 to use APXS (--with-apxs) and the necessary link extensions (--enable-versioning). Otherwise, all standard installations instructions apply. For example:
The global configuration file, php3.ini, has changed its name to php.ini.
For the Apache configuration file, there are slightly more changes. The MIME types recognized by the PHP module have changed.
application/x-httpd-php3 --> application/x-httpd-php application/x-httpd-php3-source --> application/x-httpd-php-source |
You can make your configuration files work with both versions of PHP (depending on which one is currently compiled into the server), using the following syntax:
AddType application/x-httpd-php3 .php3 AddType application/x-httpd-php3-source .php3s AddType application/x-httpd-php .php AddType application/x-httpd-php-source .phps |
In addition, the PHP directive names for Apache have changed.
Starting with PHP 4.0, there are only four Apache directives that relate to PHP:
php_value [PHP directive name] [value] php_flag [PHP directive name] [On|Off] php_admin_value [PHP directive name] [value] php_admin_flag [PHP directive name] [On|Off] |
There are two differences between the Admin values and the non admin values:
Admin values (or flags) can only appear in the server-wide apache configuration files (e.g., httpd.conf).
Standard values (or flags) cannot control certain PHP directives, for example - safe mode (if you could override safe mode settings in .htaccess files, it would defeat safe-mode's purpose). In contrast, Admin values can modify the value of any PHP directive.
To make the transition process easier, PHP 4 is bundled with scripts that automatically convert your Apache configuration and .htaccess files to work with both PHP 3 and PHP 4. These scripts do NOT convert the mime type lines! You have to convert these yourself.
To convert your Apache configuration files, run the apconf-conv.sh script (available in the scripts/apache/ directory). For example:
Your original configuration file will be saved in httpd.conf.orig.
To convert your .htaccess files, run the aphtaccess-conv.sh script (available in the scripts/apache/ directory as well):
Likewise, your old .htaccess files will be saved with an .orig prefix.
The conversion scripts require awk to be installed.
Parsing and execution are now two completely separated steps, no execution of a files code will happen until the complete file and everything it requires has completely and successfully been parsed.
One of the new requirements introduced with this split is that required and included files now have to be syntactically complete. You can no longer spread the different controlling parts of a control structure across file boundaries. That is you cannot start a for or while loop, an if statement or a switch block in one file and have the end of loop, else, endif, case or break statements in a different file.
It still perfectly legal to include additional code within loops or other control structures, only the controlling keywords and corresponding curly braces {...} have to be within the same compile unit (file or eval()ed string).
This should not harm to much as spreading code like this should be considered as very bad style anyway.
Another thing no longer possible, though rarely seen in PHP 3 code is returning values from a required file. Returning a value from an included file is still possible.
With PHP 3 the error reporting level was set as a simple numeric value formed by summing up the numbers related to different error levels. Usual values where 15 for reporting all errors and warnings or 7 for reporting everything but simple notice messages reporting bad style and things like that.
PHP 4 has a larger set of error and warning levels and comes with a configuration parser that now allows for symbolic constants to be used for setting the intended behavior.
Error reporting level should now be configured by explicitly taking away the warning levels you do not want to generate error messages by x-oring them from the symbolic constant E_ALL. Sounds complicated? Well, lets say you want the error reporting system to report all but the simple style warnings that are categorized by the symbolic constant E_NOTICE. Then you'll put the following into your php.ini: error_reporting = E_ALL & ~ ( E_NOTICE ). If you want to suppress warnings too you add up the appropriate constant within the braces using the binary or operator '|': error_reporting= E_ALL & ~ ( E_NOTICE | E_WARNING ).
Atenção |
When upgrading code or servers from PHP 3 to PHP 4 you should check these settings and calls to error_reporting() or you might disable reporting the new error types, especially E_COMPILE_ERROR. This may lead to empty documents without any feedback of what happened or where to look for the problem. |
Atenção |
Using the old values 7 and 15 for setting up error reporting is a very bad idea as this suppresses some of the newly added error classes including parse errors. This may lead to very strange behavior as scripts might no longer work without error messages showing up anywhere. This has lead to a lot of unreproducible bug reports in the past where people reported script engine problems they were not capable to track down while the TRUE case was usually some missing '}' in a required file that the parser was not able to report due to a misconfigured error reporting system. So checking your error reporting setup should be the first thing to do whenever your scripts silently die. The Zend engine can be considered mature enough nowadays to not cause this kind of strange behavior. |
A lot of existing PHP 3 code uses language constructs that should be considered as very bad style as this code, while doing the intended thing now, could easily be broken by changes in other places. PHP 4 will output a lot of notice messages in such situations where PHP 3 didn't. The easy fix is to just turn off E_NOTICE messages, but it is usually a good idea to fix the code instead.
The most common case that will now produce notice messages is the use of unquoted string constants as array indices. Both PHP 3 and 4 will fall back to interpret these as strings if no keyword or constant is known by that name, but whenever a constant by that name had been defined anywhere else in the code it might break your script. This can even become a security risk if some intruder manages to redefine string constants in a way that makes your script give him access rights he wasn't intended to have. So PHP 4 will now warn you whenever you use unquoted string constants as for example in $_SERVER[REQUEST_METHOD]. Changing it to $_SERVER['REQUEST_METHOD'] will make the parser happy and greatly improve the style and security of your code.
Another thing PHP 4 will now tell you about is the use of uninitialized variables or array elements.
Static variable and class member initializers only accept scalar values while in PHP 3 they accepted any valid expression. This is, once again, due to the split between parsing and execution as no code has yet been executed when the parser sees the initializer.
For classes you should use constructors to initialize member variables instead. For static variables anything but a simple static value rarely makes sense anyway.
The perhaps most controversial change in behavior has happened to the behavior of the empty(). A String containing only the character '0' (zero) is now considered empty while it wasn't in PHP 3.
This new behavior makes sense in web applications, with all input fields returning strings even if numeric input is requested, and with PHP's capabilities of automatic type conversion. But on the other hand it might break your code in a rather subtle way, leading to misbehavior that is hard to track down if you do not know about what to look for.
While PHP 4 comes with a lot of new features, functions and extensions, you may still find some functions from version 3 missing. A small number of core functions has vanished because they do not work with the new scheme of splitting parsing and execution as introduced into 4 with the Zend engine. Other functions and even complete extensions have become obsolete as newer functions and extensions serve the same task better and/or in a more general way. Some functions just simply haven't been ported yet and finally some functions or extensions may be missing due to license conflicts.
As PHP 4 now separates parsing from execution it is no longer possible to change the behavior of the parser (now embedded in the Zend engine) at runtime as parsing already happened by then. So the function short_tags() no longer exists. You can still change the parsers behavior by setting appropriate values in the php.ini file.
Another feature of PHP 3 that is not a part of PHP 4 is the bundled debugging interface. There are third-party add-ons for the Zend engine which add similar functionality.
The Adabas and Solid database extensions are no more. Long live the unified ODBC extension instead.
unset(), although still available, is implemented as a language construct rather than a function.
This does not have any consequences on the behavior of unset(), but testing for "unset" using function_exists() will return FALSE as it would with other language constructs that look like functions such as echo().
Another more practical change is that it is no longer possible to call unset() indirectly, that is $func="unset"; $func($somevar) won't work anymore.
Extensions written for PHP 3 will not work with PHP 4, neither as binaries nor at the source level. It is not difficult to port extensions to PHP 4 if you have access to the original source. A detailed description of the actual porting process is not part of this text.
PHP 4 adds a new mechanism to variable substitution in strings. You can now finally access object member variables and elements from multidimensional arrays within strings.
To do so you have to enclose your variables with curly braces with the dollar sign immediately following the opening brace: {$...}
To embed the value of an object member variable into a string you simply write "text {$obj->member} text" while in PHP 3 you had to use something like "text ".$obj->member." text".
This should lead to more readable code, while it may break existing scripts written for PHP 3. But you can easily check for this kind of problem by checking for the character combination {$ in your code and by replacing it with \{$ with your favorite search-and-replace tool.
PHP 3 had the bad habit of setting cookies in the reverse order of the setcookie() calls in your code. PHP 4 breaks with this habit and creates the cookie header lines in exactly the same order as you set the cookies in the code.
This might break some existing code, but the old behaviour was so strange to understand that it deserved a change to prevent further problems in the future.
While handling of global variables had the focus on to be easy in PHP 3 and early versions of PHP 4, the focus has changed to be more secure. While in PHP 3 the following example worked fine, in PHP 4 it has to be unset($GLOBALS["id"]);. This is only one issue of global variable handling. You should always have used $GLOBALS, with newer versions of PHP 4 you are forced to do so in most cases. Read more on this subject in the global references section.
PHP 3.0 is rewritten from the ground up. It has a proper parser that is much more robust and consistent than 2.0's. 3.0 is also significantly faster, and uses less memory. However, some of these improvements have not been possible without compatibility changes, both in syntax and functionality.
In addition, PHP's developers have tried to clean up both PHP's syntax and semantics in version 3.0, and this has also caused some incompatibilities. In the long run, we believe that these changes are for the better.
This chapter will try to guide you through the incompatibilities you might run into when going from PHP/FI 2.0 to PHP 3.0 and help you resolve them. New features are not mentioned here unless necessary.
A conversion program that can automatically convert your old PHP/FI 2.0 scripts exists. It can be found in the convertor subdirectory of the PHP 3.0 distribution. This program only catches the syntax changes though, so you should read this chapter carefully anyway.
The first thing you probably will notice is that PHP's start and end tags have changed. The old <? > form has been replaced by three new possible forms:
The `alternative' way to write if/elseif/else statements, using if(); elseif(); else; endif; cannot be efficiently implemented without adding a large amount of complexity to the 3.0 parser. Because of this, the syntax has been changed:
Just like with if..endif, the syntax of while..endwhile has changed as well:
Atenção |
If you use the old while..endwhile syntax in PHP 3.0, you will get a never-ending loop. |
PHP/FI 2.0 used the left side of expressions to determine what type the result should be. PHP 3.0 takes both sides into account when determining result types, and this may cause 2.0 scripts to behave unexpectedly in 3.0.
Consider this example:
In PHP/FI 2.0, this would display both of $a's indices. In PHP 3.0, it wouldn't display anything. The reason is that in PHP 2.0, because the left argument's type was string, a string comparison was made, and indeed "" does not equal "0", and the loop went through. In PHP 3.0, when a string is compared with an integer, an integer comparison is made (the string is converted to an integer). This results in comparing atoi("") which is 0, and variablelist which is also 0, and since 0==0, the loop doesn't go through even once.The fix for this is simple. Replace the while statement with:
PHP 3.0's error messages are usually more accurate than 2.0's were, but you no longer get to see the code fragment causing the error. You will be supplied with a file name and a line number for the error, though.
In PHP 3.0 boolean evaluation is short-circuited. This means that in an expression like (1 || test_me()), the function test_me() would not be executed since nothing can change the result of the expression after the 1.
This is a minor compatibility issue, but may cause unexpected side-effects.
Most internal functions have been rewritten so they return TRUE when successful and FALSE when failing, as opposed to 0 and -1 in PHP/FI 2.0, respectively. The new behaviour allows for more logical code, like $fp = fopen("/your/file") or fail("darn!");. Because PHP/FI 2.0 had no clear rules for what functions should return when they failed, most such scripts will probably have to be checked manually after using the 2.0 to 3.0 convertor.
The PHP 3.0 Apache module no longer supports Apache versions prior to 1.2. Apache 1.2 or later is required.
echo() no longer supports a format string. Use the printf() function instead.
In PHP/FI 2.0, an implementation side-effect caused $foo[0] to have the same effect as $foo. This is not true for PHP 3.0.
Reading arrays with $array[] is no longer supported
That is, you cannot traverse an array by having a loop that does $data = $array[]. Use current() and next() instead.
Also, $array1[] = $array2 does not append the values of $array2 to $array1, but appends $array2 as the last entry of $array1. See also multidimensional array support.
"+" is no longer overloaded as a concatenation operator for strings, instead it converts it's arguments to numbers and performs numeric addition. Use "." instead.
O PHP 3 tem suporte ao debug baseado em rede.
O PHP 4 não possui um utilitário de debug interno. Mas você pode utilizar debugadores externos alternativamente. O Zend IDE inclui um debugador e há também outras extensões grátis como o DBG em http://dd.cron.ru/dbg/ ou o Advanced PHP Debugger (APD).
O debugador interno do PHP 3 é útil para rastrear bugs fugitivos. O debugador trabalha conectado em uma porta TCP cada vez que o PHP 3 inicia. Todas as mensagens de erro daquela requisição será enviada para esta conexão TCP. Estas informações são destinadas a "debugar o servidor" de dentro de um sistema IDE ou editor de arquivos programável (como o Emacs).
Como ativar o debugger:
Configure uma porta TCP para ele no arquivo de configuração (debugger.port) e habilite ele (debugger.enabled).
Configure um "ouvidor" TCP naquela porta em algum programa (por exemplo socket -l -s 1400 no UNIX).
Em seu código execute um "debugger_on(endereço)", onde endereço é o número IP ou nome do computador executando o "ouvidor" TCP.
O protocolo do debugador do PHP 3 é baseado em linhas. Cada linha tem um tipo, e várias linhas compõem uma mensagem. Cada mensagem começa com uma linha do tipo start e termina com uma linha do tipo end. O PHP 3 pode enviar linhas de diferentes mensagens simultaneamente.
Uma linha tem este formato:
Data no formato ISO 8601 (yyyy-mm-dd)
Hora, incluindo microsegundos: hh:mm:uuuuuu
Nome DNS ou IP da maquina onde o erro do script foi gerado.
ID do processo na máquina do processo com o PHP 3 que gerou este erro de script.
Tipo da linha. Informa o programa sobre como ele deve tratar os seguintes dados:
Tabela D-1. Tipos de Linhas de Debug
Nome | Significado |
---|---|
start | Informa ao programa que a mensagem começa aqui. O conteúdo de data será o tipo de erro da mensagem, como listado abaixo. |
message | A mensagem de erro do PHP 3. |
location | Arquivo e número da linha onde ocorreu o erro. A primeira linha location sempre conterá o nível superior. data conterá: arquivo:linha. Sempre existirá uma linha location após uma message e após cada function. |
frames | Número de janelas (frames) na saida atual. Se houver quatro níveis, será esperado informação sobre quatro níveis de funções chamadas. Se não for dada nenhuma linha de janela (frame) assume que o valor é 0 (o erro aconteceu no início). |
function | Nome da função onde o erro ocorreu. Será repetida para cada vez que a função for chamada dentro da pilha. |
end | Informa ao programa que a mensagem de debug termina aqui. |
Linha de dados.
Tabela D-2. Tipos de erros de debug
Debugador | Interno do PHP 3 |
---|---|
warning (alerta, atenção) | E_WARNING |
error (erro) | E_ERROR |
parse (interpretação) | E_PARSE |
notice (notificação) | E_NOTICE |
core-error (erro grave) | E_CORE_ERROR |
core-warning (aviso grave) | E_CORE_WARNING |
unknown (desconhecido) | (qualquer outro) |
Exemplo D-1. Exemplo de uma mensagem de Debug
|
All functions look like this:
void php3_foo(INTERNAL_FUNCTION_PARAMETERS) { } |
Arguments are always of type pval. This type contains a union which has the actual type of the argument. So, if your function takes two arguments, you would do something like the following at the top of your function:
When you change any of the passed parameters, whether they are sent by reference or by value, you can either start over with the parameter by calling pval_destructor on it, or if it's an ARRAY you want to add to, you can use functions similar to the ones in internal_functions.h which manipulate return_value as an ARRAY.
Also if you change a parameter to IS_STRING make sure you first assign the new estrdup()'ed string and the string length, and only later change the type to IS_STRING. If you change the string of a parameter which already IS_STRING or IS_ARRAY you should run pval_destructor on it first.
A function can take a variable number of arguments. If your function can take either 2 or 3 arguments, use the following:
The type of each argument is stored in the pval type field. This type can be any of the following:
Tabela E-1. PHP Internal Types
IS_STRING | String |
IS_DOUBLE | Double-precision floating point |
IS_LONG | Long integer |
IS_ARRAY | Array |
IS_EMPTY | None |
IS_USER_FUNCTION | ?? |
IS_INTERNAL_FUNCTION | ?? (if some of these cannot be passed to a function - delete) |
IS_CLASS | ?? |
IS_OBJECT | ?? |
If you get an argument of one type and would like to use it as another, or if you just want to force the argument to be of a certain type, you can use one of the following conversion functions:
convert_to_long(arg1); convert_to_double(arg1); convert_to_string(arg1); convert_to_boolean_long(arg1); /* If the string is "" or "0" it becomes 0, 1 otherwise */ convert_string_to_number(arg1); /* Converts string to either LONG or DOUBLE depending on string */ |
These function all do in-place conversion. They do not return anything.
The actual argument is stored in a union; the members are:
IS_STRING: arg1->value.str.val
IS_LONG: arg1->value.lval
IS_DOUBLE: arg1->value.dval
Any memory needed by a function should be allocated with either emalloc() or estrdup(). These are memory handling abstraction functions that look and smell like the normal malloc() and strdup() functions. Memory should be freed with efree().
There are two kinds of memory in this program: memory which is returned to the parser in a variable, and memory which you need for temporary storage in your internal function. When you assign a string to a variable which is returned to the parser you need to make sure you first allocate the memory with either emalloc() or estrdup(). This memory should NEVER be freed by you, unless you later in the same function overwrite your original assignment (this kind of programming practice is not good though).
For any temporary/permanent memory you need in your functions/library you should use the three emalloc(), estrdup(), and efree() functions. They behave EXACTLY like their counterpart functions. Anything you emalloc() or estrdup() you have to efree() at some point or another, unless it's supposed to stick around until the end of the program; otherwise, there will be a memory leak. The meaning of "the functions behave exactly like their counterparts" is: if you efree() something which was not emalloc()'ed nor estrdup()'ed you might get a segmentation fault. So please take care and free all of your wasted memory.
If you compile with "-DDEBUG", PHP will print out a list of all memory that was allocated using emalloc() and estrdup() but never freed with efree() when it is done running the specified script.
A number of macros are available which make it easier to set a variable in the symbol table:
SET_VAR_STRING(name,value)
SET_VAR_DOUBLE(name,value)
SET_VAR_LONG(name,value)
Atenção |
Be careful with SET_VAR_STRING. The value part must be malloc'ed manually because the memory management code will try to free this pointer later. Do not pass statically allocated memory into a SET_VAR_STRING. |
Symbol tables in PHP are implemented as hash tables. At any given time, &symbol_table is a pointer to the 'main' symbol table, and active_symbol_table points to the currently active symbol table (these may be identical like in startup, or different, if you're inside a function).
The following examples use 'active_symbol_table'. You should replace it with &symbol_table if you specifically want to work with the 'main' symbol table. Also, the same functions may be applied to arrays, as explained below.
If you want to define a new array in a symbol table, you should do the following.
First, you may want to check whether it exists and abort appropriately, using hash_exists() or hash_find().
Next, initialize the array:
Here's how to add new entries to it:
Exemplo E-6. Adding entries to a new array
|
hash_next_index_insert() uses more or less the same logic as "$foo[] = bar;" in PHP 2.0.
If you are building an array to return from a function, you can initialize the array just like above by doing:
if (array_init(return_value) == FAILURE) { failed...; } |
...and then adding values with the helper functions:
add_next_index_long(return_value,long_value); add_next_index_double(return_value,double_value); add_next_index_string(return_value,estrdup(string_value)); |
Of course, if the adding isn't done right after the array initialization, you'd probably have to look for the array first:
pval *arr; if (hash_find(active_symbol_table,"foo",sizeof("foo"),(void **)&arr)==FAILURE) { can't find... } else { use arr->value.ht... } |
Note that hash_find receives a pointer to a pval pointer, and not a pval pointer.
Just about any hash function returns SUCCESS or FAILURE (except for hash_exists(), which returns a boolean truth value).
A number of macros are available to make returning values from a function easier.
The RETURN_* macros all set the return value and return from the function:
RETURN
RETURN_FALSE
RETURN_TRUE
RETURN_LONG(l)
RETURN_STRING(s,dup) If dup is TRUE, duplicates the string
RETURN_STRINGL(s,l,dup) Return string (s) specifying length (l).
RETURN_DOUBLE(d)
The RETVAL_* macros set the return value, but do not return.
RETVAL_FALSE
RETVAL_TRUE
RETVAL_LONG(l)
RETVAL_STRING(s,dup) If dup is TRUE, duplicates the string
RETVAL_STRINGL(s,l,dup) Return string (s) specifying length (l).
RETVAL_DOUBLE(d)
The string macros above will all estrdup() the passed 's' argument, so you can safely free the argument after calling the macro, or alternatively use statically allocated memory.
If your function returns boolean success/error responses, always use RETURN_TRUE and RETURN_FALSE respectively.
Your function can also return a complex data type such as an object or an array.
Returning an object:
Call object_init(return_value).
Fill it up with values. The functions available for this purpose are listed below.
Possibly, register functions for this object. In order to obtain values from the object, the function would have to fetch "this" from the active_symbol_table. Its type should be IS_OBJECT, and it's basically a regular hash table (i.e., you can use regular hash functions on .value.ht). The actual registration of the function can be done using:
add_method( return_value, function_name, function_ptr ); |
The functions used to populate an object are:
add_property_long( return_value, property_name, l ) - Add a property named 'property_name', of type long, equal to 'l'
add_property_double( return_value, property_name, d ) - Same, only adds a double
add_property_string( return_value, property_name, str ) - Same, only adds a string
add_property_stringl( return_value, property_name, str, l ) - Same, only adds a string of length 'l'
Returning an array:
Call array_init(return_value).
Fill it up with values. The functions available for this purpose are listed below.
The functions used to populate an array are:
add_assoc_long(return_value,key,l) - add associative entry with key 'key' and long value 'l'
add_assoc_double(return_value,key,d)
add_assoc_string(return_value,key,str,duplicate)
add_assoc_stringl(return_value,key,str,length,duplicate) specify the string length
add_index_long(return_value,index,l) - add entry in index 'index' with long value 'l'
add_index_double(return_value,index,d)
add_index_string(return_value,index,str)
add_index_stringl(return_value,index,str,length) - specify the string length
add_next_index_long(return_value,l) - add an array entry in the next free offset with long value 'l'
add_next_index_double(return_value,d)
add_next_index_string(return_value,str)
add_next_index_stringl(return_value,str,length) - specify the string length
PHP has a standard way of dealing with various types of resources. This replaces all of the local linked lists in PHP 2.0.
Available functions:
php3_list_insert(ptr, type) - returns the 'id' of the newly inserted resource
php3_list_delete(id) - delete the resource with the specified id
php3_list_find(id,*type) - returns the pointer of the resource with the specified id, updates 'type' to the resource's type
Typical list code would look like this:
Exemplo E-8. Using an existing resource
|
PHP has a standard way of storing persistent resources (i.e., resources that are kept in between hits). The first module to use this feature was the MySQL module, and mSQL followed it, so one can get the general impression of how a persistent resource should be used by reading mysql.c. The functions you should look at are:
php3_mysql_do_connect |
php3_mysql_connect() |
php3_mysql_pconnect() |
The general idea of persistence modules is this:
Code all of your module to work with the regular resource list mentioned in section (9).
Code extra connect functions that check if the resource already exists in the persistent resource list. If it does, register it as in the regular resource list as a pointer to the persistent resource list (because of 1., the rest of the code should work immediately). If it doesn't, then create it, add it to the persistent resource list AND add a pointer to it from the regular resource list, so all of the code would work since it's in the regular resource list, but on the next connect, the resource would be found in the persistent resource list and be used without having to recreate it. You should register these resources with a different type (e.g. LE_MYSQL_LINK for non-persistent link and LE_MYSQL_PLINK for a persistent link).
If you read mysql.c, you'll notice that except for the more complex connect function, nothing in the rest of the module has to be changed.
The very same interface exists for the regular resource list and the persistent resource list, only 'list' is replaced with 'plist':
php3_plist_insert(ptr, type) - returns the 'id' of the newly inserted resource
php3_plist_delete(id) - delete the resource with the specified id
php3_plist_find(id,*type) - returns the pointer of the resource with the specified id, updates 'type' to the resource's type
However, it's more than likely that these functions would prove to be useless for you when trying to implement a persistent module. Typically, one would want to use the fact that the persistent resource list is really a hash table. For instance, in the MySQL/mSQL modules, when there's a pconnect() call (persistent connect), the function builds a string out of the host/user/passwd that were passed to the function, and hashes the SQL link with this string as a key. The next time someone calls a pconnect() with the same host/user/passwd, the same key would be generated, and the function would find the SQL link in the persistent list.
Until further documented, you should look at mysql.c or msql.c to see how one should use the plist's hash table abilities.
One important thing to note: resources going into the persistent resource list must *NOT* be allocated with PHP's memory manager, i.e., they should NOT be created with emalloc(), estrdup(), etc. Rather, one should use the regular malloc(), strdup(), etc. The reason for this is simple - at the end of the request (end of the hit), every memory chunk that was allocated using PHP's memory manager is deleted. Since the persistent list isn't supposed to be erased at the end of a request, one mustn't use PHP's memory manager for allocating resources that go to it.
When you register a resource that's going to be in the persistent list, you should add destructors to it both in the non-persistent list and in the persistent list. The destructor in the non-persistent list destructor shouldn't do anything. The one in the persistent list destructor should properly free any resources obtained by that type (e.g. memory, SQL links, etc). Just like with the non-persistent resources, you *MUST* add destructors for every resource, even it requires no destruction and the destructor would be empty. Remember, since emalloc() and friends aren't to be used in conjunction with the persistent list, you mustn't use efree() here either.
Many of the features of PHP can be configured at runtime. These configuration directives can appear in either the designated php3.ini file, or in the case of the Apache module version in the Apache .conf files. The advantage of having them in the Apache .conf files is that they can be configured on a per-directory basis. This means that one directory may have a certain safemodeexecdir for example, while another directory may have another. This configuration granularity is especially handy when a server supports multiple virtual hosts.
The steps required to add a new directive:
Add directive to php3_ini_structure struct in mod_php3.h.
In main.c, edit the php3_module_startup function and add the appropriate cfg_get_string() or cfg_get_long() call.
Add the directive, restrictions and a comment to the php3_commands structure in mod_php3.c. Note the restrictions part. RSRC_CONF are directives that can only be present in the actual Apache .conf files. Any OR_OPTIONS directives can be present anywhere, include normal .htaccess files.
In either php3take1handler() or php3flaghandler() add the appropriate entry for your directive.
In the configuration section of the _php3_info() function in functions/info.c you need to add your new directive.
And last, you of course have to use your new directive somewhere. It will be addressable as php3_ini.directive.
To call user functions from an internal function, you should use the call_user_function() function.
call_user_function() returns SUCCESS on success, and FAILURE in case the function cannot be found. You should check that return value! If it returns SUCCESS, you are responsible for destroying the retval pval yourself (or return it as the return value of your function). If it returns FAILURE, the value of retval is undefined, and you mustn't touch it.
All internal functions that call user functions must be reentrant. Among other things, this means they must not use globals or static variables.
call_user_function() takes six arguments:
This is a pointer to an object on which the function is invoked. This should be NULL if a global function is called. If it's not NULL (i.e. it points to an object), the function_table argument is ignored, and instead taken from the object's hash. The object *may* be modified by the function that is invoked on it (that function will have access to it via $this). If for some reason you don't want that to happen, send a copy of the object instead.
The name of the function to call. Must be a pval of type IS_STRING with function_name.str.val and function_name.str.len set to the appropriate values. The function_name is modified by call_user_function() - it's converted to lowercase. If you need to preserve the case, send a copy of the function name instead.
A pointer to a pval structure, into which the return value of the invoked function is saved. The structure must be previously allocated - call_user_function() does NOT allocate it by itself.
An array of pointers to values that will be passed as arguments to the function, the first argument being in offset 0, the second in offset 1, etc. The array is an array of pointers to pval's; The pointers are sent as-is to the function, which means if the function modifies its arguments, the original values are changed (passing by reference). If you don't want that behavior, pass a copy instead.
To report errors from an internal function, you should call the php3_error() function. This takes at least two parameters -- the first is the level of the error, the second is the format string for the error message (as in a standard printf() call), and any following arguments are the parameters for the format string. The error levels are:
Notices are not printed by default, and indicate that the script encountered something that could indicate an error, but could also happen in the normal course of running a script. For example, trying to access the value of a variable which has not been set, or calling stat() on a file that doesn't exist.
Warnings are printed by default, but do not interrupt script execution. These indicate a problem that should have been trapped by the script before the call was made. For example, calling ereg() with an invalid regular expression.
Errors are also printed by default, and execution of the script is halted after the function returns. These indicate errors that can not be recovered from, such as a memory allocation problem.
Parse errors should only be generated by the parser. The code is listed here only for the sake of completeness.
This is like an E_ERROR, except it is generated by the core of PHP. Functions should not generate this type of error.
This is like an E_WARNING, except it is generated by the core of PHP. Functions should not generate this type of error.
This is like an E_ERROR, except it is generated by the Zend Scripting Engine. Functions should not generate this type of error.
This is like an E_WARNING, except it is generated by the Zend Scripting Engine. Functions should not generate this type of error.
This is like an E_ERROR, except it is generated in PHP code by using the PHP function trigger_error(). Functions should not generate this type of error.
This is like an E_WARNING, except it is generated by using the PHP function trigger_error(). Functions should not generate this type of error.
This is like an E_NOTICE, except it is generated by using the PHP function trigger_error(). Functions should not generate this type of error.
Esta é a lista de funções sinônimas. Todas as funções sinônimas estão listadas aqui. Normalmente é uma má idéia utiliza-lás, pois elas estão em vias de ficarem obsoletas ou serem renomeadas, o que criaria um script não portável. Esta lista é fornecida para ajudar aqueles que querem atualizar os seus scripts antigos para a nova sintaxe.
De qualquer forma, alguma funções simplesmente tem dois nomes e não tem real preferência. (Por exemplo, is_int() e is_integer() são igualmente boas)
Esta lista é consistente com o PHP versão 4.0.6.
Tabela F-1. Sinônimos
Função sinônimo (alias) | Função mestre | Extensão usada |
---|---|---|
_ | gettext() | Gettext |
add | swfmovie_add() | Ming (flash) |
add | swfsprite_add() | Ming (flash) |
add_root | domxml_add_root() | DOM XML |
addaction | swfbutton_addAction() | Ming (flash) |
addcolor | swfdisplayitem_addColor() | Ming (flash) |
addentry | swfgradient_addEntry() | Ming (flash) |
addfill | swfshape_addfill() | Ming (flash) |
addshape | swfbutton_addShape() | Ming (flash) |
addstring | swftext_addString() | Ming (flash) |
addstring | swftextfield_addString() | Ming (flash) |
align | swftextfield_align() | Ming (flash) |
attributes | domxml_attributes() | DOM XML |
children | domxml_children() | DOM XML |
chop | rtrim() | Base syntax |
close | closedir() | Base syntax |
com_get | com_propget() | COM |
com_propset | com_propput() | COM |
com_set | com_propput() | COM |
cv_add | ccvs_add() | CCVS |
cv_auth | ccvs_auth() | CCVS |
cv_command | ccvs_command() | CCVS |
cv_count | ccvs_count() | CCVS |
cv_delete | ccvs_delete() | CCVS |
cv_done | ccvs_done() | CCVS |
cv_init | ccvs_init() | CCVS |
cv_lookup | ccvs_lookup() | CCVS |
cv_new | ccvs_new() | CCVS |
cv_report | ccvs_report() | CCVS |
cv_return | ccvs_return() | CCVS |
cv_reverse | ccvs_reverse() | CCVS |
cv_sale | ccvs_sale() | CCVS |
cv_status | ccvs_status() | CCVS |
cv_textvalue | ccvs_textvalue() | CCVS |
cv_void | ccvs_void() | CCVS |
die | exit() | Miscellaneous functions |
dir | getdir() | Base syntax |
diskfreespace | disk_free_space() | Filesystem |
domxml_getattr | domxml_get_attribute() | DOM XML |
domxml_setattr | domxml_set_attribute() | DOM XML |
doubleval | floatval() | Base syntax |
drawarc | swfshape_drawarc() | Ming (flash) |
drawcircle | swfshape_drawcircle() | Ming (flash) |
drawcubic | swfshape_drawcubic() | Ming (flash) |
drawcubicto | swfshape_drawcubicto() | Ming (flash) |
drawcurve | swfshape_drawcurve() | Ming (flash) |
drawcurveto | swfshape_drawcurveto() | Ming (flash) |
drawglyph | swfshape_drawglyph() | Ming (flash) |
drawline | swfshape_drawline() | Ming (flash) |
drawlineto | swfshape_drawlineto() | Ming (flash) |
dtd | domxml_intdtd() | DOM XML |
dumpmem | domxml_dumpmem() | DOM XML |
fbsql | fbsql_db_query() | FrontBase |
fputs | fwrite() | Base syntax |
get_attribute | domxml_get_attribute() | DOM XML |
getascent | swffont_getAscent() | Ming (flash) |
getascent | swftext_getAscent() | Ming (flash) |
getattr | domxml_get_attribute() | DOM XML |
getdescent | swffont_getDescent() | Ming (flash) |
getdescent | swftext_getDescent() | Ming (flash) |
getheight | swfbitmap_getHeight() | Ming (flash) |
getleading | swffont_getLeading() | Ming (flash) |
getleading | swftext_getLeading() | Ming (flash) |
getshape1 | swfmorph_getShape1() | Ming (flash) |
getshape2 | swfmorph_getShape2() | Ming (flash) |
getwidth | swfbitmap_getWidth() | Ming (flash) |
getwidth | swffont_getWidth() | Ming (flash) |
getwidth | swftext_getWidth() | Ming (flash) |
gzputs | gzwrite() | Zlib |
i18n_convert | mb_convert_encoding() | Multi-bytes Strings |
i18n_discover_encoding | mb_detect_encoding() | Multi-bytes Strings |
i18n_http_input | mb_http_input() | Multi-bytes Strings |
i18n_http_output | mb_http_output() | Multi-bytes Strings |
i18n_internal_encoding | mb_internal_encoding() | Multi-bytes Strings |
i18n_ja_jp_hantozen | mb_convert_kana() | Multi-bytes Strings |
i18n_mime_header_decode | mb_decode_mimeheader() | Multi-bytes Strings |
i18n_mime_header_encode | mb_encode_mimeheader() | Multi-bytes Strings |
imap_create | imap_createmailbox() | IMAP |
imap_fetchtext | imap_body() | IMAP |
imap_getmailboxes | imap_list_full() | IMAP |
imap_getsubscribed | imap_lsub_full() | IMAP |
imap_header | imap_headerinfo() | IMAP |
imap_listmailbox | imap_list() | IMAP |
imap_listsubscribed | imap_lsub() | IMAP |
imap_rename | imap_renamemailbox() | IMAP |
imap_scan | imap_listscan() | IMAP |
imap_scanmailbox | imap_listscan() | IMAP |
ini_alter | ini_set() | Base syntax |
is_double | is_float() | Base syntax |
is_integer | is_int() | Base syntax |
is_long | is_int() | Base syntax |
is_real | is_float() | Base syntax |
is_writeable | is_writable() | Base syntax |
join | implode() | Base syntax |
labelframe | swfmovie_labelFrame() | Ming (flash) |
labelframe | swfsprite_labelFrame() | Ming (flash) |
last_child | domxml_last_child() | DOM XML |
lastchild | domxml_last_child() | DOM XML |
ldap_close | ldap_unbind() | LDAP |
magic_quotes_runtime | set_magic_quotes_runtime() | Base syntax |
mbstrcut | mb_strcut() | Multi-bytes Strings |
mbstrlen | mb_strlen() | Multi-bytes Strings |
mbstrpos | mb_strpos() | Multi-bytes Strings |
mbstrrpos | mb_strrpos() | Multi-bytes Strings |
mbsubstr | mb_substr() | Multi-bytes Strings |
ming_setcubicthreshold | ming_setCubicThreshold() | Ming (flash) |
ming_setscale | ming_setScale() | Ming (flash) |
move | swfdisplayitem_move() | Ming (flash) |
movepen | swfshape_movepen() | Ming (flash) |
movepento | swfshape_movepento() | Ming (flash) |
moveto | swfdisplayitem_moveTo() | Ming (flash) |
moveto | swffill_moveTo() | Ming (flash) |
moveto | swftext_moveTo() | Ming (flash) |
msql | msql_db_query() | mSQL |
msql_createdb | msql_create_db() | mSQL |
msql_dbname | msql_result() | mSQL |
msql_dropdb | msql_drop_db() | mSQL |
msql_fieldflags | msql_field_flags() | mSQL |
msql_fieldlen | msql_field_len() | mSQL |
msql_fieldname | msql_field_name() | mSQL |
msql_fieldtable | msql_field_table() | mSQL |
msql_fieldtype | msql_field_type() | mSQL |
msql_freeresult | msql_free_result() | mSQL |
msql_listdbs | msql_list_dbs() | mSQL |
msql_listfields | msql_list_fields() | mSQL |
msql_listtables | msql_list_tables() | mSQL |
msql_numfields | msql_num_fields() | mSQL |
msql_numrows | msql_num_rows() | mSQL |
msql_regcase | sql_regcase() | mSQL |
msql_selectdb | msql_select_db() | mSQL |
msql_tablename | msql_result() | mSQL |
mssql_affected_rows | sybase_affected_rows() | Sybase |
mssql_affected_rows | sybase_affected_rows() | Sybase |
mssql_close | sybase_close() | Sybase |
mssql_close | sybase_close() | Sybase |
mssql_connect | sybase_connect() | Sybase |
mssql_connect | sybase_connect() | Sybase |
mssql_data_seek | sybase_data_seek() | Sybase |
mssql_data_seek | sybase_data_seek() | Sybase |
mssql_fetch_array | sybase_fetch_array() | Sybase |
mssql_fetch_array | sybase_fetch_array() | Sybase |
mssql_fetch_field | sybase_fetch_field() | Sybase |
mssql_fetch_field | sybase_fetch_field() | Sybase |
mssql_fetch_object | sybase_fetch_object() | Sybase |
mssql_fetch_object | sybase_fetch_object() | Sybase |
mssql_fetch_row | sybase_fetch_row() | Sybase |
mssql_fetch_row | sybase_fetch_row() | Sybase |
mssql_field_seek | sybase_field_seek() | Sybase |
mssql_field_seek | sybase_field_seek() | Sybase |
mssql_free_result | sybase_free_result() | Sybase |
mssql_free_result | sybase_free_result() | Sybase |
mssql_get_last_message | sybase_get_last_message() | Sybase |
mssql_get_last_message | sybase_get_last_message() | Sybase |
mssql_min_client_severity | sybase_min_client_severity() | Sybase |
mssql_min_error_severity | sybase_min_error_severity() | Sybase |
mssql_min_message_severity | sybase_min_message_severity() | Sybase |
mssql_min_server_severity | sybase_min_server_severity() | Sybase |
mssql_num_fields | sybase_num_fields() | Sybase |
mssql_num_fields | sybase_num_fields() | Sybase |
mssql_num_rows | sybase_num_rows() | Sybase |
mssql_num_rows | sybase_num_rows() | Sybase |
mssql_pconnect | sybase_pconnect() | Sybase |
mssql_pconnect | sybase_pconnect() | Sybase |
mssql_query | sybase_query() | Sybase |
mssql_query | sybase_query() | Sybase |
mssql_result | sybase_result() | Sybase |
mssql_result | sybase_result() | Sybase |
mssql_select_db | sybase_select_db() | Sybase |
mssql_select_db | sybase_select_db() | Sybase |
multcolor | swfdisplayitem_multColor() | Ming (flash) |
mysql | mysql_db_query() | MySQL |
mysql_createdb | mysql_create_db() | MySQL |
mysql_db_name | mysql_result() | MySQL |
mysql_dbname | mysql_result() | MySQL |
mysql_dropdb | mysql_drop_db() | MySQL |
mysql_fieldflags | mysql_field_flags() | MySQL |
mysql_fieldlen | mysql_field_len() | MySQL |
mysql_fieldname | mysql_field_name() | MySQL |
mysql_fieldtable | mysql_field_table() | MySQL |
mysql_fieldtype | mysql_field_type() | MySQL |
mysql_freeresult | mysql_free_result() | MySQL |
mysql_listdbs | mysql_list_dbs() | MySQL |
mysql_listfields | mysql_list_fields() | MySQL |
mysql_listtables | mysql_list_tables() | MySQL |
mysql_numfields | mysql_num_fields() | MySQL |
mysql_numrows | mysql_num_rows() | MySQL |
mysql_selectdb | mysql_select_db() | MySQL |
mysql_tablename | mysql_result() | MySQL |
name | domxml_attrname() | DOM XML |
new_child | domxml_new_child() | DOM XML |
new_xmldoc | domxml_new_xmldoc() | DOM XML |
nextframe | swfmovie_nextFrame() | Ming (flash) |
nextframe | swfsprite_nextFrame() | Ming (flash) |
node | domxml_node() | DOM XML |
oci8append | ocicollappend() | OCI8 |
oci8assign | ocicollassign() | OCI8 |
oci8assignelem | ocicollassignelem() | OCI8 |
oci8close | ocicloselob() | OCI8 |
oci8free | ocifreecoll() | OCI8 |
oci8free | ocifreedesc() | OCI8 |
oci8getelem | ocicollgetelem() | OCI8 |
oci8load | ociloadlob() | OCI8 |
oci8max | ocicollmax() | OCI8 |
oci8ocifreecursor | ocifreestatement() | OCI8 |
oci8save | ocisavelob() | OCI8 |
oci8savefile | ocisavelobfile() | OCI8 |
oci8size | ocicollsize() | OCI8 |
oci8trim | ocicolltrim() | OCI8 |
oci8writetemporary | ociwritetemporarylob() | OCI8 |
oci8writetofile | ociwritelobtofile() | OCI8 |
odbc_do | odbc_exec() | OCI8 |
odbc_field_precision | odbc_field_len() | OCI8 |
output | swfmovie_output() | Ming (flash) |
parent | domxml_parent() | DOM XML |
pdf_add_outline | pdf_add_bookmark() | |
pg_clientencoding | pg_client_encoding() | PostgreSQL |
pg_setclientencoding | pg_set_client_encoding() | PostgreSQL |
pos | current() | Base syntax |
recode | recode_string() | Recode |
remove | swfmovie_remove() | Ming (flash) |
remove | swfsprite_remove() | Ming (flash) |
rewind | rewinddir() | Base syntax |
root | domxml_root() | DOM XML |
rotate | swfdisplayitem_rotate() | Ming (flash) |
rotateto | swfdisplayitem_rotateTo() | Ming (flash) |
rotateto | swffill_rotateTo() | Ming (flash) |
save | swfmovie_save() | Ming (flash) |
savetofile | swfmovie_saveToFile() | Ming (flash) |
scale | swfdisplayitem_scale() | Ming (flash) |
scaleto | swfdisplayitem_scaleTo() | Ming (flash) |
scaleto | swffill_scaleTo() | Ming (flash) |
set_attribute | domxml_set_attribute() | DOM XML |
set_content | domxml_set_content() | DOM XML |
setaction | swfbutton_setAction() | Ming (flash) |
setattr | domxml_set_attribute() | DOM XML |
setbackground | swfmovie_setBackground() | Ming (flash) |
setbounds | swftextfield_setBounds() | Ming (flash) |
setcolor | swftext_setColor() | Ming (flash) |
setcolor | swftextfield_setColor() | Ming (flash) |
setdepth | swfdisplayitem_setDepth() | Ming (flash) |
setdimension | swfmovie_setDimension() | Ming (flash) |
setdown | swfbutton_setDown() | Ming (flash) |
setfont | swftext_setFont() | Ming (flash) |
setfont | swftextfield_setFont() | Ming (flash) |
setframes | swfmovie_setFrames() | Ming (flash) |
setframes | swfsprite_setFrames() | Ming (flash) |
setheight | swftext_setHeight() | Ming (flash) |
setheight | swftextfield_setHeight() | Ming (flash) |
sethit | swfbutton_setHit() | Ming (flash) |
setindentation | swftextfield_setIndentation() | Ming (flash) |
setleftfill | swfshape_setleftfill() | Ming (flash) |
setleftmargin | swftextfield_setLeftMargin() | Ming (flash) |
setline | swfshape_setline() | Ming (flash) |
setlinespacing | swftextfield_setLineSpacing() | Ming (flash) |
setmargins | swftextfield_setMargins() | Ming (flash) |
setmatrix | swfdisplayitem_setMatrix() | Ming (flash) |
setname | swfdisplayitem_setName() | Ming (flash) |
setname | swftextfield_setName() | Ming (flash) |
setover | swfbutton_setOver() | Ming (flash) |
setrate | swfmovie_setRate() | Ming (flash) |
setratio | swfdisplayitem_setRatio() | Ming (flash) |
setrightfill | swfshape_setrightfill() | Ming (flash) |
setrightmargin | swftextfield_setRightMargin() | Ming (flash) |
setspacing | swftext_setSpacing() | Ming (flash) |
setup | swfbutton_setUp() | Ming (flash) |
show_source | highlight_file () | Base syntax |
sizeof | count() | Base syntax |
skewx | swfdisplayitem_skewX() | Ming (flash) |
skewxto | swfdisplayitem_skewXTo() | Ming (flash) |
skewxto | swffill_skewXTo() | Ming (flash) |
skewy | swfdisplayitem_skewY() | Ming (flash) |
skewyto | swfdisplayitem_skewYTo() | Ming (flash) |
skewyto | swffill_skewYTo() | Ming (flash) |
snmpwalkoid | snmprealwalk() | SNMP |
strchr | strstr() | Base syntax |
streammp3 | swfmovie_streamMp3() | Ming (flash) |
swfaction | swfaction_init() | Ming (flash) |
swfbitmap | swfbitmap_init() | Ming (flash) |
swfbutton | swfbutton_init() | Ming (flash) |
swffill | swffill_init() | Ming (flash) |
swffont | swffont_init() | Ming (flash) |
swfgradient | swfgradient_init() | Ming (flash) |
swfmorph | swfmorph_init() | Ming (flash) |
swfmovie | swfmovie_init() | Ming (flash) |
swfshape | swfshape_init() | Ming (flash) |
swfsprite | swfsprite_init() | Ming (flash) |
swftext | swftext_init() | Ming (flash) |
swftextfield | swftextfield_init() | Ming (flash) |
unlink | domxml_unlink_node() | DOM XML |
xptr_new_context | xpath_new_context() | DOM XML |
Esta é uma lista de identificadores predefinidos do PHP. Nenhum dos identificadores listados aqui pode ser utilizado como seus identificadores nos scripts. Esta lista inclui palavras-chave e variáveis predefinidas, constantes e nomes de classes. Esta lista ainda não está completa.
Estas palavras tem um significado especial no PHP. Algumas delas representam coisas que parecem funções, algumas parecem constantes mas na verdade não o são realmente: elas são construtores de linguagem. Você não pode usar nenhuma das seguintes palavras como constantes, nomes de classes ou de funções. Utilizar como nome de variáveis geralmente não causa erros, mas pode levar a confusão.
Tabela G-1. Palavras-chave do PHP
and | or | xor | __FILE__ | |
__LINE__ | array() | as | break | case |
cfunction | class | const | continue | declare |
default | die() | do | echo() | else |
elseif | empty() | enddeclare | endfor | endforeach |
endif | endswitch | endwhile | eval | exit() |
extends | for | foreach | function | global |
if | include() | include_once() | isset() | list() |
new | old_function | print() | require() | require_once() |
return() | static | switch | unset() | use |
var | while | __FUNCTION__ | __CLASS__ |
Nota: Introduzida na versão 4.1.0. Em versões anteriores, use $HTTP_SERVER_VARS.
$_SERVER é um array contendo informações como headers, caminhos e localizações do script. Os itens deste array são criados pelo servidor web. Não há garantias que todos os servidores web geram todas elas: alguns servidores talvez omitam algumas ou geram outras que não estão listadas aqui. Mesmo assim, um grande número dessas variáveis estão de acordo com a especificação CGI 1.1, então você pode esperar encontrá-las nesse array.
Esta é uma variável 'superglobal', ou automaticamente global. Isto significa que ela é disponível em todos os escopos (níveis) de um script. Você não precisa fazer um global $_SERVER; para pode acessá-la dentro de funções ou métodos, como era necessário com $HTTP_SERVER_VARS.
$HTTP_SERVER_VARS contém a mesmas informações, mas ela não é uma superglobal.(Note que $HTTP_SERVER_VARS e $_SERVER são variáveis diferentes como também o PHP as manipula diferentemente)
Se a diretiva register_globals está ativa, então essas variáveis tornam-se disponíveis no escopo global do script (por exemplo, separados dos arrays $_SERVER e $HTTP_SERVER_VARS. Para maiores informações, veja o capítulo de segurança entitulado Utilizando registradores globais. Estas variáveis globais individuais não são superglobais.
Você poderá ou não encontrar qualquer um dos seguintes elementos dentro de $_SERVER. Note que poucos (ou nenhum) deles estão disponíveis (ou não terão qualquer sentido) se você estiver rodando o PHP na linha de comando.
O nome do arquivo do script atualmente em uso, relativo ao document root. Por exemplo, $_SERVER['PHP_SELF'] em um script com o endereço http://example.com/test.php/foo.bar pode ser /test.php/foo.bar.
Se estiver rodando o PHP em linha de comando, esta variável não está disponível.
Array de argumentos passado para o script. Quando o script é executado na linha de comando, isto permite um acesso aos parâmetros de linha de comando no estilo do C. Quando chamado via método GET, ele conterá a query string.
Contém o número de parâmetros da linha de comando passados para o script (se executando da linha de comando).
O número de revisão da especificação CGI que o servidor está utilizando, por exemplo : 'CGI/1.1'.
O nome host do servidor onde o script atual é executado. Se o script está rodando em um host virtual, este será o valor definido para aquele host virtual.
A string de identificação do servidor, fornecida nos headers quando respondendo a requests.
Nome e número de revisão do protocolo de informação pelo qual a página foi requerida, por exemplo 'HTTP/1.0';
Contém o método de request utilizando para acessar a página. Geralmente 'GET', 'HEAD', 'POST' ou 'PUT'.
A query string (string de solicitação), se houver, pela qual a página foi acessada.
O diretório raiz sob onde o script atual é executado, como definido no arquivos de configuração do servidor.
O conteúdo do header Accept: da requisição atual, se houver.
O conteúdo do header Accept-Charset: da requisição atual, se houver. Exemplo: 'iso-8859-1,*,utf-8'.
O conteúdo do header Accept-Encoding: da requisição atual, se houver. Exemplo: 'gzip'.
O conteúdo do header Accept-Language: da requisição atual, se houver. Exemplo 'en'.
O conteúdo do header Connection: da requisição atual, se houver. Exemplo: 'Keep-Alive'.
O conteúdo do header Host: da requisição atual, se houver.
O endereço da página (se houver) através da qual o agente do usuário acessou a página atual. Essa diretiva é informada pelo agente do usuário. Nem todos os browsers geram esse header, e alguns ainda possuem a habilidade de modificar o conteúdo do HTTP_REFERER como recurso. Em poucas palavras, não é confiável.
O conteúdo do header User_Agent: da requisição atual, se houver. É uma string denotando o agente de usuário pelo qual a página é acessada. Um exemplo típico é: Mozilla/4.5 [en] (X11; U; Linux 2.2.9 i586). Além de outras coisas, você pode utilizar este valor com get_browser() para personalizar a geração de suas páginas para as capacidades do agente do usuário.
O endereço IP de onde o usuário está visualizado a página atual.
A porta TCP na máquina do usuário utilizada para comunicação com o servidor web.
O caminho absoluto o script atualmente em execução.
O valor fornecido pela diretiva SERVER_ADMIN (do Apache) no arquivo de configuração do servidor. Se o script está sendo executado em um host virtual, este será os valores definidos para aquele host virtual.
A porta na máquina servidora utilizada pelo servidor web para comunicação. Como default, este valor é '80'. Utilizando SSL, entretanto, mudará esse valor para a porta de comunicação segura HTTP.
String contendo a versão do servidor e nome do host virtual que é adicionado às páginas geradas no servidor, se ativo.
O caminho real do script relativo ao sistema de arquivos (não o document root), depois realizou todos os mapeamentos de caminhos (virtual-to-real).
Contém o caminho completo do script atual. Útil para páginas que precisam apontar para elas mesmas (dinamicamente).
O URI fornecido para acessar a página atual, por exemplo, '/index.html'.
Quando executando sob o Apache como módulo e fazendo autenticaçào HTTP, esta variável estará definida com o username fornecido pelo usuário.
Quando executando sob o Apache como módulo e fazendo autenticaçào HTTP, esta variável estará definida com a senha fornecida pelo usuário.
Quando executando sob o Apache como módulo e fazendo autenticaçào HTTP, esta variável estará definida com o tipo de autenticação utilizado.
Nota: Introduzida na versão 4.1.0. Em versões anteriores, utilize $HTTP_ENV_VARS.
Estas variáveis são importadas dentro no espaço global do PHP do ambiente sob qual o interpretador do PHP está rodando. Muitos são são criados no shell (terminal) sob o qual o PHP é executado e sistemas diferentes normalmente utilizam vários sabores de shells, e uma lista definitiva é impossível. Verifique a documentação de sua shell para a lista de variáveis ambiente definidas.
Outras variáveis ambiente incluem as variáveis CGI, informadas aqui independente do PHP estar rodando como um módulo do servidor ou como processador CGI.
Esta é uma variável 'superglobal', ou automaticamente global. Isto significa que ela é disponível em todos os escopos (níveis) de um script. Você não precisa fazer um global $_ENV; para pode acessá-la dentro de funções ou métodos, como era necessário com $HTTP_ENV_VARS.
$HTTP_ENV_VARS contém a mesma informação, mas não é uma superglobal. (Note que HTTP_ENV_VARS e $_ENV são variáveis diferentes como também o PHP as manipula diferentemente)
Se a diretiva register_globals está ativa, então essas variáveis tornam-se disponíveis no escopo global do script (por exemplo, separados dos arrays $_ENV e $HTTP_ENV_VARS. Para maiores informações, veja o capítulo de segurança entitulado Utilizando registradores globais. Estas variáveis globais individuais não são superglobais.
Nota: Introduzida na versão 4.1.0. Em versões anteriores, utilize $HTTP_COOKIE_VARS.
Contém um array associativo de variáveis passas para o script atual através de cookies HTTP.
Esta é uma variável 'superglobal', ou automaticamente global. Isto significa que ela é disponível em todos os escopos (níveis) de um script. Você não precisa fazer um global $_COOKIE; para pode acessá-la dentro de funções ou métodos, como era necessário com $HTTP_COOKIE_VARS.
$HTTP_COOKIE_VARS contém as mesmas informações, mas não é uma superglobal. (Note que HTTP_COOKIE_VARS e $_COOKIE são variáveis diferentes como também o PHP as manipula diferentemente)
Se a diretiva register_globals está ativa, então essas variáveis tornam-se disponíveis no escopo global do script (por exemplo, separados dos arrays $_COOKIE e $HTTP_COOKIE_VARS. Para maiores informações, veja o capítulo de segurança entitulado Utilizando registradores globais. Estas variáveis globais individuais não são superglobais.
Nota: Introduzida na versão 4.1.0. Em versões anteriores, use $HTTP_GET_VARS.
Contém um array associativo de variáveis passadas para o script atual através do método HTTP GET.
Esta é uma variável 'superglobal', ou automaticamente global. Isto significa que ela é disponível em todos os escopos (níveis) de um script. Você não precisa fazer um global $_GET; para pode acessá-la dentro de funções ou métodos, como era necessário com $HTTP_GET_VARS.
$HTTP_GET_VARS contém as mesmas informações, mas não é uma superglobal. (Note que HTTP_GET_VARS e $_GET são variáveis diferentes como também o PHP as manipula diferentemente)
Se a diretiva register_globals está ativa, então essas variáveis tornam-se disponíveis no escopo global do script (por exemplo, separados dos arrays $_GET e $HTTP_GET_VARS. Para maiores informações, veja o capítulo de segurança entitulado Utilizando registradores globais. Estas variáveis globais individuais não são superglobais.
Nota: Introduzida na versão 4.1.0. Em versões anteriores, use $HTTP_POST_VARS.
Contém um array associativo de variáveis passadas para o script atual através do método HTTP POST.
Esta é uma variável 'superglobal', ou automaticamente global. Isto siginifica que ela é disponível em todos os escopos (níveis) de um script. Você não precisa fazer um global $_POST; para pode acessá-la dentro de funções ou métodos, como era necessário com $HTTP_POST_VARS.
$HTTP_POST_VARS contém as mesmas informações, mas não é uma superglobal. (Note que HTTP_POST_VARS e $_POST são variáveis diferentes como também o PHP as manipula diferentemente)
Se a diretiva register_globals está ativa, então essas variáveis tornam-se disponíveis no escopo global do script (por exemplo, separados dos arrays $_POST e $HTTP_POST_VARS. Para maiores informações, veja o capítulo de segurança entitulado Utilizando registradores globais. Estas variáveis globais individuais não são superglobais.
Nota: Introduzida na versão 4.1.0. Em versões anteriores, use $HTTP_POST_FILES.
Contém um array associativo dos itens carregador no script atual através do método HTTP POST.
Esta é uma variável 'superglobal', ou automaticamente global. Isto significa que ela é disponível em todos os escopos (níveis) de um script. Você não precisa fazer um global $_FILES; para pode acessá-la dentro de funções ou métodos, como era necessário com $HTTP_FILES_VARS.
$HTTP_POST_FILES contém as mesmas informações, mas não é uma superglobal.
Se a diretiva register_globals está ativa, então essas variáveis tornam-se disponíveis no escopo global do script (por exemplo, separados dos arrays $_FILES e $HTTP_POST_FILES. Para maiores informações, veja o capítulo de segurança entitulado Utilizando registradores globais. Estas variáveis globais individuais não são superglobais.
Nota: Introduzida na versão 4.1.0. Não há array equivalente em versões anteriores.
Contém um array associativo com os conteúdos de $_GET, $_POST, $_COOKIE e $_FILES.
Esta é uma variável 'superglobal', ou automaticamente global. Isto significa que ela é disponível em todos os escopos (níveis) de um script. Você não precisa fazer um global $_REQUEST; para pode acessá-la dentro de funções ou métodos.
Se a diretiva register_globals está ativa, então essas variáveis tornam-se disponíveis no escopo global do script (por exemplo, separados dos arrays $_REQUEST. Para maiores informações, veja o capítulo de segurança entitulado Utilizando registradores globais. Estas variáveis globais individuais não são superglobais.
Nota: Introduzida na versão 4.1.0. Em versões anteriores, use $HTTP_SESSION_VARS.
Contém um array associativo das variáveis de sessão disponíveis para o script atual. Veja a documentação das funções de Sessões para maiores informações de como utilizá-las.
Esta é uma variável 'superglobal', ou automaticamente global. Isto siginifica que ela é disponível em todos os escopos (níveis) de um script. Você não precisa fazer um global $_SESSION; para pode acessá-la dentro de funções ou métodos, como era necessário com $HTTP_SESSION_VARS.
$HTTP_SESSION_VARS contém as mesmas informações, mas não é uma superglobal.
Se a diretiva register_globals está ativa, então essas variáveis tornam-se disponíveis no escopo global do script (por exemplo, separados dos arrays $_SESSION e $HTTP_SESSION_VARS Para maiores informações, veja o capítulo de segurança entitulado Utilizando registradores globais. Estas variáveis globais individuais não são superglobais.
Nota: $GLOBALS foi disponibilizada desde a versão 3.0.0.
Um array associativo contendo referências para todas as variáveis atualmente definidas no escopo global do script. Os nomes das variáveis são as chaves do array.
Esta é uma variável 'superglobal', ou automaticamente global. Isto significa que ela é disponível em todos os escopos (níveis) de um script. Você não precisa fazer um global $GLOBALS; para pode acessá-la dentro de funções ou métodos.
$php_errormsg é uma variável contendo o texto da última mensagem de erro gerada pelo PHP. Esta variável somente está disponível no escopo em que o erro ocorreu, e somente se a opção de configuração track_errors está ativa (seu default é off).
Estas classes são definidas dentro do conjunto padrão de funções incluídas na compilação do PHP.
A classe de onde a função dir() é instanciada.
Estas classes são definidas na extensão Ming, e somente estarão disponíveis quando esta extensão for compilada dento do PHP ou carregada em tempo de execução.
Estas classes são definidas na extensão Oracle 8, e somente estarão disponíveis quando esta extensão for compilada dento do PHP ou carregada em tempo de execução.
Estas classes são definidas na extensão qtdom e somente estarão disponíveis quando esta extensão for compilada dento do PHP ou carregada em tempo de execução.
These constants are defined by the PHP core. This includes PHP, the Zend engine, and SAPI modules.
These constants are defined in PHP by default.
The following is a list of functions which create, use or destroy PHP resources. The function is_resource() can be used to determine if a variable is a resource and get_resource_type() will return the type of resource it is.
Tabela H-1. Resource Types
Resource Type Name | Created By | Used By | Destroyed By | Definition |
---|---|---|---|---|
aspell | aspell_new() | aspell_check(), aspell_check_raw(), aspell_suggest() | None | Aspell dictionary |
bzip2 | bzopen() | bzerrno(), bzerror(), bzerrstr(), bzflush(), bzread(), bzwrite() | bzclose() | Bzip2 file |
COM | com_load() | com_invoke(), com_propget(), com_get(), com_propput(), com_set(), com_propput() | None | COM object reference |
VARIANT | ||||
cpdf | cpdf_open() | cpdf_page_init(), cpdf_finalize_page(), cpdf_finalize(), cpdf_output_buffer(), cpdf_save_to_file(), cpdf_set_current_page(), cpdf_begin_text(), cpdf_end_text(), cpdf_show(), cpdf_show_xy(), cpdf_text(), cpdf_set_font(), cpdf_set_leading(), cpdf_set_text_rendering(), cpdf_set_horiz_scaling(), cpdf_set_text_rise(), cpdf_set_text_matrix(), cpdf_set_text_pos(), cpdf_set_text_pos(), cpdf_set_word_spacing(), cpdf_continue_text(), cpdf_stringwidth(), cpdf_save(), cpdf_translate(), cpdf_restore(), cpdf_scale(), cpdf_rotate(), cpdf_setflat(), cpdf_setlinejoin(), cpdf_setlinecap(), cpdf_setmiterlimit(), cpdf_setlinewidth(), cpdf_setdash(), cpdf_moveto(), cpdf_rmoveto(), cpdf_curveto(), cpdf_lineto(), cpdf_rlineto(), cpdf_circle(), cpdf_arc(), cpdf_rect(), cpdf_closepath(), cpdf_stroke(), cpdf_closepath_fill_stroke(), cpdf_fill_stroke(), cpdf_clip(), cpdf_fill(), cpdf_setgray_fill(), cpdf_setgray_stroke(), cpdf_setgray(), cpdf_setrgbcolor_fill(), cpdf_setrgbcolor_stroke(), cpdf_setrgbcolor(), cpdf_add_outline(), cpdf_set_page_animation(), cpdf_import_jpeg(), cpdf_place_inline_image(), cpdf_add_annotation() | cpdf_close() | PDF document with CPDF lib |
cpdf outline | ||||
curl | curl_init() | curl_init(), curl_exec() | curl_close() | Curl session |
dbm | dbmopen() | dbmexists(), dbmfetch(), dbminsert(), dbmreplace(), dbmdelete(), dbmfirstkey(), dbmnextkey() | dbmclose() | Link to DBM database |
dba | dba_open() | dba_delete(), dba_exists(), dba_fetch(), dba_firstkey(), dba_insert(), dba_nextkey(), dba_optimize(), dba_replace(), dba_sync() | dba_close() | Link to DBA database |
dba persistent | dba_popen() | dba_delete(), dba_exists(), dba_fetch(), dba_firstkey(), dba_insert(), dba_nextkey(), dba_optimize(), dba_replace(), dba_sync() | None | Persistent link to DBA database |
dbase | dbase_open() | dbase_pack(), dbase_add_record(), dbase_replace_record(), dbase_delete_record(), dbase_get_record(), dbase_get_record_with_names(), dbase_numfields(), dbase_numrecords() | dbase_close() | Link to Dbase database |
dbx_link_object | dbx_connect() | dbx_query() | dbx_close() | dbx connection |
dbx_result_object | dbx_query() | () | None | dbx result |
domxml attribute | ||||
domxml document | ||||
domxml node | ||||
xpath context | ||||
xpath object | ||||
fbsql database | fbsql_select_db() | () | None | fbsql database |
fbsql link | fbsql_change_user(), fbsql_connect() | fbsql_autocommit(), fbsql_change_user(), fbsql_create_db(), fbsql_data_seek(), fbsql_db_query(), fbsql_drop_db(), (), fbsql_select_db(), fbsql_errno(), fbsql_error(), fbsql_insert_id(), fbsql_list_dbs() | fbsql_close() | Link to fbsql database |
fbsql plink | fbsql_change_user(), fbsql_pconnect() | fbsql_autocommit(), fbsql_change_user(), fbsql_create_db(), fbsql_data_seek(), fbsql_db_query(), fbsql_drop_db(), (), fbsql_select_db(), fbsql_errno(), fbsql_error(), fbsql_insert_id(), fbsql_list_dbs() | None | Persistent link to fbsql database |
fbsql result | fbsql_db_query(), fbsql_list_dbs(), fbsql_query(), fbsql_list_fields(), fbsql_list_tables(), fbsql_tablename() | fbsql_affected_rows(), fbsql_fetch_array(), fbsql_fetch_assoc(), fbsql_fetch_field(), fbsql_fetch_lengths(), fbsql_fetch_object(), fbsql_fetch_row(), fbsql_field_flags(), fbsql_field_name(), fbsql_field_len(), fbsql_field_seek(), fbsql_field_table(), fbsql_field_type(), fbsql_next_result(), fbsql_num_fields(), fbsql_num_rows(), fbsql_result(), fbsql_num_rows() | fbsql_free_result() | fbsql result |
fdf | fdf_open() | fdf_create(), fdf_save(), fdf_get_value(), fdf_set_value(), fdf_next_field_name(), fdf_set_ap(), fdf_set_status(), fdf_get_status(), fdf_set_file(), fdf_get_file(), fdf_set_flags(), fdf_set_opt(), fdf_set_submit_form_action(), fdf_set_javascript_action() | fdf_close() | FDF File |
ftp | ftp_connect() | ftp_login(), ftp_pwd(), ftp_cdup(), ftp_chdir(), ftp_mkdir(), ftp_rmdir(), ftp_nlist(), ftp_rawlist(), ftp_systype(), ftp_pasv(), ftp_get(), ftp_fget(), ftp_put(), ftp_fput(), ftp_size(), ftp_mdtm(), ftp_rename(), ftp_delete(), ftp_site() | ftp_quit() | FTP stream |
gd | imagecreate(), imagecreatefromgif(), imagecreatefromjpeg(), imagecreatefrompng(), imagecreatefromwbmp(), imagecreatefromstring(), imagecreatetruecolor() | imagearc(), imagechar(), imagecharup(), imagecolorallocate(), imagecolorat(), imagecolorclosest(), imagecolorexact(), imagecolorresolve(), imagegammacorrect(), imagegammacorrect(), imagecolorset(), imagecolorsforindex(), imagecolorstotal(), imagecolortransparent(), imagecopy(), imagecopyresized(), imagedashedline(), imagefill(), imagefilledpolygon(), imagefilledrectangle(), imagefilltoborder(), imagegif(), imagepng(), imagejpeg(), imagewbmp(), imageinterlace(), imageline(), imagepolygon(), imagepstext(), imagerectangle(), imagesetpixel(), imagestring(), imagestringup(), imagesx(), imagesy(), imagettftext(), imagefilledarc(), imageellipse(), imagefilledellipse(), imagecolorclosestalpha(), imagecolorexactalpha(), imagecolorresolvealpha(), imagecopymerge(), imagecopymergegray(), imagecopyresampled(), imagetruecolortopalette(), imagesetbrush(), imagesettile(), imagesetthickness() | imagedestroy() | GD Image |
gd font | imageloadfont() | imagechar(), imagecharup(), imagefontheight() | None | Font for GD |
gd PS encoding | ||||
gd PS font | imagepsloadfont() | imagepstext(), imagepsslantfont(), imagepsextendfont(), imagepsencodefont(), imagepsbbox() | imagepsfreefont() | PS font for GD |
GMP integer | gmp_init() | gmp_intval(), gmp_strval(), gmp_add(), gmp_sub(), gmp_mul(), gmp_div_q(), gmp_div_r(), gmp_div_qr(), gmp_div(), gmp_mod(), gmp_divexact(), gmp_cmp(), gmp_neg(), gmp_abs(), gmp_sign(), gmp_fact(), gmp_sqrt(), gmp_sqrtrm(), gmp_perfect_square(), gmp_pow(), gmp_powm(), gmp_prob_prime(), gmp_gcd(), gmp_gcdext(), gmp_invert(), gmp_legendre(), gmp_jacobi(), gmp_random(), gmp_and(), gmp_or(), gmp_xor(), gmp_setbit(), gmp_clrbit(), gmp_scan0(), gmp_scan1(), gmp_popcount(), gmp_hamdist() | None | GMP Number |
hyperwave document | hw_cp(), hw_docbyanchor(), hw_getremote(), hw_getremotechildren() | hw_children(), hw_childrenobj(), hw_getparents(), hw_getparentsobj(), hw_getchildcoll(), hw_getchildcollobj(), hw_getremote(), hw_getsrcbydestobj(), hw_getandlock(), hw_gettext(), hw_getobjectbyquerycoll(), hw_getobjectbyquerycollobj(), hw_getchilddoccoll(), hw_getchilddoccollobj(), hw_getanchors(), hw_getanchorsobj(), hw_inscoll(), hw_pipedocument(), hw_unlock() | hw_deleteobject() | Hyperwave object |
hyperwave link | hw_connect() | hw_children(), hw_childrenobj(), hw_cp(), hw_deleteobject(), hw_docbyanchor(), hw_docbyanchorobj(), hw_errormsg(), hw_edittext(), hw_error(), hw_getparents(), hw_getparentsobj(), hw_getchildcoll(), hw_getchildcollobj(), hw_getremote(), hw_getremotechildren(), hw_getsrcbydestobj(), hw_getobject(), hw_getandlock(), hw_gettext(), hw_getobjectbyquery(), hw_getobjectbyqueryobj(), hw_getobjectbyquerycoll(), hw_getobjectbyquerycollobj(), hw_getchilddoccoll(), hw_getchilddoccollobj(), hw_getanchors(), hw_getanchorsobj(), hw_mv(), hw_incollections(), hw_info(), hw_inscoll(), hw_insdoc(), hw_insertdocument(), hw_insertobject(), hw_mapid(), hw_modifyobject(), hw_pipedocument(), hw_unlock(), hw_who(), hw_getusername() | hw_close(), hw_free_document() | Link to Hyperwave server |
hyperwave link persistent | hw_pconnect() | hw_children(), hw_childrenobj(), hw_cp(), hw_deleteobject(), hw_docbyanchor(), hw_docbyanchorobj(), hw_errormsg(), hw_edittext(), hw_error(), hw_getparents(), hw_getparentsobj(), hw_getchildcoll(), hw_getchildcollobj(), hw_getremote(), hw_getremotechildren(), hw_getsrcbydestobj(), hw_getobject(), hw_getandlock(), hw_gettext(), hw_getobjectbyquery(), hw_getobjectbyqueryobj(), hw_getobjectbyquerycoll(), hw_getobjectbyquerycollobj(), hw_getchilddoccoll(), hw_getchilddoccollobj(), hw_getanchors(), hw_getanchorsobj(), hw_mv(), hw_incollections(), hw_info(), hw_inscoll(), hw_insdoc(), hw_insertdocument(), hw_insertobject(), hw_mapid(), hw_modifyobject(), hw_pipedocument(), hw_unlock(), hw_who(), hw_getusername() | None | Persistent link to Hyperwave server |
icap | icap_open() | icap_fetch_event(), icap_list_events(), icap_store_event(), icap_snooze(), icap_list_alarms(), icap_delete_event() | icap_close() | Link to icap server |
imap | imap_open() | imap_append(), imap_body(), imap_check(), imap_createmailbox(), imap_delete(), imap_deletemailbox(), imap_expunge(), imap_fetchbody(), imap_fetchstructure(), imap_headerinfo(), imap_header(), imap_headers(), imap_listmailbox(), imap_getmailboxes(), imap_get_quota(), imap_status(), imap_listsubscribed(), imap_set_quota(), imap_set_quota(), imap_getsubscribed(), imap_mail_copy(), imap_mail_move(), imap_num_msg(), imap_num_recent(), imap_ping(), imap_renamemailbox(), imap_reopen(), imap_subscribe(), imap_undelete(), imap_unsubscribe(), imap_scanmailbox(), imap_mailboxmsginfo(), imap_fetchheader(), imap_uid(), imap_msgno(), imap_search(), imap_fetch_overview() | imap_close() | Link to IMAP, POP3 server |
imap chain persistent | ||||
imap persistent | ||||
ingres | ingres_connect() | ingres_query(), ingres_num_rows(), ingres_num_fields(), ingres_field_name(), ingres_field_type(), ingres_field_nullable(), ingres_field_length(), ingres_field_precision(), ingres_field_scale(), ingres_fetch_array(), ingres_fetch_row(), ingres_fetch_object(), ingres_rollback(), ingres_commit(), ingres_autocommit() | ingres_close() | Link to ingresII base |
ingres persistent | ingres_pconnect() | ingres_query(), ingres_num_rows(), ingres_num_fields(), ingres_field_name(), ingres_field_type(), ingres_field_nullable(), ingres_field_length(), ingres_field_precision(), ingres_field_scale(), ingres_fetch_array(), ingres_fetch_row(), ingres_fetch_object(), ingres_rollback(), ingres_commit(), ingres_autocommit() | None | Persistent link to ingresII base |
interbase blob | ||||
interbase link | ibase_connect() | ibase_query(), ibase_prepare(), ibase_trans() | ibase_close() | Link to Interbase database |
interbase link persistent | ibase_pconnect() | ibase_query(), ibase_prepare(), ibase_trans() | None | Persistent link to Interbase database |
interbase query | ibase_prepare() | ibase_execute() | ibase_free_query() | Interbase query |
interbase result | ibase_query() | ibase_fetch_row(), ibase_fetch_object(), ibase_field_info(), ibase_num_fields() | ibase_free_result() | Interbase Result |
interbase transaction | ibase_trans() | ibase_commit() | ibase_rollback() | Interbase transaction |
java | ||||
ldap link | ldap_connect(), ldap_search() | ldap_count_entries(), ldap_first_attribute(), ldap_first_entry(), ldap_get_attributes(), ldap_get_dn(), ldap_get_entries(), ldap_get_values(), ldap_get_values_len(), ldap_next_attribute(), ldap_next_entry() | ldap_close() | ldap connection |
ldap result | ldap_read() | ldap_add(), ldap_compare(), ldap_bind(), ldap_count_entries(), ldap_delete(), ldap_errno(), ldap_error(), ldap_first_attribute(), ldap_first_entry(), ldap_get_attributes(), ldap_get_dn(), ldap_get_entries(), ldap_get_values(), ldap_get_values_len(), ldap_get_option(), ldap_list(), ldap_modify(), ldap_mod_add(), ldap_mod_replace(), ldap_next_attribute(), ldap_next_entry(), ldap_mod_del(), ldap_set_option(), ldap_unbind() | ldap_free_result() | ldap search result |
ldap result entry | ||||
mcal | mcal_open(), mcal_popen() | mcal_create_calendar(), mcal_rename_calendar(), mcal_rename_calendar(), mcal_delete_calendar(), mcal_fetch_event(), mcal_list_events(), mcal_append_event(), mcal_store_event(), mcal_delete_event(), mcal_list_alarms(), mcal_event_init(), mcal_event_set_category(), mcal_event_set_title(), mcal_event_set_description(), mcal_event_set_start(), mcal_event_set_end(), mcal_event_set_alarm(), mcal_event_set_class(), mcal_next_recurrence(), mcal_event_set_recur_none(), mcal_event_set_recur_daily(), mcal_event_set_recur_weekly(), mcal_event_set_recur_monthly_mday(), mcal_event_set_recur_monthly_wday(), mcal_event_set_recur_yearly(), mcal_fetch_current_stream_event(), mcal_event_add_attribute(), mcal_expunge() | mcal_close() | Link to calendar server |
SWFAction | ||||
SWFBitmap | ||||
SWFButton | ||||
SWFDisplayItem | ||||
SWFFill | ||||
SWFFont | ||||
SWFGradient | ||||
SWFMorph | ||||
SWFMovie | ||||
SWFShape | ||||
SWFSprite | ||||
SWFText | ||||
SWFTextField | ||||
mnogosearch agent | ||||
mnogosearch result | ||||
msql link | msql_connect() | msql(), msql_create_db(), msql_createdb(), msql_drop_db(), msql_drop_db(), msql_select_db(), msql_select_db() | msql_close() | Link to mSQL database |
msql link persistent | msql_pconnect() | msql(), msql_create_db(), msql_createdb(), msql_drop_db(), msql_drop_db(), msql_select_db(), msql_select_db() | None | Persistent link to mSQL |
msql query | msql_query() | msql(), msql_affected_rows(), msql_data_seek(), msql_dbname(), msql_fetch_array(), msql_fetch_field(), msql_fetch_object(), msql_fetch_row(), msql_fieldname(), msql_field_seek(), msql_fieldtable(), msql_fieldtype(), msql_fieldflags(), msql_fieldlen(), msql_num_fields(), msql_num_rows(), msql_numfields(), msql_numrows(), msql_result() | msql_free_result(), msql_free_result() | mSQL result |
mssql link | mssql_connect() | mssql_query(), mssql_select_db() | mssql_close() | Link to Microsft SQL Server database |
mssql link persistent | mssql_pconnect() | mssql_query(), mssql_select_db() | None | Persistent link to Microsft SQL Server |
mssql result | mssql_query() | mssql_data_seek(), mssql_fetch_array(), mssql_fetch_field(), mssql_fetch_object(), mssql_fetch_row(), mssql_field_length(), mssql_field_name(), mssql_field_seek(), mssql_field_type(), mssql_num_fields(), mssql_num_rows(), mssql_result() | mssql_free_result() | Microsft SQL Server result |
mysql link | mysql_connect() | mysql_affected_rows(), mysql_change_user(), mysql_create_db(), mysql_data_seek(), mysql_db_name(), mysql_db_query(), mysql_drop_db(), mysql_errno(), mysql_error(), mysql_insert_id(), mysql_list_dbs(), mysql_list_fields(), mysql_list_tables(), mysql_query(), mysql_result(), mysql_select_db(), mysql_tablename(), mysql_get_host_info(), mysql_get_proto_info(), mysql_get_server_info() | mysql_close() | Link to MySQL database |
mysql link persistent | mysql_pconnect() | mysql_affected_rows(), mysql_change_user(), mysql_create_db(), mysql_data_seek(), mysql_db_name(), mysql_db_query(), mysql_drop_db(), mysql_errno(), mysql_error(), mysql_insert_id(), mysql_list_dbs(), mysql_list_fields(), mysql_list_tables(), mysql_query(), mysql_result(), mysql_select_db(), mysql_tablename(), mysql_get_host_info(), mysql_get_proto_info(), mysql_get_server_info() | None | Persistent link to MySQL database |
mysql result | mysql_db_query(), mysql_list_dbs(), mysql_list_fields(), mysql_list_tables(), mysql_query() | mysql_data_seek(), mysql_db_name(), mysql_fetch_array(), mysql_fetch_assoc(), mysql_fetch_field(), mysql_fetch_lengths(), mysql_fetch_object(), mysql_fetch_row(), mysql_fetch_row(), mysql_field_flags(), mysql_field_name(), mysql_field_len(), mysql_field_seek(), mysql_field_table(), mysql_field_type(), mysql_num_fields(), mysql_num_rows(), mysql_result(), mysql_tablename() | mysql_free_result() | MySQL result |
oci8 collection | ||||
oci8 connection | ocilogon(), ociplogon(), ocinlogon() | ocicommit(), ociserverversion(), ocinewcursor(), ociparse(), ocierror() | ocilogoff() | Link to Oracle database |
oci8 descriptor | ||||
oci8 server | ||||
oci8 session | ||||
oci8 statement | ocinewdescriptor() | ocirollback(), ocinewdescriptor(), ocirowcount(), ocidefinebyname(), ocibindbyname(), ociexecute(), ocinumcols(), ociresult(), ocifetch(), ocifetchinto(), ocifetchstatement(), ocicolumnisnull(), ocicolumnname(), ocicolumnsize(), ocicolumntype(), ocistatementtype(), ocierror() | ocifreestatement() | Oracle Cursor |
odbc link | odbc_connect() | odbc_autocommit(), odbc_commit(), odbc_error(), odbc_errormsg(), odbc_exec(), odbc_tables(), odbc_tableprivileges(), odbc_do(), odbc_prepare(), odbc_columns(), odbc_columnprivileges(), odbc_procedurecolumns(), odbc_specialcolumns(), odbc_rollback(), odbc_setoption(), odbc_gettypeinfo(), odbc_primarykeys(), odbc_foreignkeys(), odbc_procedures(), odbc_statistics() | odbc_close() | Link to ODBC database |
odbc link persistent | odbc_connect() | odbc_autocommit(), odbc_commit(), odbc_error(), odbc_errormsg(), odbc_exec(), odbc_tables(), odbc_tableprivileges(), odbc_do(), odbc_prepare(), odbc_columns(), odbc_columnprivileges(), odbc_procedurecolumns(), odbc_specialcolumns(), odbc_rollback(), odbc_setoption(), odbc_gettypeinfo(), odbc_primarykeys(), odbc_foreignkeys(), odbc_procedures(), odbc_statistics() | None | Persistent link to ODBC database |
odbc result | odbc_prepare() | odbc_binmode(), odbc_cursor(), odbc_execute(), odbc_fetch_into(), odbc_fetch_row(), odbc_field_name(), odbc_field_num(), odbc_field_type(), odbc_field_len(), odbc_field_precision(), odbc_field_scale(), odbc_longreadlen(), odbc_num_fields(), odbc_num_rows(), odbc_result(), odbc_result_all(), odbc_setoption() | odbc_free_result() | ODBC result |
birdstep link | ||||
birdstep result | ||||
OpenSSL key | openssl_get_privatekey(), openssl_get_publickey() | openssl_sign(), openssl_seal(), openssl_open(), openssl_verify() | openssl_free_key() | OpenSSL key |
OpenSSL X.509 | openssl_x509_read() | openssl_x509_parse(), openssl_x509_checkpurpose() | openssl_x509_free() | Public Key |
oracle Cursor | ora_open() | ora_bind(), ora_columnname(), ora_columnsize(), ora_columntype(), ora_error(), ora_errorcode(), ora_exec(), ora_fetch(), ora_fetch_into(), ora_getcolumn(), ora_numcols(), ora_numrows(), ora_parse() | ora_close() | Oracle cursor |
oracle link | ora_logon() | ora_do(), ora_error(), ora_errorcode(), ora_rollback(), ora_commitoff(), ora_commiton(), ora_open(), ora_commit() | ora_logoff() | Link to oracle database |
oracle link persistent | ora_plogon() | ora_do(), ora_error(), ora_errorcode(), ora_rollback(), ora_commitoff(), ora_commiton(), ora_open(), ora_commit() | None | Persistent link to oracle database |
pdf document | pdf_new() | pdf_add_bookmark(), pdf_add_launchlink(), pdf_add_locallink(), pdf_add_note(), pdf_add_pdflink(), pdf_add_weblink(), pdf_arc(), pdf_attach_file(), pdf_begin_page(), pdf_circle(), pdf_clip(), pdf_closepath(), pdf_closepath_fill_stroke(), pdf_closepath_stroke(), pdf_concat(), pdf_continue_text(), pdf_curveto(), pdf_end_page(), pdf_endpath(), pdf_fill(), pdf_fill_stroke(), pdf_findfont(), pdf_get_buffer(), pdf_get_image_height(), pdf_get_image_width(), pdf_get_parameter(), pdf_get_value(), pdf_lineto(), pdf_moveto(), pdf_open_ccitt(), pdf_open_file(), pdf_open_image_file(), pdf_place_image(), pdf_rect(), pdf_restore(), pdf_rotate(), pdf_save(), pdf_scale(), pdf_setdash(), pdf_setflat(), pdf_setfont(), pdf_setgray(), pdf_setgray_fill(), pdf_setgray_stroke(), pdf_setlinecap(), pdf_setlinejoin(), pdf_setlinewidth(), pdf_setmiterlimit(), pdf_setpolydash(), pdf_setrgbcolor(), pdf_setrgbcolor_fill(), pdf_setrgbcolor_stroke(), pdf_set_border_color(), pdf_set_border_dash(), pdf_set_border_style(), pdf_set_char_spacing(), pdf_set_duration(), pdf_set_font(), pdf_set_horiz_scaling(), pdf_set_parameter(), pdf_set_text_pos(), pdf_set_text_rendering(), pdf_set_value(), pdf_set_word_spacing(), pdf_show(), pdf_show_boxed(), pdf_show_xy(), pdf_skew(), pdf_stringwidth(), pdf_stroke(), pdf_translate(), pdf_open_memory_image() | pdf_close(), pdf_delete() | PDF document |
pdf image | pdf_open_image(), pdf_open_image_file(), pdf_open_memory_image() | pdf_get_image_height(), pdf_get_image_width(), pdf_open_CCITT(), pdf_place_image() | pdf_close_image() | Image in PDF file |
pdf object | ||||
pdf outline | ||||
pgsql large object | pg_lo_open() | pg_lo_open(), pg_lo_create(), pg_lo_read(), pg_lo_read_all(), pg_lo_seek(), pg_lo_tell(), pg_lo_unlink(), pg_lo_write() | pg_lo_close() | PostgreSQL Large Object |
pgsql link | pg_connect() | pg_affected_rows(), pg_query(), pg_send_query(), pg_get_result(), pg_connection_busy(), pg_connection_reset(), pg_connection_status(), pg_last_error(), pg_last_notice(), pg_lo_create(), pg_lo_export(), pg_lo_import(), pg_lo_open(), pg_lo_unlink(), pg_host(), pg_port(), pg_dbname(), pg_options(), pg_copy_from(), pg_copy_to(), pg_end_copy(), pg_put_line(), pg_tty(), pg_trace(), pg_untrace(), pg_set_client_encoding(), pg_client_encoding(), pg_metadata(), pg_convert(), pg_insert(), pg_select(), pg_delete(), pg_update() | pg_close() | Link to PostgreSQL database |
pgsql link persistent | pg_pconnect() | pg_affected_rows(), pg_query(), pg_send_query(), pg_get_result(), pg_connection_busy(), pg_connection_reset(), pg_connection_status(), pg_last_error(), pg_last_notice(), pg_lo_create(), pg_lo_export(), pg_lo_import(), pg_lo_open(), pg_lo_unlink(), pg_host(), pg_port(), pg_dbname(), pg_options(), pg_copy_from(), pg_copy_to(), pg_end_copy(), pg_put_line(), pg_tty(), pg_trace(), pg_untrace(), pg_set_client_encoding(), pg_client_encoding(), pg_metadata(), pg_convert(), pg_insert(), pg_select(), pg_delete(), pg_update() | None | Persistent link to PostgreSQL database |
pgsql result | pg_query(), pg_get_result() | pg_fetch_array(), pg_fetch_object(), pg_fetch_result(), pg_fetch_row(), pg_field_is_null(), pg_field_name(), pg_field_num(), pg_field_prtlen(), pg_field_size(), pg_field_type(), pg_last_oid(), pg_num_fields(), pg_num_rows(), pg_result_error(), pg_result_status() | pg_free_result() | PostgreSQL result |
pgsql string | ||||
printer | ||||
printer brush | ||||
printer font | ||||
printer pen | ||||
pspell | pspell_new(), pspell_new_config(), pspell_new_personal() | pspell_add_to_personal(), pspell_add_to_session(), pspell_check(), pspell_clear_session(), pspell_config_ignore(), pspell_config_mode(), pspell_config_personal(), pspell_config_repl(), pspell_config_runtogether(), pspell_config_save_repl(), pspell_save_wordlist(), pspell_store_replacement(), pspell_suggest() | None | pspell dictionary |
pspell config | pspell_config_create() | pspell_new_config() | None | pspell configuration |
Sablotron XSLT | xslt_create() | xslt_closelog(), xslt_openlog(), xslt_run(), xslt_set_sax_handler(), xslt_errno(), xslt_error(), xslt_fetch_result(), xslt_free() | xslt_free() | XSLT parser |
shmop | shmop_open() | shmop_read(), shmop_write(), shmop_size(), shmop_delete() | shmop_close() | |
sockets file descriptor set | socket() | accept_connect(), bind(), connect(), listen(), read(), write() | close() | Socket |
sockets i/o vector | ||||
dir | dir() | readdir(), rewinddir() | closedir() | Dir handle |
file | fopen() | feof(), fflush(), fgetc(), fgetcsv(), fgets(), fgetss(), flock(), fpassthru(), fputs(), fwrite(), fread(), fseek(), ftell(), fstat(), ftruncate(), set_file_buffer(), rewind() | fclose() | File handle |
pipe | popen() | feof(), fflush(), fgetc(), fgetcsv(), fgets(), fgetss(), fpassthru(), fputs(), fwrite(), fread() | pclose() | Process handle |
socket | fsockopen() | fflush(), fgetc(), fgetcsv(), fgets(), fgetss(), fpassthru(), fputs(), fwrite(), fread() | fclose() | Socket handle |
stream | ||||
sybase-db link | sybase_connect() | sybase_query(), sybase_select_db() | sybase_close() | Link to Sybase database using DB library |
sybase-db link persistent | sybase_pconnect() | sybase_query(), sybase_select_db() | None | Persistent link to Sybase database using DB library |
sybase-db result | sybase_query() | sybase_data_seek(), sybase_fetch_array(), sybase_fetch_field(), sybase_fetch_object(), sybase_fetch_row(), sybase_field_seek(), sybase_num_fields(), sybase_num_rows(), sybase_result() | sybase_free_result() | Sybase result using DB library |
sybase-ct link | sybase_connect() | sybase_affected_rows(), sybase_query(), sybase_select_db() | sybase_close() | Link to Sybase database using CT library |
sybase-ct link persistent | sybase_pconnect() | sybase_affected_rows(), sybase_query(), sybase_select_db() | None | Persistent link to Sybase database using CT library |
sybase-ct result | sybase_query() | sybase_data_seek(), sybase_fetch_array(), sybase_fetch_field(), sybase_fetch_object(), sybase_fetch_row(), sybase_field_seek(), sybase_num_fields(), sybase_num_rows(), sybase_result() | sybase_free_result() | Sybase result using CT library |
sysvsem | sem_get() | sem_acquire() | sem_release() | System V Semaphore |
sysvshm | shm_attach() | shm_remove(), shm_put_var(), shm_get_var(), shm_remove_var() | shm_detach() | System V Shared Memory |
wddx | wddx_packet_start() | wddx_add_vars() | wddx_packet_end() | WDDX packet |
xml | xml_parser_create() | xml_set_object(), xml_set_element_handler(), xml_set_character_data_handler(), xml_set_processing_instruction_handler(), xml_set_default_handler(), xml_set_unparsed_entity_decl_handler(), xml_set_notation_decl_handler(), xml_set_external_entity_ref_handler(), xml_parse(), xml_get_error_code(), xml_error_string(), xml_get_current_line_number(), xml_get_current_column_number(), xml_get_current_byte_index(), xml_parse_into_struct(), xml_parser_set_option(), xml_parser_get_option() | xml_parser_free() | XML parser |
zlib | gzopen() | gzeof(), gzgetc(), gzgets(), gzgetss(), gzpassthru(), gzputs(), gzread(), gzrewind(), gzseek(), gztell(), gzwrite() | gzclose() | gz-compressed file |
The following is a list of the various URL style protocols that PHP has built-in for use with the filesystem functions such as fopen() and copy(). In addition to these wrappers, as of PHP 4.3, you can write your own wrappers using PHP script and stream_register_wrapper().
PHP 3, PHP 4. https:// since PHP 4.3
http://example.com
http://user:password@example.com
https://example.com
https://user:password@example.com
Allows read-only access to files/resources via HTTP 1.0, using the HTTP GET method. A Host: header is sent with the request to handle name-based virtual hosts. If you have configured a user_agent string using your ini file or the stream context, it will also be included in the request.
Redirects have been supported since PHP 4.0.5; if you are using an earlier version you will need to include trailing slashes in your URLs.
The stream allows access to the body of the resource; the headers are stored in the $http_response_header variable. Since PHP 4.3, the headers are available using stream_get_meta_data().
HTTP connections are read-only; you cannot write data or copy files to an HTTP resource.
Nota: HTTPS is supported starting from PHP 4.3, if you have compiled in support for OpenSSL.
PHP 3, PHP 4. ftps:// since PHP 4.3
ftp://example.com/pub/file.txt
ftp://user:password@example.com/pub/file.txt
ftps://example.com/pub/file.txt
ftps://user:password@example.com/pub/file.txt
Allows read access to existing files and creation of new files via FTP. If the server does not support passive mode ftp, the connection will fail.
You can open files for either reading or writing, but not both simultaneously. If the remote file already exists on the ftp server and you attempt to open it for writing, the connection will fail. If you need to update existing files over ftp, use ftp_connect().
ftps:// was introduced in PHP 4.3. It is the same as ftp://, but attempts to negotiate a secure connection with the ftp server. If the server does not support SSL, then the connection falls back to regular unencrypted ftp.
Nota: FTPS is supported starting from PHP 4.3, if you have compiled in support for OpenSSL.
PHP 3.0.13 and up, php://output and php://input since PHP 4.3
php://stdin
php://stdout
php://stderr
php://output
php://input
php://stdin, php://stdout and php://stderr allow access to the corresponding input or output stream of the PHP process.
php://output allows you to write to the output buffer mechanism in the same way as print() and echo().
php://input allows you to read raw POST data. It is a less memory intensive alternative to $HTTP_RAW_POST_DATA and does not need any special php.ini directives.
php://stdin and php://input are read-only, whereas php://stdout, php://stderr and php://output are write-only.
zlib: PHP 4.0.4 - PHP 4.2.3 (systems with fopencookie only)
compress.zlib:// and compress.bzip2:// PHP 4.3 and up
zlib:
compress.zlib://
compress.bzip2://
zlib: works like gzopen(), except that the stream can be used with fread() and the other filesystem functions. This is deprecated as of PHP 4.3 due to ambiguities with filenames containing ':' characters; use compress.zlib:// instead.
compress.zlib:// and compress.bzip2:// are equivalent to gzopen() and bzopen() respectively, and operate even on systems that do not support fopencookie.
Various parts of the PHP language are represented internally by types like T_SR. PHP outputs identifiers like this one in parse errors, like "Parse error: unexpected T_SR, expecting ',' or ';' in script.php on line 10."
You're supposed to know what T_SR means. For everybody who doesn't know that, here is a table with those identifiers, PHP-syntax and references to the appropriate places in the manual.
Tabela J-1. Tokens
Token | Syntax | Reference |
---|---|---|
T_AND_EQUAL | &= | assignment operators |
T_ARRAY | array() | array(), array syntax |
T_ARRAY_CAST | (array) | type-casting |
T_AS | as | foreach |
T_BAD_CHARACTER | anything below ASCII 32 except \t (0x09), \n (0x0a) and \r (0x0d) | |
T_BOOLEAN_AND | && | logical operators |
T_BOOLEAN_OR | || | logical operators |
T_BOOL_CAST | (bool) or (boolean) | type-casting |
T_BREAK | break | break |
T_CASE | case | switch |
T_CHARACTER | ||
T_CLASS | class | classes and objects |
T_CLOSE_TAG | ?> or %> | |
T_COMMENT | // or # | comments |
T_CONCAT_EQUAL | .= | assignment operators |
T_CONST | const | |
T_CONSTANT_ENCAPSED_STRING | "foo" or 'bar' | string syntax |
T_CONTINUE | continue | |
T_CURLY_OPEN | ||
T_DEC | -- | incrementing/decrementing operators |
T_DECLARE | declare | declare |
T_DEFAULT | default | switch |
T_DIV_EQUAL | /= | assignment operators |
T_DNUMBER | 0.12, etc | floating point numbers |
T_DO | do | do..while |
T_DOLLAR_OPEN_CURLY_BRACES | ${ | complex variable parsed syntax |
T_DOUBLE_ARROW | => | array syntax |
T_DOUBLE_CAST | (real), (double) or (float) | type-casting |
T_ECHO | echo | echo() |
T_ELSE | else | else |
T_ELSEIF | elseif | elseif |
T_EMPTY | empty | empty() |
T_ENCAPSED_AND_WHITESPACE | ||
T_ENDDECLARE | enddeclare | declare, alternative syntax |
T_ENDFOR | endfor | for, alternative syntax |
T_ENDFOREACH | endforeach | foreach, alternative syntax |
T_ENDIF | endif | if, alternative syntax |
T_ENDSWITCH | endswitch | switch, alternative syntax |
T_ENDWHILE | endwhile | while, alternative syntax |
T_END_HEREDOC | heredoc syntax | |
T_EVAL | eval() | eval() |
T_EXIT | exit or die | exit(), die() |
T_EXTENDS | extends | extends, classes and objects |
T_FILE | __FILE__ | constants |
T_FOR | for | for |
T_FOREACH | foreach | foreach |
T_FUNCTION | function or cfunction | functions |
T_GLOBAL | global | variable scope |
T_IF | if | if |
T_INC | ++ | incrementing/decrementing operators |
T_INCLUDE | include() | include() |
T_INCLUDE_ONCE | include_once() | include_once() |
T_INLINE_HTML | ||
T_INT_CAST | (int) or (integer) | type-casting |
T_ISSET | isset() | isset() |
T_IS_EQUAL | == | comparison operators |
T_IS_GREATER_OR_EQUAL | >= | comparison operators |
T_IS_IDENTICAL | === | comparison operators |
T_IS_NOT_EQUAL | != or <> | comparison operators |
T_IS_NOT_IDENTICAL | !== | comparison operators |
T_SMALLER_OR_EQUAL | <= | comparison operators |
T_LINE | __LINE__ | constants |
T_LIST | list() | list() |
T_LNUMBER | 123, 012, 0x1ac, etc | integers |
T_LOGICAL_AND | and | logical operators |
T_LOGICAL_OR | or | logical operators |
T_LOGICAL_XOR | xor | logical operators |
T_MINUS_EQUAL | -= | assignment operators |
T_ML_COMMENT | /* and */ | comments |
T_MOD_EQUAL | %= | assignment operators |
T_MUL_EQUAL | *= | assignment operators |
T_NEW | new | classes and objects |
T_NUM_STRING | ||
T_OBJECT_CAST | (object) | type-casting |
T_OBJECT_OPERATOR | -> | classes and objects |
T_OLD_FUNCTION | old_function | old_function |
T_OPEN_TAG | <?php, <? or <% | escaping from HTML |
T_OPEN_TAG_WITH_ECHO | <?= or <%= | escaping from HTML |
T_OR_EQUAL | |= | assignment operators |
T_PAAMAYIM_NEKUDOTAYIM | :: | :: |
T_PLUS_EQUAL | += | assignment operators |
T_PRINT | print() | print() |
T_REQUIRE | require() | require() |
T_REQUIRE_ONCE | require_once() | require_once() |
T_RETURN | return | returning values |
T_SL | << | bitwise operators |
T_SL_EQUAL | <<= | assignment operators |
T_SR | >> | bitwise operators |
T_SR_EQUAL | >>= | assignment operators |
T_START_HEREDOC | <<< | heredoc syntax |
T_STATIC | static | variable scope |
T_STRING | ||
T_STRING_CAST | (string) | type-casting |
T_STRING_VARNAME | ||
T_SWITCH | switch | switch |
T_UNSET | unset() | unset() |
T_UNSET_CAST | (unset) | (not documented; casts to NULL) |
T_USE | use | (not implemented) |
T_VAR | var | classes and objects |
T_VARIABLE | $foo | variables |
T_WHILE | while | while, do..while |
T_WHITESPACE | ||
T_XOR_EQUAL | ^= | assignment operators |
T_FUNC_C | __FUNCTION__ | constants, since PHP 4.3.0 |
T_CLASS_C | __CLASS__ | constants, since PHP 4.3.0 |
O manual do PHP é fornecido em vários formatos. Esses formatos podem ser divididos em dois grupos: de leitura online e em pacotes para download.
Nota: Algumas editoras tornaram disponíveis versões impressas desse manual. Nós não podemos recomendar nenhum deles, pois eles se tornam desatualizados rapidamente.
Você pode ler o manual online em http://www.php.net/ e em numerosos mirrors. Para melhor performance, escolha o mirror localizado mais fisicamente próximo a você. Você pode visualizar o manual no formato HTML simples ou em um formato HTML que se assemelha ao próprio look and feel do site do PHP
A vantagem do manual online para a maioria dos formatos offline é a sua integração com os comentários dos usuários. A desvantagem óbvia é que você precisa estar online para ler o manual.
Existem vários formatos offline do manual, e o formato mais apropriado para você depende do seu sistema operacional de seu estilo pessoal de leitura. Para informações de como esse manual é gerado e quais são esses formatos, veja a seção 'Como nós criamos os formatos' deste apêndice.
As versões mais independentes de plataforma são o HTML e o texto simples. O formato HTML é fornecido em um único arquivo e também como um pacote de arquivos individuais para cada seção (o que resulta numa coleção de vários milhares de arquivos). Os formatos HTML e texto simples são condensados com o tar e comprimidos usando o bzip2.
Outro formato popular independente de plataforma, e que ainda fornece suporte a impressão, é o PDF (também conhecido como Adobe Acrobat). Mas antes de você baixar o manual neste formato e apertar o botão Imprimir, esteja avisado que o ele tem por volta de 2000 páginas, e está sendo constantemente revisado.
Nota: Se você ainda não tem um programa capaz de visualizar arquivos PDF, você precisará baixar o Adobe Acrobat Reader.
Para proprietários de handhelds compatíveis com o Palm, os formatos DOC e iSilo são ideias para esta plataforma. Você pode ter no seu handheld de seu uso diário um visualizador DOC ou iSilo para aumentar seu conhecimento em PHP, ou apenas como referência rápida.
Para a plataforma Windows, a versão HTML Help do manual condensa os originais no formato HTML para o uso com o HTML Help. Esse formato tem busca de textos, índice completo e marcadores. Vários ambientes de desenvolvimento populares do PHP em Windows se integram com esse formato da documentação para facilitar o acesso a documentação.
Os comentários de usuários são uma importante presença no desenvolvimento deste manual. Permitindo aos usuários do manual a contribuir com exemplos e outros esclarecimentos através de seus browsers, nós podemos incorporar esse feedback no corpo do manual. E até que as notas sejam incorporadas, os comentários podem ser visualizados na versão online e em alguns formatos offline.
Nota: As contribuições dos usuários não são moderadas antes da sua publicação online, então a qualidade desses textos e exemplos ou a veracidade e origem dessas contribuições não pode ser garantida. (Note que não há uma garantia total de qualidade ou exatidão do próprio manual.)
Cada função é documentada para referência rápida, e conhecendo como ler e entender o manual fará com que a utilização do PHP seja muito mais fácil. Mais do que simplesmente estudar exemplos ou copiar e colar, você precisa saber como ler as definições de função (protótipo). Vamos começar:
Pré-requisito: Conhecimento básico dos tipos: Mesmo sendo o PHP uma linguagem fracamente tipada, é importante ter um conhecimento básico dos tipo pois eles tem um significado importante.
Definições de função nos dizem que tipo de valor é retornado, e vamos utilizar a definição de strlen() como nosso primeiro exemplo:
strlen (PHP 3, PHP 4 >= 4.0.0) strlen -- Obtêm o tamanho da string Description int strlen ( string str ) Retorna o comprimento da string. |
Tabela K-1. Detalhamento da definição da função
Parte | Descrição |
---|---|
strlen | Nome da função. |
(PHP 3, PHP 4 >= 4.0.0) | strlen() está disponível em todos os PHP 3 e PHP 4 |
int | Tipo do valor que esta função retorna, que no caso é um inteiro (no caso, o comprimento de uma string é medida em números). |
( string str ) | O primeiro (e neste caso, o único) parâmetro/argumento da função strlen() é chamado str, e é uma string. |
Nos podemos reescrever a definição de função acima de maneira genérica:
tipo retornado nome da função ( parametro tipo parametro tipo ) |
Muitas funções tem parâmetros multiplos, como in_array(). Seu protótipo é como:
bool in_array ( mixed needle, array haystack [, bool strict]) |
O que isso significa? in_array() retorna um valor booleano, TRUE em caso de sucesso (needle foi encontrado em haystack) ou FALSE em caso de falha (needle não foi encontrado em haystack). O primeiro parâmetro é chamado needle e pode de ser de vários tipos, por isso nós dizemos que ele é "mixed". Esse needle mixed (que nós estamos procurando) pode ser tanto um valor escalar (string, inteiro, ou float), ou um array. haystack (o array onde nós estamos procurando) é o segundo parâmetro. O terceiro parâmetro opcional é chamado strict. Todos os parâmetros opcionais aparecem dentro de [ colchetes ]. O manual diz que o default do parâmetro strict é o booleano FALSE. Veja a página de do manual de cada função para detalhes de como elas funcionam.
Esse manual não fornece instruções sobre práticas gerais de programação. Se esse é seu primeiro contato, ou se ainda está iniciando em programação, você poderá encontrar dificuldade em aprender a programar em PHP apenas usando esse manual. Você precisa procurar textos destinados a orientar os iniciantes. Você pode encontrar uma lista de livros relacionados ao PHP em http://www.php.net/books.php.
Há também um grande número de listas de discussão ativas para todos os aspectos da programação com o PHP. Se você se deparar com um problema que por si só não consegue solucionar, você poderá obter ajuda nestas listas. Uma relação dessas listas pode ser encontrada em http://www.php.net/support.php, como também links para os arquivos dessas listas de discussão e outras fontes de suporte online. Em http://www.php.net/links.php há uma relação de sites com artigos, fóruns e galerias de código PHP.
Há várias maneiras de você contribuir a melhorar essa documentação.
Se você encontrar erros no manual, em qualquer língua, notifique-os utilizando o rastreamento de bugs em http://bugs.php.net/. Classifique o problema com um "Documentation Problem". Você também pode submeter problemas específicos dos formatos do manual nesse endereço.
Nota: Por favor, não abuse do rastreamento de bugs para solicitar ajuda. Use as listas de discussão ou as comunidades mencionadas anteriormente.
Você pode também contribuir com comentários, fornecendo exemplos adicionais e esclarecimentos para outros leitores. Mas não envie notificações de bugs usando o sistema de comentários. Você pode ler mais sobre os comentários na seção 'Sobre os comentários de usuários' deste apêndice.
Se você sabe Inglês e alguma outra língua, você pode ajudar com as traduções. Se você deseja iniciar uma nova tradução, ou ajudar num projeto de tradução, leia o http://cvs.php.net/co.php/phpdoc/howto/howto.html.tar.gz.
Este manual é escrito em XML, utilizando o DocBook XML DTD e usando DSSSL (Document Style and Semantics Specification Language) para formatação. Experimentalmente XSLT (Extensible Stylesheet Language Transformations) para manutenção e formatação.
Utilizando XML como meta dado nos permite gerar vários outros formatos a partir dos arquivos fonte, ao mesmo tempo que a manutenção é feita em um único lugar para todas as versões. As ferramentas utilizadas para criar as versões HTML e TeX são o Jade, escrito por James Clark, e The Modular DocBook Stylesheets, escrito por Norman Walsh. Nós utilizamos o Microsoft HTML Help Workshop para criar o formato HTML Help e, é claro, o próprio PHP para fazer algumas conversões adicionais.
Você pode obter o manual em várias línguas e formatos, incluindo texto simples, HTML, PDF, PalmPilot DOC, PalmPilot iSilo e Windows HTML Help, a partir do http://www.php.net/docs.php. Os manuais são automaticamente atualizados quando da alteração dos fontes.
Para maiores informações sobre como obter os fontes XML desta documentação, veja em http://cvs.php.net/. A documentação é guardada no módulo phpdoc.
O manual do PHP não está disponível apenas em vários formatos, mas também em várias línguas. O texto do manual é primeiramente escrito em Inglês, então um time de pessoas ao redor do mundo fazem a tradução em suas línguas natais. Se a tradução de uma função específica ou de um capítulo ainda não foi realizada, o sistema de compilação do manual utiliza a versão original em Inglês.
As pessoas envolvidas na tradução iniciam a partir dos fontes XML disponíveis em http://cvs.php.net/ e partir daí traduzem para sua lingua mãe. Eles não utilizam as versões HTML, texto ou PDF. É o sistema de compilação do manual que converte os fontes XML para formatos mais legíveis.
Nota: Se você quiser colaborar com a tradução da documentação para a sua língua, entre e contato com o time de documentação e tradução, inscrevendo-se na lista de discussão phpdoc: para isso, encaminhe um e-mail em branco para phpdoc-subscribe@lists.php.net. O endereço da lista é em phpdoc@lists.php.net. Depois, encaminhe uma mensagem mencionando seu interesse em traduzir o manual para uma língua que você receberá retorno, fornecendo ajuda para você começar a tradução para uma nova língua ou participar do time de documentação da sua língua.
Atualmente o manual está disponível, parcialmente ou não, nas seguintes línguas: Português (Brasil), Chinês, Checo, Holandês, Francês, Alemão, Húngaro, Italiano, Japonês, Koreano, Polonês e Espanhol.
Todos eles podem ser baixados aqui: http://www.php.net/docs.php.