2005-10-26
Copyright © 1997-2005 Gruppo di Documentazione PHP
Copyright
Questo manuale è © Copyright 1997-2005 del Gruppo di Documentazione PHP. Questo manuale può essere redistribuito secondo i termini e le condizioni indicate dalla Open Publication License, v1.0 o successive (l'ultima versione è disponibile a http://www.opencontent.org/openpub/).
La distribuzione di versioni modificate di questo manuale è proibita senza l'esplicito consenso dei detentori del copyright.
La distribuzione di parte o di derivati da parti del manuale in qualsiasi forma di libro standard (cartaceo) è proibita senza un preventivo permesso ottenuto dai detentori del copyright.
In caso si desideri distribuire o pubblicare questo documento, totalmente od in parte, sia in versione integrale o modificata, oppure se si hanno dubbi, contattare i detentori del copyright a phpdoc@lists.php.net. Nota: questo indirizzo porta ad una mailing list pubblica.
La sezione 'Estendere PHP 4.0' di questo manuale è copyright © 2000 della Zend Technologies, Ltd. Questo materiale può essere distribuito solo secondo i termini e le condizioni della Open Publication License, v1.0 o successiva (la versione più recente è al momento disponibile qui http://www.opencontent.org/openpub/).
PHP, che significa "PHP: Hypertext Preprocessor", è un linguaggio di scripting general-purpose Open Source molto utilizzato, è specialmente indicato per lo sviluppo Web e può essere integrato nell'HTML. La sua sintassi è basata su quella di C, Java e Perl, ed è molto semplice da imparare. L'obiettivo principale del linguaggio è quello di permettere agli sviluppatori web di scrivere velocemente pagine web dinamiche, ma con PHP si possono fare molte altre cose.
Questo manuale consiste principalmente in un elenco commentato di funzioni, ma contiene anche una guida al linguaggio, la spiegazione di alcune delle principali caratteristiche e altre informazioni aggiuntive.
Il manuale è fornito in diversi formati qui: ???. Maggiori informazioni su come questo manuale viene sviluppato possono essere trovate nell'appendice 'Informazioni sul Manuale'. Se si è interessati alla storia del PHP, leggere l'appendice.
We highlight the currently most active people on the manual frontpage, but there are many more contributors who currently help in our work or provided a great amount of help to the project in the past. There are a lot of unnamed people who help out with their user notes on manual pages, which continually get included in the references, the work of whom we are also very thankful. All the lists provided below are in alphabetical order.
The following contributors should be recognized for the impact they have made and/or continue to make by adding content to the manual: Jouni Ahto, Alexander Aulbach, Daniel Beckham, Stig Bakken, Jesus M. Castagnetto, Ron Chmara, Sean Coates, John Coggeshall, Simone Cortesi, Markus Fischer, Wez Furlong, Sara Golemon, Rui Hirokawa, Brad House, Moriyoshi Koizumi, Rasmus Lerdorf, Andrew Lindeman, Stanislav Malyshev, Rafael Martinez, Yasuo Ohgaki, Derick Rethans, Sander Roobol, Egon Schmid, Thomas Schoefbeck, Sascha Schumann, Dan Scott, Lars Torben Wilson, Jim Winstead, Jeroen van Wolffelaar e Andrei Zmievski.
The following contributors have done significant work editing the manual: Stig Bakken, Hartmut Holzgraefe e Egon Schmid.
The currently most active maintainers are: Mehdi Achour, Friedhelm Betz, Vincent Gevers, Aidan Lister, Nuno Lopes e Tom Sommer.
These people have also put a lot of effort into managing user notes: Daniel Beckham, Victor Boivie, Jesus M. Castagnetto, Nicolas Chaillan, Ron Chmara, James Cox, Sara Golemon, Zak Greant, Szabolcs Heilig, Oliver Hinckel, Hartmut Holzgraefe, Rasmus Lerdorf, Andrew Lindeman, Maxim Maletsky, James Moore, Sebastian Picklum, Derick Rethans, Sander Roobol, Damien Seguy, Jason Sheets, Jani Taskinen, Yasuo Ohgaki, Philip Olson, Lars Torben Wilson, Jim Winstead, Jared Wyles e Jeroen van Wolffelaar.
PHP (acronimo ricorsivo per "PHP: Hypertext Preprocessor") è un linguaggio di scripting general-purpose Open Source molto utilizzato, è specialmente indicato per lo sviluppo Web e può essere integrato nell'HTML.
Risposta banale, ma che cosa significa? Un esempio:
Notate come questo esempio è differente da uno script scritto in altri linguaggi tipo Perl o C -- invece di scrivere un programma con parecchi comandi per produrre HTML, si scrive in HTML con qualche comando immerso per ottenere dei risultati (in questo semplice esempio, la visualizzazione di una frase). Il codice PHP è delimitato da speciali start ed end tag che ne indicano l'inizio e la fine e che consentono di passare dal modo HTML al modo PHP.
Ciò che distingue PHP da altri linguaggi di scripting del tipo client-side JavaScript è che il codice viene eseguito nel server. Per avere uno script simile a quello sopra nel vostro server, il client dovrebbe ricevere il risultato ottenuto con lo script, senza sapere mai quali sono le funzioni eseguite. Potete persino configurare il vostro web server per processare tutte i vostri file HTML con PHP ed allora non ci sarebbe realmente alcun modo per gli utenti di sapere cosa avete sul vostro server.
La cosa più interessante nell'uso di PHP è che si tratta di un linguaggio estremamente semplice per il neofita, ma che, tuttavia, offre molte prestazioni avanzate al programmatore di professione. Non lasciatevi impressionare dalla lunga lista delle potenzialità di PHP. In poco tempo potrete iniziare a creare velocemente semplici scripts.
Sebbene lo sviluppo di PHP abbia come obiettivo lo scripting server-side, si può fare molto di più con esso. Leggete, e consultate la sezione Che cosa può fare PHP? oppure andate su tutorial introduttivo se si è interessati solo alla programmazione web.
Qualsiasi cosa. PHP ha come obiettivo principale lo scripting server-side, per cui può fare tutto ciò che può fare un qualunque programma CGI, come raccogliere dati da un form, generare pagine dai contenuti dinamici, oppure mandare e ricevere cookies. Ma PHP può fare molto di più.
Esistono tre campi principali in cui vengono usati gli scripts PHP.
Lo scripting server-side. Questo è il campo più tradizionale ed il maggiore obiettivo del PHP. Per fare questo lavoro occorrono tre cose. Il parser PHP (CGI o server module), un webserver ed un browser web. Occorre avviare il server web con un'installazione di PHP attiva. Si può accedere all'output del programma PHP con un browser web e vedere la pagina PHP tramite il server. Tutto ciò può essere attivato sul pc di casa se si desidera semplicemenet provare la programmazione PHP. Consultate la sezione Istruzioni per l'installazione per ulteriori informazioni.
Lo scripting di righe di comando. Si può creare uno script PHP da usare senza alcun server o browser. Per usarlo in questo modo, l'unica cosa necessaria è un parser PHP. Questo tipo di utilizzo è ideale per gli scripts eseguiti con cron (sui sistemi *nix o Linux) oppure il Task Scheduler (su Windows). Questi script possono essere utilizzati per semplici task di proessamento testi. Vedere la sezione Uso di righe di comando in PHP per maggiori informazioni.
Scrittura di applicazioni desktop. Probabilmente PHP non è il linguaggio più adatto per scrivere applicazioni desktop, con interfaccia grafica, ma, se lo si conosce molto bene, e se se ne vogliono usare delle caratteristiche avanzate in applicazioni client-side, si può anche adoperare PHP-GTK per scrivere questo tipo di pogrammi. Allo stesso modo, c'è anche la possibilità di scrivere applicazioni cross-platform. PHP-GTK è un'estensione di PHP non reperibile nella grande distribuzione. Se vi interessa, visitate il sito web.
PHP può essere usato su tutti i principali sistemi operativi, inclusi Linux, molte varianti di Unix (compresi HP-UX, Solaris e OpenBSD), Microsoft Windows, MacOS X, MacOS Xserver, RISC OS, e probabilmente altri. Inoltre supporta anche la maggior parte dei server web esistenti. Ciò comprende Apache, Microsoft Internet Information Server, Personal Web Server, i servers Netscape ed iPlanet, Oreilly Website Pro Server, Caudium, Xitami, OmniHTTPd, e molti altri. Per la maggioranza dei servers PHP ha un modulo, per gli altri che supportano lo standard CGI, può funzionare come un processore CGI.
Pertanto, con PHP si ha la libertà di scegliere praticamente qualsiasi sistema operativo e qualsiasi server web. Inoltre, si può anche scegliere se fare uso di una programmazione procedurale oppure orientata agli oggetti, o una combinazione di entrambe. Sebbene non tutte le caratteristiche standard di OOP siano realizzate in PHP 4, molte librerie di codice e grandi applicazioni (compresa PEAR library) sono state scritte usando codice OOP. Con la version 5, il PHP supera le debolezze dell'OOP presenti in PHP 4, ed introduce in modo completo il modello a oggetti.
Con PHP non siete limitati soltanto ad un output in HTML. Le possibilità di PHP, infatti, includono l'abilità di generare immagini, files PDF e perfino filmati Flash al volo (utilizzando libswf e Ming). Sarete in grado di generare facilmente qualsiasi testo, come XHTML e qualsiasi altro file XML. PHP può autogenerare questi file, e salvarli nel file system, piuttosto che eseguire un printing esterno, o creare server-side cache per contenuti dinamici.
Una delle caratteristiche più importanti e significative di PHP è la possibilit` di supportare una completa gamma di databases. Scrivere una pagina web collegata ad un database è incredibilmente semplice. Attualmente sono supportati i seguenti database:
Esiste anche un'estensione DBX database abstraction extension, che vi permette di usare in modo trasparente qualsiasi database da essa supportato. Inoltre PHP supporta ODBC, lo standard di collegamento con i database, pertanto è possibile collegarsi con qualsiasi database che supporti questo standard mondiale.
Adabas D InterBase PostgreSQL dBase FrontBase SQLite Empress mSQL Solid FilePro (read-only) Direct MS-SQL Sybase Hyperwave MySQL Velocis IBM DB2 ODBC Unix dbm Informix Oracle (OCI7 and OCI8) Ingres Ovrimos
PHP fa anche da supporto per dialogare con altri servizi utilizzando i protocolli del tipo LDAP, IMAP, SNMP, NNTP, POP3, HTTP, COM (in Windows) e innumerevoli altri. Potete anche aprire network sockets ed interagire usando qualsiasi altro protocollo. Inoltre supporta l'interscambio di dati complessi WDDX tra, virtualmente, tutti i linguaggi di programmazione web. A proposito di interconessioni, PHP supporta l'installazione dei JavaObjects e l'utilizzo di questi come oggetti PHP in modo trasparente. Si può anche usare la nostra estensione CORBA per accedere ad oggetti remoti.
PHP possiede alcune caratteristiche molto utili per la gestione del testo, da POSIX Extended o Perl regular expressions al parsing di documenti XML. Per fare il parsing ed accedere ai documenti XML, il PHP 4 supporta gli standard SAX e DOM, e si può utilizzare il modulo XSLT per le trasformazioni dei docuemtni XML. Il PHP 5 standardizza tutte le estensioni XML sulla base solida di libxml2 ed espande le caratteristiche aggiungendo SimpleXML ed XMLReader.
Se si usa PHP nel campo dell'E-commerce, si avranno a disposizione funzioni utili per i programmi di pagamento online, come: Cybercash, CyberMUT, Verysign Payflow Pro e MCVE.
L'ultimo, ma di non poca importanza, PHP ha molte altre estensioni interessanti, come funzioni per motori di ricerca mnoGoSearch, le funzioni IRC Gateway, molte utilità di compressione (gzip, bz2), conversione dei calendari, traduzione...
Come si può notare, questa pagina non è sufficiente per elencare tutte le funzioni che PHP offre. Per approfondire il discorso sulle suddette caratteristiche, consultate le sezioni Installazione di PHP, e function reference
Di seguito, in una breve e semplice introduzione, vorremmo mostrare alcuni esempi per l'utilizzo di PHP. Essi sono relativi soltanto alla creazione dinamica di pagine web, anche se PHP non ha funzionalità limitate esclusivamente alla creazione delle sole pagine web. Fare riferimento alla sezione intitolata Cosa può fare PHP per avere ulteriori informazioni.
Le pagine web create con PHP vengono trattate come normali pagine HTML e possono essere create e modificate nello stesso modo in cui si sviluppano normali pagine HTML.
In questo tutorial assumiamo che il vostro server abbia il suporto PHP attivato e che tutti i file con estensione .php vengano gestiti da questo. Quasi in tutti i server questa è l'estensione di default per i file PHP., ma consultatevi col vostro system administrator per sicurezza. Se il vostro server supporta PHP, allora, non è necessario fare nulla. Semplicemente create i vostri file .php e scaricateli nella vostra directory web, il server le analizzerà e le eseguirà magicamente. Non è necessario compilare nulla nè installare strumenti aggiuntivi. Si pensi ai file PHP come a dei semplici file HTML con una intera famiglia aggiuntiva di magici tags che consentono di fare ogni sorta di cose.
Creare un file con nome ciao.php nella directory del web server che abbia il seguente contenuto:
Si noti che questo file non è come uno script CGI. Il file non necessita in alcun modo di essere eseguibile o speciale in alcuna maniera. Si pensi ad esso come ad un normale file HTML nel quale sono contenuti uno speciale set di tags che permettono di eseguire una moltitudine di cose interessanti.
Questo programma è molto semplice e sicuramente non era necessario fare ricorso a PHP per creare una pagina come quella. Tutto ciò che essa fa è di visualizzare: Hello World! usando la funzione echo() di PHP.
Se si è provato questo esempio e non ha dato alcun output, o è apparso un pop-up che chiedeva se scaricare la pagina, o se è apparso il file come testo, probabilmente che il server su cui si stanno effettuando le prove non ha abilitato PHP. Provare a chiedere al proprio amministratore di sistema di abilitarlo per voi usando il capitolo del manuale dedicato all'Installazione. Se si vogliono sviluppare in locale script PHP, fare riferimento alla sezione download. Si può sviluppare senza problemi sul proprio Sistema Operativo in locale, è bene installare anche un web server.
L'obiettivo dell'esempio è quello di mostrare il formato speciale dei tag PHP. In questo esempio abbiamo usato <?php per indicare l'inizio di un tag PHP. Quindi abbiamo scritto la funzione PHP e abbiamo lasciato la modalità PHP usando il tag di chiusura, ?>. All'interno di un file HTML si può entrare ed uscire dalla modalità PHP quante volte si desidera.
Nota riguardo gli editor di testo: Esistomo molti editor di testo e Integrated Development Environment (IDE) che possono essere usati per creare, modificare e gestire file PHP. Una lista parziale di questi strumenti è disponibile qui: PHP Editor's List. Se si desidera suggerire un nuovo programma, visitare la pagina sopra e chiedere al curatore di aggiungerlo alla lista.
Nota riguardo i Word Processor: Word processor quali StarOffice Writer, Microsoft Word e Abiword non sono una buona scelta per modificare i file PHP.
Se si vogliono provare comunque per scrivere questo script di test, ci si deve assicurare di salvare il file come SOLO TESTO, altrimenti PHP non sarà in grado di leggerlo e quindi non riuscirà ad eseguire lo script.
Nota riguardo Blocco Note di Windows: Se si scrive codice usando l'applicazione di Windows Blocco Note, occorre assicurarsi che i file vengano salvati con estensione .php. (Blocco Note aggiunge automaticamente l'estensione .txt ai file, a meno che non si intraprenda uno dei passi descritti di seguito.)
Quando si salva il file e viene chiesto il nome da assegnargli, scrivere il nome fra virgolette (ad esempio: "ciao.php").
In alternativa, si può cliccare sul menu a tendina 'Documenti di Testo' nella finestra di salvataggio e cambiare l'impostazione in "Tutti i File". A quel punto si può inserire il nome del file, senza usare le virgolette.
Andiamo a fare qualcosa di leggermente più utile. Andremo a controllare che tipo di browser sta utilizzando la persona che visita le nostre pagine. Per fare questo si andrà a controllare la stringa dell'user agent che il browser invia come parte della richiesta HTTP. Quest'informazione viene inviata in una variabile. Le Variabili iniziano sempre con il simbolo di dollaro $ in PHP. La variabile alla quale ci riferiamo adesso è $_SERVER["HTTP_USER_AGENT"].
Note sulle variabili Autoglobali di PHP: $_SERVER è una variabile speciale riservata a PHP la quale contiene tutte le informazioni relative al Web Server. È conosciuta come Variabile autoglobale (o Superglobale). Per maggiori informazioni è possibile vedere la pagina del manuale relativa alle Variabili Autoglobali. Questo tipo di variabili sono state introdotte nella versione 4.1.0 di PHP. Nelle versioni precedenti abbiamo utilizzato le ormai vecchie $HTTP_SERVER_VARS, oggi in disuso, anche se queste continuano ad esistere. (Potete guardare nelle note del vecchio codice.)
Per visualizzare questa variabile, dobbiamo semplicemente:
Ci sono molti types (tipi) di variabili disponibili in PHP. Nell'esempio di sopra abbiamo stampato un elemento di un Array. Gli Array possono essere molto utili.
$_SERVER è soltanto una variabile che automaticamente viene resa diponibile da PHP. È possibile visualizzare una lunga lista nella sezione Variabili riservate del manuale oppure ottenere la lista completa creando un file php nella seguente forma:
Se caricate questo documento da un browser riceverete una pagina piena d'informazioni circa PHP, così come la lista di tutte le variabili disponibili.
Potete mettere dichiarazioni multipli di PHP all'interno di un tag di PHP e generare piccoli blocchi di codice che fanno di più di un singolo echo. Per esempio, se desiderassimo controllare per vedere se l'utente usa Internet Explorer potremmo fare qualcosa come questo:
Esempio 2-4. Esempi usando le strutture di controllo e le funzioni
L'output di esempio di questo script potrebbe essere:
|
Qui introduciamo una coppia di nuovi concetti. Abbiamo la dichiarazione if (se). Se avete una conoscenza con la sintassi di base usata dal linguaggio C questo dovrebbe sembrare logico per voi. Se non conoscete abbastanza C od un altro linguaggio che utilizza la sintassi qui sopra descritta, dovreste probabilmente prendere qualsiasi libro introduttivo di PHP e leggere i primi capitoli, o leggere la parte del manuale relativa ai Riferimenti del Linguaggio. Potete trovare una lista dei libri di PHP su http://www.php.net/books.php.
Il secondo concetto che abbiamo introdotto era la chiamata alla funzione strstr(). Questa è una funzione sviluppata in PHP che cerca una stringa all'interno di un'altra stringa. In questo caso abbiamo cercato "MSIE" all'interno della stringa $_SERVER["HTTP_USER_AGENT"]. Se la stringa viene trovata, la funzione restituisce TRUE altrimenti, FALSE. Se restituisce TRUE, la dichiarazione if viene valuta come TRUE ed il codice all'interno dei relativi {braces} (sostegni) sarà eseguito. Altrimenti, non esegue altro. Sentitevi liberi di generare esempi simili, con if, else (altrimenti) ed altre funzioni quali strtoupper() e strlen(). Ogni pagina del manuale, relativa a queste funzioni contiene anche degli esempi pratici.
Possiamo fare un passo avanti e mostrarvi come potete entrare ed uscite dal modo PHP anche dall' interno di un blocco PHP:
Invece di usare la dichiarazione echo per fare l'output di qualcosa, saltiamo fuori dal modo PHP inviando soltanto HTML puro. Il punto importante da notare qui è che il flusso logico dello script rimane intatto. Solo uno dei blocchi di di HTML finirà per essere inviato come risposta, dipendendo se strstr() ritorna TRUE o FALSE in altre parole, se la stringa MSIE viene trovata o meno.
Una delle caratteritiche più forti di PHP è il modo in cui gestisce i form. Il concetto da comprendere principalmente è che qualsiasi elemento di un form sarà automaticamente disponibile per i vostri script PHP. Per maggiori informazioni ed esempi relativi all'utilizzo dei form consultate la sezione del manuale che si riferisce a le Variabili al di fuori di PHP. A seguire un esempio di un form HTML:
Questo form non ha niente di speciale. È un semplice form in HTML che non presenta nessun tipo di tags particolari. Quando l'utente riempie questo form e preme il pulsante submit, viene richiamata la pagina action.php. In questo file il risultato sarà qualcosa di simile:
Ciò che avviene dovrebbe risultare ovvio. Non c' è altro da aggiungere. Le variabili $_POST["name"] e $_POST["age"] vengono impostate automaticamente dal PHP. Prima avevamo usato la variabile autoglobal $_SERVER, ora invece abbiamo introdotto la variabile autoglobal $_POST che contiene tutti i dati di tipo POST. Notate che il metodo del nostro form è il POST. Se usassimo il metodo GET le informazioni ricavate dal nostro form si troverebbero invece in $_GET. Si può anche usare la variabile $_REQUEST se la provenienza dei dati richiesti non ci interessa. Questa variabile contiene un misto di dati GET, POST, COOKIE e FILE. Vedere anche la funzione import_request_variables().
Da quando il PHP è divenuto un linguaggio di scripting popolare, esistono più fonti che producono listati di codice che si possono adoperare nei propri scripts. La maggioranza degli sviluppatori del PHP ha cercato di renderlo compatibile con le versioni precedenti, perciò uno script creato per una vecchia versione del PHP dovrebbe girare senza modifiche (in teoria) in una più recente, ma in pratica spesso possono servire delle correzioni.
Ecco due delle più importanti modifiche apportate al vecchio codice:
Il disuso dei vecchi arrays $HTTP_*_VARS (che devono essere dichiarati global quando vengano adoperati all' interno di una funzione o di un metodo). L' introduzione in PHP 4.1.0 dei seguenti autoglobal arrays: $_GET, $_POST, $_COOKIE, $_SERVER, $_ENV, $_REQUEST, and $_SESSION. I vecchi arrays $HTTP_*_VARS quali $HTTP_POST_VARS, invece, continuano ad essere adoperati fin da PHP3.
Le variabili esterne non vengono più registrate nel global scope per default. In altre parole, da PHP 4.2.0 la direttiva PHP register_globals è off per default in php.ini. Il metodo consigliato per accedere a questi valori è quello che fa uso degli arrays autoglobali suddetti. Scripts, libri e tutorials più vecchi devono attenersi a queste direttive. Se, per esempio, qualcuno potesse usare $id dall'URL http://www.example.com/foo.php?id=42. La variabile, $_GET['id'] sarebbe disponibile indifferentemente del fatto che sia on od off.
Con quello che sapete ora dovreste essere in grado di comprendere la maggior parte del manuale ed anche i vari scripts di esempio reperibili nelle raccolte di esempi. Inoltre potete trovarne altri sui siti web di php.net nella sezione links: http://www.php.net/links.php.
Before starting the installation, 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 (e.g. Apache on Linux and MacOS X; 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 or FastCGI processor. This means you set up your server to use the CGI executable of PHP to process all PHP file requests on the server.
If you are also interested to use PHP for command line scripting (e.g. 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 desktop 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. You will also find information on the command line executable in the following sections.
PHP source code and binary distributions for Windows can be found at http://www.php.net/downloads.php. We recommend you to choose a mirror nearest to you for downloading the distributions.
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.
As our manual outlines in the General Installation Considerations section, we are mainly dealing with web centric setups of PHP in this section, although we will cover setting up PHP for command line usage as well.
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. Many Unix like systems have some sort of package installation system. 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.
Prerequisite knowledge and software for compiling:
Basic Unix skills (being able to operate "make" and a C compiler)
An ANSI C compiler
flex: Version 2.5.4
bison: Version 1.28 (preferred), 1.35, or 1.75
A web server
Any module specific components (such as gd, pdf libs, etc.)
The initial PHP setup and configuration process is controlled by the use of the commandline options of the configure script. You could get a list of all available options along with short explanations running ./configure --help. Our manual documents the different options separately. You will find the core options in the appendix, while the different extension specific options are descibed on the reference pages.
When PHP is configured, you are ready to build the module and/or executables. The command make should take care of this. If it fails and you can't figure out why, see the Problems section.
This section contains notes and hints specific to Apache installs of PHP on Unix platforms. We also have instructions and notes for Apache 2 on a separate page.
You can select arguments to add to the configure on line 10 below from the list of core configure options and from extension specific options described at the respective places in the manual. The version numbers have been omitted here, to ensure the instructions are not incorrect. You will need to replace the 'xxx' here with the correct values from your files.
Esempio 4-1. Installation Instructions (Apache Shared Module Version) for PHP
|
Alternatively, to install PHP as a static object:
Esempio 4-2. Installation Instructions (Static Module Installation for Apache) for PHP
|
Nota: Replace php-4 by php-5 and php4 by php5 in PHP 5.
Depending on your Apache install and Unix variant, there are many possible ways to stop and restart the server. Below are some typical lines used in restarting the server, for different apache/unix installations. You should replace /path/to/ with the path to these applications on your systems.
Esempio 4-3. Example commands for restarting Apache
|
The locations of the apachectl and http(s)dctl binaries often vary. If your system has locate or whereis or which commands, these can assist you in finding your server control programs.
Different examples of compiling PHP for apache are as follows:
This will create a libphp4.so shared library that is loaded into Apache using a LoadModule line in Apache's httpd.conf file. The PostgreSQL support is embedded into this libphp4.so library.
This will create a libphp4.so shared library for Apache, but it will also create a pgsql.so shared library that is loaded into PHP either by using the extension directive in php.ini file or by loading it explicitly in a script using the dl() function.
This will create a libmodphp4.a library, a mod_php4.c and some accompanying files and copy this into the src/modules/php4 directory in the Apache source tree. Then you compile Apache using --activate-module=src/modules/php4/libphp4.a and the Apache build system will create libphp4.a and link it statically into the httpd binary (replace php4 by php5 in PHP 5). The PostgreSQL support is included directly into this httpd binary, so the final result here is a single httpd binary that includes all of Apache and all of PHP.
Same as before, except instead of including PostgreSQL support directly into the final httpd you will get a pgsql.so shared library that you can load into PHP from either the php.ini file or directly using dl().
When choosing to build PHP in different ways, you should consider the advantages and drawbacks of each method. Building as a shared object will mean that you can compile apache separately, and don't have to recompile everything as you add to, or change, PHP. Building PHP into apache (static method) means that PHP will load and run faster. For more information, see the Apache webpage on DSO support.
Nota: Apache's default httpd.conf currently ships with a section that looks like this:
Unless you change that to "Group nogroup" or something like that ("Group daemon" is also very common) PHP will not be able to open files.
Nota: Make sure you specify the installed version of apxs when using --with-apxs=/path/to/apxs. You must NOT use the apxs version that is in the apache sources but the one that is actually installed on your system.
This section contains notes and hints specific to Apache 2.0 installs of PHP on Unix systems.
Avvertimento |
We do not recommend using a threaded MPM in production with Apache2. Use the prefork MPM instead, or use Apache1. For information on why, read the following FAQ entry |
You are highly encouraged to take a look at the Apache Documentation to get a basic understanding of the Apache 2.0 Server.
PHP and Apache 2.0.x compatibility notes: The following versions of PHP are known to work with the most recent version of Apache 2.0.x:
These versions of PHP are compatible to Apache 2.0.40 and later.
- PHP 4.3.0 or later available at http://www.php.net/downloads.php.
- the latest stable development version. Get the source code http://snaps.php.net/php4-latest.tar.gz or download binaries for Windows http://snaps.php.net/win32/php4-win32-latest.zip.
- a prerelease version downloadable from http://qa.php.net/.
- you have always the option to obtain PHP through anonymous CVS.
Apache 2.0 SAPI-support started with PHP 4.2.0. PHP 4.2.3 works with Apache 2.0.39, don't use any other version of Apache with PHP 4.2.3. However, the recommended setup is to use PHP 4.3.0 or later with the most recent version of Apache2.
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.
Esempio 4-4. 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: If you want to use content negotiation, read the Apache MultiViews FAQ.
Nota: To build a multithreaded version of Apache your system must support threads. This also implies to build PHP with experimental Zend Thread Safety (ZTS). Therefore not all extensions might be available. The recommended setup is to build Apache with the standard prefork MPM-Module.
PHP 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.
Esempio 4-5. Caudium Installation Instructions
|
You can of course compile your Caudium module with support for the various extensions available in PHP 4. See the reference pages for extension specific configure options.
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.
Nota: Support for fhttpd is no longer available as of PHP 4.3.0.
This section contains notes and hints specific to Sun Java System Web Server, Sun ONE Web Server, iPlanet and Netscape server installs of PHP on Sun Solaris.
From PHP 4.3.3 on you can use PHP scripts with the NSAPI module to generate custom directory listings and error pages. Additional functions for Apache compatibility are also available. For support in current webservers read the note about subrequests.
You can find more information about setting up PHP for the Netscape Enterprise Server (NES) here: http://benoit.noss.free.fr/php/install-php4.html
To build PHP with Sun JSWS/Sun ONE WS/iPlanet/Netscape webservers, 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.
Install the following packages from http://www.sunfreeware.com/ or another download site:
autoconf-2.13 |
automake-1.4 |
bison-1_25-sol26-sparc-local |
flex-2_5_4a-sol26-sparc-local |
gcc-2_95_2-sol26-sparc-local |
gzip-1.2.4-sol26-sparc-local |
m4-1_4-sol26-sparc-local |
make-3_76_1-sol26-sparc-local |
mysql-3.23.24-beta (if you want mysql support) |
perl-5_005_03-sol26-sparc-local |
tar-1.13 (GNU tar) |
Make sure your path includes the proper directories PATH=.:/usr/local/bin:/usr/sbin:/usr/bin:/usr/ccs/bin and make it available to your system export PATH.
gunzip php-x.x.x.tar.gz (if you have a .gz dist, otherwise go to 4).
tar xvf php-x.x.x.tar
Change to your extracted PHP directory: cd ../php-x.x.x
For the following step, make sure /opt/netscape/suitespot/ is where your netscape server is installed. Otherwise, change to the correct path and run:
./configure --with-mysql=/usr/local/mysql \ --with-nsapi=/opt/netscape/suitespot/ \ --enable-libgcc |
Run make followed by make install.
After performing the base install and reading the appropriate readme file, you may need to perform some additional configuration steps.
Configuration Instructions for Sun/iPlanet/Netscape. Firstly you may need to add some paths to the LD_LIBRARY_PATH environment for the server to find all the shared libs. This can best done in the start script for your webserver. 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/.
Add the following line to mime.types (you can do that by the administration server):
type=magnus-internal/x-httpd-php exts=php |
Edit magnus.conf (for servers >= 6) or obj.conf (for servers < 6) and add the following, shlib will vary depending on your system, it will be something like /opt/netscape/suitespot/bin/libphp4.so. You should place the following lines after mime types init.
Init fn="load-modules" funcs="php4_init,php4_execute,php4_auth_trans" shlib="/opt/netscape/suitespot/bin/libphp4.so" Init fn="php4_init" LateInit="yes" errorString="Failed to initialize PHP!" [php_ini="/path/to/php.ini"] |
Configure the default object in obj.conf (for virtual server classes [version 6.0+] in their vserver.obj.conf):
<Object name="default"> . . . .#NOTE this next line should happen after all 'ObjectType' and before all 'AddLog' lines Service fn="php4_execute" type="magnus-internal/x-httpd-php" [inikey=value inikey=value ...] . . </Object> |
This is only needed if you want to configure a directory that only consists of PHP scripts (same like a cgi-bin directory):
<Object name="x-httpd-php"> ObjectType fn="force-type" type="magnus-internal/x-httpd-php" Service fn=php4_execute [inikey=value inikey=value ...] </Object> |
Setup of authentication: PHP authentication cannot be used with any other authentication. ALL AUTHENTICATION IS PASSED TO YOUR PHP SCRIPT. To configure PHP Authentication for the entire server, add the following line to your default object:
<Object name="default"> AuthTrans fn=php4_auth_trans . . . </Object> |
To use PHP Authentication on a single directory, add the following:
<Object ppath="d:\path\to\authenticated\dir\*"> AuthTrans fn=php4_auth_trans </Object> |
Nota: The stacksize that PHP uses depends on the configuration of the webserver. If you get crashes with very large PHP scripts, it is recommended to raise it with the Admin Server (in the section "MAGNUS EDITOR").
Important when writing PHP scripts is the fact that Sun JSWS/Sun ONE WS/iPlanet/Netscape is a multithreaded web server. Because of that all requests are running in the same process space (the space of the webserver itself) and this space has only one environment. If you want to get CGI variables like PATH_INFO, HTTP_HOST etc. it is not the correct way to try this in the old PHP 3.x way with getenv() or a similar way (register globals to environment, $_ENV). You would only get the environment of the running webserver without any valid CGI variables!
Nota: Why are there (invalid) CGI variables in the environment?
Answer: This is because you started the webserver process from the admin server which runs the startup script of the webserver, you wanted to start, as a CGI script (a CGI script inside of the admin server!). This is why the environment of the started webserver has some CGI environment variables in it. You can test this by starting the webserver not from the administration server. Use the command line as root user and start it manually - you will see there are no CGI-like environment variables.
Simply change your scripts to get CGI variables in the correct way for PHP 4.x by using the superglobal $_SERVER. If you have older scripts which use $HTTP_HOST, etc., you should turn on register_globals in php.ini and change the variable order too (important: remove "E" from it, because you do not need the environment here):
variables_order = "GPCS" register_globals = On |
You can use PHP to generate the error pages for "404 Not Found" or similar. Add the following line to the object in obj.conf for every error page you want to overwrite:
Error fn="php4_execute" code=XXX script="/path/to/script.php" [inikey=value inikey=value...] |
Another possibility is to generate self-made directory listings. Just create a PHP script which displays a directory listing and replace the corresponding default Service line for type="magnus-internal/directory" in obj.conf with the following:
Service fn="php4_execute" type="magnus-internal/directory" script="/path/to/script.php" [inikey=value inikey=value...] |
The NSAPI module now supports the nsapi_virtual() function (alias: virtual()) to make subrequests on the webserver and insert the result in the webpage. This function uses some undocumented features from the NSAPI library. On Unix the module automatically looks for the needed functions and uses them if available. If not, nsapi_virtual() is disabled.
Nota: But be warned: Support for nsapi_virtual() is EXPERIMENTAL!!!
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 users to run different PHP-enabled pages under different user-ids.
Avvertimento |
By using the CGI setup, your server is open to several possible attacks. Please read our CGI security section to learn how to defend yourself from those attacks. |
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 modalità sicura 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 modalità sicura. 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 environment variables are not defined in the current CGI/1.1 specification. Only the following variables are defined there: 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. Everything else should be treated as 'vendor extensions'.
This section contains notes and hints specific to installing PHP on HP-UX systems. (Contributed by paul_mckay at clearwater-it dot co dot uk).
Nota: These tips were written for PHP 4.0.4 and Apache 1.3.9.
You need gzip, download a binary distribution from http://hpux.connect.org.uk/ftp/hpux/Gnu/gzip-1.2.4a/gzip-1.2.4a-sd-10.20.depot.Z uncompress the file and install using swinstall.
You need gcc, download a binary distribution from http://gatekeep.cs.utah.edu/ftp/hpux/Gnu/gcc-2.95.2/gcc-2.95.2-sd-10.20.depot.gz. uncompress this file and install gcc using swinstall.
You need the GNU binutils, you can download a binary distribution from http://hpux.connect.org.uk/ftp/hpux/Gnu/binutils-2.9.1/binutils-2.9.1-sd-10.20.depot.gz. uncompress this file and install binutils using swinstall.
You now need bison, you can download a binary distribution from http://hpux.connect.org.uk/ftp/hpux/Gnu/bison-1.28/bison-1.28-sd-10.20.depot.gz, install as above.
You now need flex, you need to download the source from one of the http://www.gnu.org mirrors. It is in the non-gnu directory of the ftp site. Download the file, gunzip, then tar -xvf it. Go into the newly created flex directory and run ./configure, followed by make, and then make install.
If you have errors here, it's probably because gcc etc. are not in your PATH so add them to your PATH.
Download the PHP and apache sources.
gunzip and tar -xvf them. We need to hack a couple of files so that they can compile OK.
Firstly the configure file needs to be hacked because it seems to lose track of the fact that you are a hpux machine, there will be a better way of doing this but a cheap and cheerful hack is to put lt_target=hpux10.20 on line 47286 of the configure script.
Next, the Apache GuessOS file needs to be hacked. Under apache_1.3.9/src/helpers change line 89 from echo "hp${HPUXMACH}-hpux${HPUXVER}"; exit 0 to: echo "hp${HPUXMACH}-hp-hpux${HPUXVER}"; exit 0
You cannot install PHP as a shared object under HP-UX so you must compile it as a static, just follow the instructions at the Apache page.
PHP and Apache should have compiled OK, but Apache won't start. you need to create a new user for Apache, e.g. www, or apache. You then change lines 252 and 253 of the conf/httpd.conf in Apache so that instead of
User nobody Group nogroup |
you have something like
User www Group sys |
This is because you can't run Apache as nobody under hp-ux. Apache and PHP should then work.
This section contains notes and hints specific to installing PHP on OpenBSD 3.6.
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.3.8.tgz, which contains the basic engine (plus gettext and iconv). Next, take a look at the module packages, such as php4-mysql-4.3.8.tgz or php4-imap-4.3.8.tgz. You need to use the phpxs command to activate and deactivate these modules in your php.ini.
Esempio 4-6. 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 PHP 4 port is split into two sub-directories: core and extensions. 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.
The default install of Apache runs inside a chroot(2) jail, which will restrict PHP scripts to accessing files under /var/www. You will therefore need to create a /var/www/tmp directory for PHP session files to be stored, or use an alternative session backend. In addition, database sockets need to be placed inside the jail or listen on the localhost interface. If you use network functions, some files from /etc such as /etc/resolv.conf and /etc/services will need to be moved into /var/www/etc. The OpenBSD PEAR package automatically installs into the correct chroot directories, so no special modification is needed there. More information on the OpenBSD Apache is available in the OpenBSD FAQ.
The OpenBSD 3.6 package for the gd extension requires XFree86 to be installed. If you do not wish to use some of the font features that require X11, install the php4-gd-4.3.8-no_x11.tgz package instead.
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 (avsm at openbsd dot org).
This section contains notes and hints specific to installing PHP on Solaris systems.
Solaris installs often lack C compilers and their related tools. Read this FAQ for information on why using GNU versions for some of these tools is necessary. The required software is as follows:
gcc (recommended, other C compilers may work)
make
flex
bison
m4
autoconf
automake
perl
gzip
tar
GNU sed
You can simplify the Solaris install process by using pkgadd to install most of your needed components.
This section contains notes and hints specific to installing PHP on Gentoo Linux.
While you can just download the PHP source and compile it yourself, using Gentoo's packaging system is the simplest and cleanest method of installing PHP. If you are not familiar with building software on Linux, this is the way to go.
If you have built your Gentoo system so far, you are probably used to Portage already. Installing Apache and PHP is no different than the other system tools.
The first decision you need to make is whether you want to install Apache 1.3.x or Apache 2.x. While both can be used with PHP, the steps given below will use Apache 1.3.x. Another thing to consider is whether your local Portage tree is up to date. If you have not updated it recently, you need to run emerge sync before anything else. This way, you will be using the most recent stable version of Apache and PHP.
Now that everything is in place, you can use the following example to install Apache and PHP:
Esempio 4-7. Gentoo Install Example with Apache 1.3
|
You can read more about emerge in the excellent Portage Manual provided on the Gentoo website.
If you need to use Apache 2, you can simply use emerge apache in the last example.
In the last section, PHP was emerged without any activated modules. As of this writing, the only module activated by default with Portage is XML which is needed by PEAR. This may not be what you want and you will soon discover that you need more activated modules, like MySQL, gettext, GD, etc.
When you compile PHP from source yourself, you need to activate modules via the configure command. With Gentoo, you can simply provide USE flags which will be passed to the configure script automatically. To see which USE flags to use with emerge, you can try:
Esempio 4-8. Getting the list of valid USE flags
|
As you can see from the last output, PHP considers a lot of USE flags. Look at them closely and choose what you need. If you choose a flag and you do not have the proper libraries, Portage will compile them for you. It is a good idea to use emerge -pv again to see what Portage will compile in accordance to your USE flags. As an example, if you do not have X installed and you choose to include X in the USE flags, Portage will compile X prior to PHP, which can take a couple of hours.
If you choose to compile PHP with MySQL, cURL and GD support, the command will look something like this:
As in the last example, do not forget to emerge php as well as mod_php. php is responsible for the command line version of PHP as mod_php is for the Apache module version of PHP.
If you see the PHP source instead of the result the script should produce, you have probably forgot to edit /etc/conf.d/apache. Apache needs to be started with the -D PHP4 flag. To see if the flag is present, you should be able to see it when using ps ax | grep apache while Apache is running.
Due to slotting problems, you might end up with more than one version of PHP installed on your system. If this is the case, you need to unmerge the old versions manually by using emerge unmerge mod_php-<old version>.
If you cannot emerge PHP because of Java, try putting -* in front of your USE flags like in the above examples.
If you are having problems configuring Apache and PHP, you can always search the Gentoo Forums. Try searching with the keywords "Apache PHP".
This section contains notes and hints specific to installing PHP on Debian GNU/Linux.
While you can just download the PHP source and compile it yourself, using Debian's packaging system is the simplest and cleanest method of installing PHP. If you are not familiar with building software on Linux, this is the way to go.
The first decision you need to make is whether you want to install Apache 1.3.x or Apache 2.x. The corresponding PHP packages are respectively named libapache-mod-php* and libapache2-mod-php*. The steps given below will use Apache 1.3.x. Please note that, as of this writing, there is no official Debian packages of PHP 5. Then the steps given below will install PHP 4.
PHP is available in Debian as CGI or CLI flavour too, named respectively php4-cgi and php4-cli. If you need them, you'll just have to reproduce the following steps with the good package names. Another special package you'd want to install is php4-pear. It contains a minimal PEAR installation and the pear commandline utility.
If you need more recent packages of PHP than the Debian's stable ones or if some PHP modules lacks the Debian official repository, perhaps you should take a look at http://www.apt-get.org/. One of the results found should be Dotdeb. This unofficial repository is maintained by Guillaume Plessis and contains Debian packages of the most recent versions of PHP 4 and PHP 5. To use it, just add the to following two lines to your /etc/apt/sources.lists and run apt-get update :
The last thing to consider is whether your list of packages is up to date. If you have not updated it recently, you need to run apt-get update before anything else. This way, you will be using the most recent stable version of the Apache and PHP packages.
Now that everything is in place, you can use the following example to install Apache and PHP:
APT will automatically install the PHP 4 module for Apache 1.3, and all its dependencies and then activate it. If you're not asked to restart Apache during the install process, you'll have to do it manually :
In the last section, PHP was installed with only core modules. This may not be what you want and you will soon discover that you need more activated modules, like MySQL, cURL, GD, etc.
When you compile PHP from source yourself, you need to activate modules via the configure command. With APT, you just have to install additional packages. They're all named 'php4-*' (or 'php5-*' if you installed PHP 5 from a third party repository).
As you can see from the last output, there's a lot of PHP modules that you can install (excluding the php4-cgi, php4-cli or php4-pear special packages). Look at them closely and choose what you need. If you choose a module and you do not have the proper libraries, APT will automatically install all the dependencies for you.
If you choose to add the MySQL, cURL and GD support to PHP the command will look something like this:
APT will automatically add the appropriate lines to your different php.ini (/etc/php4/apache/php.ini, /etc/php4/cgi/php.ini, etc).
You'll only have to stop/start Apache as previously to activate the modules.
If you see the PHP source instead of the result the script should produce, APT has probably not included /etc/apache/conf.d/php4 in your Apache 1.3 configuration. Please ensure that the following line is present in your /etc/apache/httpd.conf file then stop/start Apache:
If you installed an additional module and if its functions are not available in your scripts, please ensure that the appropriate line is present in your php.ini, as seen before. APT may fail during the installation of the additional module, due to a confusing debconf configuration.
This section contains notes and hints specific to installing PHP on Mac OS X. There are two slightly different versions of Mac OS X, Client and Server, our manual deals with installing PHP on both systems. Note that PHP is not available for MacOS 9 and earlier versions.
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.
Get the latest distributions of Apache and PHP.
Untar them, and run the configure program on Apache like so.
./configure --exec-prefix=/usr \ --localstatedir=/var \ --mandir=/usr/share/man \ --libexecdir=/System/Library/Apache/Modules \ --iconsdir=/System/Library/Apache/Icons \ --includedir=/System/Library/Frameworks/Apache.framework/Versions/1.3/Headers \ --enable-shared=max \ --enable-module=most \ --target=apache |
If you want the compiler to do some optimization, you may also want to add this line:
setenv OPTIM=-O2 |
Next, go to the PHP 4 source directory and configure it.
./configure --prefix=/usr \ --sysconfdir=/etc \ --localstatedir=/var \ --mandir=/usr/share/man \ --with-xml \ --with-apache=/src/apache_1.3.12 |
Type make and make install. This will add a directory to your Apache source directory under src/modules/php4.
Now, reconfigure Apache to build in PHP 4.
./configure --exec-prefix=/usr \ --localstatedir=/var \ --mandir=/usr/share/man \ --libexecdir=/System/Library/Apache/Modules \ --iconsdir=/System/Library/Apache/Icons \ --includedir=/System/Library/Frameworks/Apache.framework/Versions/1.3/Headers \ --enable-shared=max \ --enable-module=most \ --target=apache \ --activate-module=src/modules/php4/libphp4.a |
Copy and rename the php.ini-dist file to your bin directory from your PHP 4 source directory: cp php.ini-dist /usr/local/bin/php.ini or (if your don't have a local directory) cp php.ini-dist /usr/bin/php.ini.
The following instructions will help you install a PHP module for the Apache web server included in MacOS X. This version includes support for the MySQL and PostgreSQL databases. These instructions are graciously provided by Marc Liyanage.
Avvertimento |
Be careful when you do this, you could screw up your Apache web server! |
Do this to install:
Open a terminal window.
Type wget http://www.diax.ch/users/liyanage/software/macosx/libphp4.so.gz, wait for the download to finish.
Type gunzip libphp4.so.gz.
Type sudo apxs -i -a -n php4 libphp4.so
Now type sudo open -a TextEdit /etc/httpd/httpd.conf. TextEdit will open with the web server configuration file. Locate these two lines towards the end of the file: (Use the Find command)
#AddType application/x-httpd-php .php #AddType application/x-httpd-php-source .phps |
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 applies to Windows 98/Me and Windows NT/2000/XP/2003. PHP will not work on 16 bit platforms such as Windows 3.1 and sometimes we refer to the supported Windows platforms as Win32. Windows 95 is no longer supported as of PHP 4.3.0.
There are two main ways to install PHP for Windows: either manually or by using the 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.
Avvertimento |
There are several all-in-one installers over the Internet, but none of those are endorsed by PHP.net, as we believe that the manual installation is the best choice to have your system secure and optimised. |
The Windows PHP installer is available from the downloads page at http://www.php.net/downloads.php. This installs the CGI version of PHP and for IIS, PWS, and Xitami, it configures the web server as well. The installer does not include any extra external PHP extensions (php_*.dll) as you'll only find those in the Windows Zip Package and PECL downloads.
Nota: While the Windows installer is an easy way to make PHP work, it is restricted in many aspects as, for example, the automatic setup of extensions is not supported. Use of the installer isn't the preferred method for installing PHP.
First, install your selected HTTP (web) 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 certain web servers to use PHP. One of the web servers the PHP installer does not configure for is Apache, so you'll need to configure it manually.
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.
Avvertimento |
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 with a web server on Microsoft Windows. To get started you'll need to download the zip binary distribution from the downloads page at http://www.php.net/downloads.php.
Although there are many all-in-one installation kits, and we also distribute a PHP installer for Microsoft Windows, we recommend you take the time to setup PHP yourself as this will provide you with a better understanding of the system, and enables you to install PHP extensions easily when needed.
Upgrading from a previous PHP version: Previous editions of the manual suggest moving various ini and DLL files into your SYSTEM (i.e. C:\WINDOWS) folder and while this simplifies the installation procedure it makes upgrading difficult. We advise you remove all of these files (like php.ini and PHP related DLLs from the Windows SYSTEM folder) before moving on with a new PHP installation. Be sure to backup these files as you might break the entire system. The old php.ini might be useful in setting up the new PHP as well. And as you'll soon learn, the preferred method for installing PHP is to keep all PHP related files in one directory and have this directory available to your systems PATH.
MDAC requirements: If you use Microsoft Windows 98/NT4 download the latest version of the Microsoft Data Access Components (MDAC) for your platform. MDAC is available at http://msdn.microsoft.com/data/. This requirement exists because ODBC is built into the distributed Windows binaries.
The following steps should be completed on all installations before any server specific instructions are performed:
Extract the distribution file into a directory of your choice. If you are installing PHP 4, extract to C:\, as the zip file expands to a foldername like php-4.3.7-Win32. If you are installing PHP 5, extract to C:\php as the zip file doesn't expand as in PHP 4. You may choose a different location but do not have spaces in the path (like C:\Program Files\PHP) as some web servers will crash if you do.
The directory structure extracted from the zip is different for PHP versions 4 and 5 and look like as follows:
Esempio 6-1. PHP 4 package structure
|
Or:
Esempio 6-2. PHP 5 package structure
|
Notice the differences and similarities. Both PHP 4 and PHP 5 have a CGI executable, a CLI executable, and server modules, but they are located in different folders and/or have different names. While PHP 4 packages have the server modules in the sapi folder, PHP 5 distributions have no such directory and instead they're in the PHP folder root. The supporting DLLs for the PHP 5 extensions are also not in a seperate directory.
Nota: In PHP 4, you should move all files located in the dll and sapi folders to the main folder (e.g. C:\php).
Here is a list of server modules shipped with PHP 4 and PHP 5:
sapi/php4activescript.dll (php5activescript.dll) - ActiveScript engine, allowing you to embed PHP in your Windows applications.
sapi/php4apache.dll (php5apache.dll) - Apache 1.3.x module.
sapi/php4apache2.dll (php5apache2.dll) - Apache 2.0.x module.
sapi/php4isapi.dll (php5isapi.dll) - ISAPI Module for ISAPI compliant web servers like IIS 4.0/PWS 4.0 or newer.
sapi/php4nsapi.dll (php5nsapi.dll) - Sun/iPlanet/Netscape server module.
sapi/php4pi3web.dll (no equivalent in PHP 5) - Pi3Web server module.
Server modules provide significantly better performance and additional functionality compared to the CGI binary. The CLI version is designed to let you use PHP for command line scripting. More information about CLI is available in the chapter about using PHP from the command line.
Avvertimento |
The SAPI modules have been significantly improved as of the 4.1 release, however, in older systems you may encounter server errors or other server modules failing, such as ASP. |
The CGI and CLI binaries, and the web server modules all require the php4ts.dll (php5ts.dll) file to be available to them. You have to make sure that this file can be found by your PHP installation. The search order for this DLL is as follows:
The same directory from where php.exe is called, or in case you use a SAPI module, the web server's directory (e.g. C:\Program Files\Apache Group\Apache2\bin).
Any directory in your Windows PATH environment variable.
To make php4ts.dll / php5ts.dll available you have three options: copy the file to the Windows system directory, copy the file to the web server's directory, or add your PHP directory, C:\php to the PATH. For better maintenance, we advise you to follow the last option, add C:\php to the PATH, because it will be simpler to upgrade PHP in the future. Read more about how to add your PHP directory to PATH in the corresponding FAQ entry.
The next step is to set up a valid configuration file for PHP, php.ini. There are two ini files distributed in the zip file, php.ini-dist and php.ini-recommended. We advise you to use php.ini-recommended, because we optimized the default settings in this file for performance, and security. Read this well documented file carefully because it has changes from php.ini-dist that will drastically affect your setup. Some examples are display_errors being off and magic_quotes_gpc being off. In addition to reading these, study 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. Copy your chosen ini-file to a directory that PHP is able to find and rename it to php.ini. PHP searches for php.ini in the locations described in la Sezione The configuration file nel Capitolo 9 section.
If you are running Apache 2, the simpler option is to use the PHPIniDir directive (read the installation on Apache 2 page), otherwise your best option is to set the PHPRC environment variable. This process is explained in the following FAQ entry.
Nota: If you're using NTFS on Windows NT, 2000, XP or 2003, make sure that the user running the web server has read permissions to your php.ini (e.g. make it readable by Everyone).
The following steps are optional:
Edit your new php.ini file. If you plan to use OmniHTTPd, do not follow the next step. Set the doc_root to point to your web servers document_root. For example:
Choose the 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 configuration setting 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. For an up-to-date browscap.ini, read the following FAQ.
PHP is now setup on your system. The next step is to choose a web server, and enable it to run PHP. Choose a webserver from the table of contents.
This section contains notes specific to the ActiveScript installation.
ActiveScript is a windows only SAPI that enables you to use PHP script in any ActiveScript compliant host, like Windows Script Host, ASP/ASP.NET, Windows Script Components or Microsoft Scriptlet control.
As of PHP 5.0.1, ActiveScript has been moved to the PECL repository. You may download this PECL extension DLL from the PHP Downloads page or at http://snaps.php.net/.
Nota: You should read the manual installation steps first!
After installing PHP, you should download the ActiveScript DLL (php5activescript.dll) and place it in the main PHP folder (e.g. C:\php).
After having all the files needed, you must register the DLL on your system. To achieve this, open a Command Prompt window (located in the Start Menu). Then go to your PHP directory by typing something like cd C:\php. To register the DLL just type regsvr32 php5activescript.dll.
To test if ActiveScript is working, create a new file, named test.wsf (the extension is very important) and type:
<job id="test"> <script language="PHPScript"> $WScript->Echo("Hello World!"); </script> </job> |
Nota: In PHP 4, the engine was named 'ActivePHP', so if you are using PHP 4, you should replace 'PHPScript' with 'ActivePHP' in the above example.
Nota: ActiveScript doesn't use the default php.ini file. Instead, it will look only in the same directory as the .exe that caused it to load. You should create php-activescript.ini and place it in that folder, if you wish to load extensions, etc.
This section contains notes and hints specific to IIS (Microsoft Internet Information Server).
Avvertimento |
By using the CGI setup, your server is open to several possible attacks. Please read our CGI security section to learn how to defend yourself from those attacks. |
First, read the Manual Installation Instructions. Do not skip this step as it provides crucial information for installing PHP on Windows.
CGI users must set the cgi.force_redirect PHP directive to 0 inside php.ini. Read the faq on cgi.force_redirect for important details. Also, CGI users may want to set the cgi.redirect_status_env directive. When using directives, be sure these directives aren't commented out inside php.ini.
The PHP 4 CGI is named php.exe while in PHP 5 it's php-cgi.exe. In PHP 5, php.exe is the CLI, and not the CGI.
Modify the Windows PATH environment variable to include the PHP directory. This way the PHP DLL files, PHP executables, and php.ini can all remain in the PHP directory without cluttering up the Windows system directory. For more details, see the FAQ on Setting the PATH.
The IIS user (usually IUSR_MACHINENAME) needs permission to read various files and directories, such as php.ini, docroot, and the session tmp directory.
Be sure the extension_dir and doc_root PHP directives are appropriately set in php.ini. These directives depend on the system that PHP is being installed on. In PHP 4, the extension_dir is extensions while with PHP 5 it's ext. So, an example PHP 5 extensions_dir value is "c:\php\ext" and an example IIS doc_root value is "c:\Inetpub\wwwroot".
PHP extension DLL files, such as php_mysql.dll and php_curl.dll, are found in the zip package of the PHP download (not the PHP installer). In PHP 5, many extensions are part of PECL and can be downloaded in the "Collection of PECL modules" package. Files such as php_zip.dll and php_ssh2.dll. Download PHP files here.
When defining the executable, the 'check that file exists' box may also be checked. For a small performance penalty, the IIS (or PWS) will check that the script file exists and sort out authentication before firing up PHP. This means that the web server will provide sensible 404 style error messages instead of CGI errors complaining that PHP did not output any data.
PHP may be installed as a CGI binary, 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', do the following:
Change the Execute Permissions to 'Scripts only'
Click on the 'Configuration' button, and choose the Application Mappings tab. Click Add and set the Executable path to the appropriate CGI file. An example PHP 5 value is: C:\php\php-cgi.exe Supply .php as the extension. Leave 'Method exclusions' blank, and check the 'Script engine' checkbox. Now, click OK a few times.
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 / php-cgi.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 / php5isapi.dll.
Under 'Home Directory', 'Virtual Directory', or 'Directory', do the following:
Change the Execute Permissions to 'Scripts only'
Click on the 'Configuration' button, and choose the Application Mappings tab. Click Add and set the Executable path to the appropriate ISAPI DLL. An example PHP 5 value is: C:\php\php5isapi.dll Supply .php as the extension. Leave 'Method exclusions' blank, and check the 'Script engine' checkbox. Now, click OK a few times.
Stop IIS completely (NET STOP iisadmin)
Start IIS again (NET START w3svc)
With IIS 6 (2003 Server), open up the IIS Manager, go to Web Service Extensions, choose "Add a new Web service extension", enter in a name such as PHP, choose the Add button and for the value browse to either the ISAPI file (php4isapi.dll or php5isapi.dll) or CGI (php.exe or php-cgi.exe) then check "Set extension status to Allowed" and click OK.
In order to use index.php as a default content page, do the following: From within the Documents tab, choose Add. Type in index.php and click OK. Adjust the order by choosing Move Up or Move Down. This is similar to setting DirectoryIndex with Apache.
The steps above must be repeated for each extension that is to be associated with PHP scripts. .php is the most common although .php3 may be required for legacy applications.
If you experience 100% CPU usage after some time, turn off the IIS setting Cache ISAPI Application.
PWS 4 does not support ISAPI, only PHP CGI should be used.
Edit the enclosed pws-php4cgi.reg / pws-php5cgi.reg file (look into the SAPI folder for PHP 4, or in the main folder for PHP 5) to reflect the location of your php.exe / php-cgi.exe. Backslashes should be escaped, for example: [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\w3svc\parameters\Script Map] ".php"="C:\\php\\php.exe" (change to C:\\php\\php-cgi.exe if you are using PHP 5) 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.
The recommended method for configuring these servers is to use the REG file included with the distribution (pws-php4cgi.reg in the SAPI folder for PHP 4, or pws-php5cgi.reg in the main folder for PHP 5). 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.
Avvertimento |
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 "%s" %s for PHP 4, or C:\php\php-cgi.exe "%s" %s for PHP 5.
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.
This section contains notes and hints specific to Apache 1.3.x installs of PHP on Microsoft Windows systems. There are also instructions and notes for Apache 2 on a separate page.
Nota: Please read the manual installation steps first!
There are two ways to set up PHP to work with Apache 1.3.x on Windows. One is to use the CGI binary (php.exe for PHP 4 and php-cgi.exe for PHP 5), the other is to use the Apache Module DLL. In either case you need to edit your httpd.conf to configure Apache to work with PHP, and then restart the server.
It is worth noting here that now the SAPI module has been made more stable under Windows, we recommend it's use above the CGI binary, since it is more transparent and secure.
Although there can be a few variations of configuring PHP under Apache, these are simple enough to be used by the newcomer. Please consult the Apache Documentation for further configuration directives.
After changing the configuration file, remember to restart the server, for example, NET STOP APACHE followed by NET START APACHE, if you run Apache as a Windows Service, or use your regular shortcuts.
Nota: Remember that when adding path values in the Apache configuration files on Windows, all backslashes such as c:\directory\file.ext must be converted to forward slashes, as c:/directory/file.ext.
You should add the following lines to your Apache httpd.conf file:
Esempio 6-3. PHP as an Apache 1.3.x module This assumes PHP is installed to c:\php. Adjust the path if this is not the case. For PHP 4:
For PHP 5:
For both:
|
If you unzipped the PHP package to C:\php\ as described in the Manual Installation Steps section, you need to insert these lines to your Apache configuration file to set up the CGI binary:
Avvertimento |
By using the CGI setup, your server is open to several possible attacks. Please read our CGI security section to learn how to defend yourself from those attacks. |
If you would like to present PHP source files syntax highlighted, there is no such convenient option as with the module version of PHP. If you chose to configure Apache to use PHP as a CGI binary, you will need to use the highlight_file() function. To do this simply create a PHP script file and add this code: <?php highlight_file('some_php_script.php'); ?>.
This section contains notes and hints specific to Apache 2.0.x installs of PHP on Microsoft Windows systems. We also have instructions and notes for Apache 1.3.x users on a separate page.
Nota: You should read the manual installation steps first!
Avvertimento |
We do not recommend using a threaded MPM in production with Apache2. Use the prefork MPM instead, or use Apache1. For information on why, read the following FAQ entry |
You are highly encouraged to take a look at the Apache Documentation to get a basic understanding of the Apache 2.0.x Server. Also consider to read the Windows specific notes for Apache 2.0.x before reading on here.
PHP and Apache 2.0.x compatibility notes: The following versions of PHP are known to work with the most recent version of Apache 2.0.x:
These versions of PHP are compatible to Apache 2.0.40 and later.
- PHP 4.3.0 or later available at http://www.php.net/downloads.php.
- the latest stable development version. Get the source code http://snaps.php.net/php4-latest.tar.gz or download binaries for Windows http://snaps.php.net/win32/php4-win32-latest.zip.
- a prerelease version downloadable from http://qa.php.net/.
- you have always the option to obtain PHP through anonymous CVS.
Apache 2.0 SAPI-support started with PHP 4.2.0. PHP 4.2.3 works with Apache 2.0.39, don't use any other version of Apache with PHP 4.2.3. However, the recommended setup is to use PHP 4.3.0 or later with the most recent version of Apache2.
All mentioned versions of PHP will work still with Apache 1.3.x.
Avvertimento |
Apache 2.0.x 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.x is not expected to work on those platforms at this time. |
Download the most recent version of Apache 2.0.x and a fitting PHP version. 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.x on Windows. One is to use the CGI binary the other is to use the Apache module DLL. In either case you need to edit your httpd.conf to configure Apache to work with PHP and then restart the server.
Nota: Remember that when adding path values in the Apache configuration files on Windows, all backslashes such as c:\directory\file.ext must be converted to forward slashes, as c:/directory/file.ext.
You need to insert these three lines to your Apache httpd.conf configuration file to set up the CGI binary:
Avvertimento |
By using the CGI setup, your server is open to several possible attacks. Please read our CGI security section to learn how to defend yourself from those attacks. |
You need to insert these two lines to your Apache httpd.conf configuration file to set up the PHP module for Apache 2.0:
Esempio 6-6. PHP and Apache 2.0 as Module
|
Nota: Remember to substitute your actual path to PHP for the c:/php/ in the above examples. Take care to use either php4apache2.dll or php5apache2.dll in your LoadModule directive and not php4apache.dll or php5apache.dll as the latter ones are designed to run with Apache 1.3.x.
Nota: If you want to use content negotiation, read related FAQ.
Avvertimento |
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. |
This section contains notes and hints specific to Sun Java System Web Server, Sun ONE Web Server, iPlanet and Netscape server installs of PHP on Windows.
From PHP 4.3.3 on you can use PHP scripts with the NSAPI module to generate custom directory listings and error pages. Additional functions for Apache compatibility are also available. For support in current webservers read the note about subrequests.
To install PHP as a CGI handler, 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 with NSAPI, 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).
Edit magnus.conf (for servers >= 6) or obj.conf (for servers < 6) and add the following: You should place the lines after mime types init.
Init fn="load-modules" funcs="php4_init,php4_execute,php4_auth_trans" shlib="c:/php/sapi/php4nsapi.dll" Init fn="php4_init" LateInit="yes" errorString="Failed to initialise PHP!" [php_ini="c:/path/to/php.ini"] |
Configure the default object in obj.conf (for virtual server classes [Sun Web Server 6.0+] in their vserver.obj.conf): 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" [inikey=value inikey=value ...] |
This is only needed if you want to configure a directory that only consists of PHP scripts (same like a cgi-bin directory):
<Object name="x-httpd-php"> ObjectType fn="force-type" type="magnus-internal/x-httpd-php" Service fn=php4_execute [inikey=value inikey=value ...] </Object> |
Restart your web service and apply changes
Do it for each web server instance you want PHP to run
Nota: More details about setting up PHP as an NSAPI filter can be found here: http://benoit.noss.free.fr/php/install-php4.html
Nota: The stacksize that PHP uses depends on the configuration of the webserver. If you get crashes with very large PHP scripts, it is recommended to raise it with the Admin Server (in the section "MAGNUS EDITOR").
Important when writing PHP scripts is the fact that Sun JSWS/Sun ONE WS/iPlanet/Netscape is a multithreaded web server. Because of that all requests are running in the same process space (the space of the webserver itself) and this space has only one environment. If you want to get CGI variables like PATH_INFO, HTTP_HOST etc. it is not the correct way to try this in the old PHP 3.x way with getenv() or a similar way (register globals to environment, $_ENV). You would only get the environment of the running webserver without any valid CGI variables!
Nota: Why are there (invalid) CGI variables in the environment?
Answer: This is because you started the webserver process from the admin server which runs the startup script of the webserver, you wanted to start, as a CGI script (a CGI script inside of the admin server!). This is why the environment of the started webserver has some CGI environment variables in it. You can test this by starting the webserver not from the administration server. Use the command line as root user and start it manually - you will see there are no CGI-like environment variables.
Simply change your scripts to get CGI variables in the correct way for PHP 4.x by using the superglobal $_SERVER. If you have older scripts which use $HTTP_HOST, etc., you should turn on register_globals in php.ini and change the variable order too (important: remove "E" from it, because you do not need the environment here):
variables_order = "GPCS" register_globals = On |
You can use PHP to generate the error pages for "404 Not Found" or similar. Add the following line to the object in obj.conf for every error page you want to overwrite:
Error fn="php4_execute" code=XXX script="/path/to/script.php" [inikey=value inikey=value...] |
Another possibility is to generate self-made directory listings. Just create a PHP script which displays a directory listing and replace the corresponding default Service line for type="magnus-internal/directory" in obj.conf with the following:
Service fn="php4_execute" type="magnus-internal/directory" script="/path/to/script.php" [inikey=value inikey=value...] |
The NSAPI module now supports the nsapi_virtual() function (alias: virtual()) to make subrequests on the webserver and insert the result in the webpage. The problem is, that this function uses some undocumented features from the NSAPI library.
Under Unix this is not a problem, because the module automatically looks for the needed functions and uses them if available. If not, nsapi_virtual() is disabled.
Under Windows limitations in the DLL handling need the use of a automatic detection of the most recent ns-httpdXX.dll file. This is tested for servers till version 6.1. If a newer version of the Sun server is used, the detection fails and nsapi_virtual() is disabled.
If this is the case, try the following: Add the following parameter to php4_init in magnus.conf/obj.conf:
Init fn=php4_init ... server_lib="ns-httpdXX.dll" |
You can check the status by using the phpinfo() function.
Nota: But be warned: Support for nsapi_virtual() is EXPERIMENTAL!!!
This section contains notes and hints specific to OmniHTTPd on Windows.
Nota: You should read the manual installation steps first!
Avvertimento |
By using the CGI setup, your server is open to several possible attacks. Please read our CGI security section to learn how to defend yourself from those attacks. |
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.
Install OmniHTTPd server.
Right click on the blue OmniHTTPd icon in the system tray and select Properties
Click on Web Server Global Settings
On the 'External' tab, enter: virtual = .php | actual = c:\php\php.exe (use php-cgi.exe if installing PHP 5), and use the Add button.
On the Mime tab, enter: virtual = wwwserver/stdcgi | actual = .php, and use the Add button.
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 the Sambar Server for Windows.
Nota: You should read the manual installation steps first!
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 install directory.
Open mappings.ini and add the following line under [ISAPI]:
Now restart the Sambar server for the changes to take effect.
This section contains notes and hints specific to Xitami on Windows.
Nota: You should read the manual installation steps first!
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. If you want to use $_SERVER['PHP_SELF'] you have to enable the cgi.fix_pathinfo directive.
Avvertimento |
By using the CGI setup, your server is open to several possible attacks. Please read our CGI security section to learn how to defend yourself from those attacks. |
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 CGI executable i.e. C:\php\php.exe for PHP 4, or C:\php\php-cgi.exe for PHP 5.
Press the 'Save' icon.
Restart the server to reflect changes.
This chapter teaches how to compile PHP from sources on windows, using Microsoft's tools. To compile PHP with cygwin, please refer to Capitolo 4.
To compile and build PHP you need a Microsoft Development Environment. Microsoft Visual C++ 6.0 is recommended, although .NET versions (either the free Microsoft Visual C++ Toolkit or the commercial Microsoft Visual C++ .NET) will also work. To extract the downloaded files you will also need a ZIP extraction utility. Windows XP and newer already include this functionality built-in.
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 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).
Build the libraries you are going to need (or download the binaries if available) and place the headers and libs in the C:\work\win32build\include and C:\work\win32build\lib directories, respectively.
+--C:\work | | | +--bindlib_w32 | | | | | +--arpa | | | | | +--conf | | | | | +--... | | | +--php-5.x.x | | | | | +--build | | | | | +--... | | | | | +--win32 | | | | | +--... | | | +--win32build | | | | | +--bin | | | | | +--include | | | | | +--lib |
If you aren't using Cygwin, you must also create the directories C:\usr\local\lib and then copy bison.simple from C:\work\win32build\bin to C:\usr\local\lib.
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 documentation at the PEAR website.
You must build the resolv.lib library. Decide whether you want to have debug symbols available (bindlib - Win32 Debug) or not (bindlib - Win32 Release), but please remember the choice you made, because you'll have to build PHP in the same way, or you may get linking errors. Build the appropriate configuration:
For GUI users, launch VC++, by double-clicking in C:\work\bindlib_w32\bindlib.dsw. Then 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"
This chapter explains how to compile PHP >=5 using the new build system, which is CLI-based and very similar with the main PHP's Unix build system.
Nota: This build system isn't available in PHP 4. Please refer to la Sezione Building PHP using DSW files [PHP 4] instead.
Before starting, be sure you have read la Sezione Putting it all together and you have built all needed libraries, like Libxml or ICU (needed for PHP >= 6).
First you should open a Visual Studio Command Prompt, which should be available under the Start menu. A regular Command Prompt window shouldn't work, as probably it doesn't have the necessary environment variables set. Then type something like cd C:\work\php-5.x.x to enter in the PHP source dir. Now you are ready to start configuring PHP.
The second step is running the buildconf batch file to make the configure script, by scanning the folder for config.w32 files. By default this command will also search in the following directories: pecl; ..\pecl; pecl\rpc; ..\pecl\rpc. Since PHP 5.1.0, you can change this behaviour by using the --add-modules-dir argument (e.g. cscript /nologo win32/build/buildconf.js --add-modules-dir=../php-gtk2 --add-modules-dir=../pecl).
The third step is configuring. To view the list of the available configuration options type cscript /nologo configure.js --help. After choosing the options that you will enable/disable, type something like: cscript /nologo configure.js --disable-foo --enable-fun-ext. Using --enable-foo=shared will attempt to build the 'foo' extension as a shared, dynamically loadable module.
The last step is compilling. To achieve this just issue the command nmake. The generated files (e.g. .exe and .dll) will be placed in either Release_TS or Debug_TS directories (if built with Thread safety), or in the Release or Debug directories otherwise.
Optionally you may also run PHP's test suite, by typing nmake test. If you want to run just a specific test, you may use the 'TESTS' variable (e.g. nmake /D TESTS=ext/sqlite/tests test - will only run sqlite's tests). To delete the files that were created during the compilation, you can use the nmake clean command.
A very usefull configure option to build snapshots is --enable-snapshot-build, which add a new compiling mode (nmake build-snap). This tries to build every extension available (as shared, by default), but it will ignore build errors in individual extensions or SAPI.
Compiling PHP using the DSW files isn't supported as of PHP 5, as a much more flexible system was made available. Anyway, you can still use them, but keep in mind that they are not maintained very often, so you can have compiling problems. To compile PHP 4 for windows, this is the only available way though.
The first 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: C:\cygwin\bin
Include files: C:\work\win32build\include
Library files: C:\work\win32build\lib
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 file. For example you can change the default location of php.ini, the built-in extensions, and the default location for your extensions.
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 successful compiling run you will find the php.exe in either the directory Release_TS\cli\ or Debug_TS\cli\.
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. You can choose which extensions you would like to load when PHP starts by modifying your php.ini. You can also load a module dynamically in your script using dl().
The DLLs for PHP extensions are prefixed with php_.
Many extensions are built into the Windows version of PHP. This means additional DLL files, and the extension directive, are not used to load these extensions. The Windows PHP Extensions table lists extensions that require, or used to require, additional PHP DLL files. Here's a list of built in extensions:
In PHP 4 (updated PHP 4.3.11): BCMath, Caledar, COM, Ctype, FTP, MySQL, ODBC, Overload, PCRE, Session, Tokenizer, WDDX, XML e Zlib
In PHP 5 (updated PHP 5.0.4), the following changes exist. Built in: DOM, LibXML, Iconv, SimpleXML, SPL e SQLite. And the following are no longer built in: MySQL and Overload.
The default location PHP searches for extensions is C:\php4\extensions in PHP 4 and C:\php5 in PHP 5. To change this setting to reflect your setup of PHP edit your php.ini file:
You will need to change the extension_dir setting to point to the directory where your extensions lives, or where you have placed your php_*.dll files. For example:
Enable the extension(s) in php.ini you want to use by uncommenting the extension=php_*.dll lines in php.ini. This is done by deleting the leading ; from the extension you want to load.
Esempio 6-8. Enable Bzip2 extension for PHP-Windows
|
Some of the extensions need extra DLLs to work. Couple of them can be found in the distribution package, in the C:\php\dlls\ folder in PHP 4 or in the main folder in PHP 5, but some, for example Oracle (php_oci8.dll) require DLLs which are not bundled with the distribution package. If you are installing PHP 4, copy the bundled DLLs from C:\php\dlls folder to the main C:\php folder. Don't forget to include C:\php in the system PATH (this process is explained in a separate FAQ entry).
Some of these DLLs are not bundled with the PHP distribution. See each extensions documentation page for details. Also, read the manual section titled Installation of PECL extensions for details on PECL. An increasingly large number of PHP extensions are found in PECL, and these extensions require a separate download.
Nota: If you are running a server module version of PHP remember to restart your webserver to reflect your changes to php.ini.
The following table describes some of the extensions available and required additional dlls.
Tabella 6-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 |
php_ctype.dll | ctype family functions | Built in since PHP 4.3.0 |
php_curl.dll | CURL, Client URL library functions | Requires: libeay32.dll, ssleay32.dll (bundled) |
php_cybercash.dll | Cybercash payment functions | PHP <= 4.2.0 |
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 |
php_dbx.dll | dbx functions | |
php_domxml.dll | DOM XML functions | PHP <= 4.2.0 requires: libxml2.dll (bundled) PHP >= 4.3.0 requires: iconv.dll (bundled) |
php_dotnet.dll | .NET functions | PHP <= 4.1.1 |
php_exif.dll | EXIF functions | php_mbstring.dll. And, php_exif.dll must be loaded after php_mbstring.dll in php.ini. |
php_fbsql.dll | FrontBase functions | PHP <= 4.2.0 |
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 | Removed in PHP 4.3.2. Also note that truecolor functions are not available in GD1, instead, use php_gd2.dll. |
php_gd2.dll | GD library image functions | GD2 |
php_gettext.dll | Gettext functions | PHP <= 4.2.0 requires gnu_gettext.dll (bundled), PHP >= 4.2.3 requires libintl-1.dll, iconv.dll (bundled). |
php_hyperwave.dll | HyperWave functions | None |
php_iconv.dll | ICONV characterset conversion | Requires: iconv-1.3.dll (bundled), PHP >=4.2.1 iconv.dll |
php_ifx.dll | Informix functions | Requires: Informix libraries |
php_iisfunc.dll | IIS management functions | None |
php_imap.dll | IMAP POP3 and NNTP functions | None |
php_ingres.dll | Ingres II functions | Requires: Ingres II libraries |
php_interbase.dll | InterBase functions | Requires: gds32.dll (bundled) |
php_java.dll | Java functions | PHP <= 4.0.6 requires: jvm.dll (bundled) |
php_ldap.dll | LDAP functions | PHP <= 4.2.0 requires libsasl.dll (bundled), PHP >= 4.3.0 requires libeay32.dll, ssleay32.dll (bundled) |
php_mbstring.dll | Multi-Byte String functions | None |
php_mcrypt.dll | Mcrypt Encryption functions | Requires: libmcrypt.dll |
php_mhash.dll | Mhash functions | PHP >= 4.3.0 requires: libmhash.dll (bundled) |
php_mime_magic.dll | Mimetype functions | Requires: magic.mime (bundled) |
php_ming.dll | Ming functions for Flash | None |
php_msql.dll | mSQL functions | Requires: msql.dll (bundled) |
php_mssql.dll | MSSQL functions | Requires: ntwdblib.dll (bundled) |
php_mysql.dll | MySQL functions | PHP >= 5.0.0, requires libmysql.dll (bundled) |
php_mysqli.dll | MySQLi functions | PHP >= 5.0.0, requires libmysql.dll (libmysqli.dll in PHP <= 5.0.2) (bundled) |
php_oci8.dll | Oracle 8 functions | Requires: Oracle 8.1+ client libraries |
php_openssl.dll | OpenSSL functions | Requires: libeay32.dll (bundled) |
php_oracle.dll | Oracle functions | Requires: Oracle 7 client libraries |
php_overload.dll | Object overloading functions | Built in since PHP 4.3.0 |
php_pdf.dll | PDF functions | None |
php_pgsql.dll | PostgreSQL functions | None |
php_printer.dll | Printer functions | None |
php_shmop.dll | Shared Memory functions | None |
php_snmp.dll | SNMP get and walk functions | NT only! |
php_soap.dll | SOAP functions | PHP >= 5.0.0 |
php_sockets.dll | Socket functions | None |
php_sybase_ct.dll | Sybase functions | Requires: Sybase client libraries |
php_tidy.dll | Tidy functions | PHP >= 5.0.0 |
php_tokenizer.dll | Tokenizer functions | Built in since PHP 4.3.0 |
php_w32api.dll | W32api functions | None |
php_xmlrpc.dll | XML-RPC functions | PHP >= 4.2.1 requires: iconv.dll (bundled) |
php_xslt.dll | XSLT functions | PHP <= 4.2.0 requires sablot.dll, expat.dll (bundled). PHP >= 4.2.1 requires sablot.dll, expat.dll, iconv.dll (bundled). |
php_yaz.dll | YAZ functions | Requires: yaz.dll (bundled) |
php_zip.dll | Zip File functions | Read only access |
php_zlib.dll | ZLib compression functions | Built in since PHP 4.3.0 |
PECL is a repository of PHP extensions that are made available to you via the PEAR packaging system. This section of the manual is intended to demonstrate how to obtain and install PECL extensions.
These instructions assume /your/phpsrcdir/ is the path to the PHP source distribution, and that extname is the name of the PECL extension. Adjust accordingly. These instructions also assume a familiarity with the pear command.
To be useful, a shared extension must be built, installed, and loaded. The methods described below provide you with various instructions on how to build and install the extensions, but they do not automatically load them. Extensions can be loaded by adding an extension directive. To this php.ini file, or through the use of the dl() function.
When building PHP modules, it's important to have known-good versions of the required tools (autoconf, automake, libtool, etc.) See the Anonymous CVS Instructions for details on the required tools, and required versions.
There are several options for downloading PECL extensions, such as:
The PECL web site contains information about the different extensions that are offered by the PHP Development Team. The information available here includes: ChangeLog, release notes, requirements and other similar details.
pear download extname
PECL extensions that have releases listed on the PECL web site are available for download and installation using the pear command. Specific revisions may also be specified.
CVS
Most PECL extensions also reside in CVS. A web-based view may be seen at http://cvs.php.net/pecl/. To download straight from CVS, the following sequence of commands may be used. Note that phpfi is the password for user cvsread:
$ cvs -d:pserver:cvsread@cvs.php.net:/repository login $ cvs -d:pserver:cvsread@cvs.php.net:/repository co pecl/extname |
Windows downloads
Windows users may find compiled PECL binaries by downloading the Collection of PECL modules from the PHP Downloads page, and by retrieving a PECL Snapshot. To compile PHP under Windows, read the Win32 Build README.
As with any other PHP extension DLL, installation is as simple as copying the PECL extension DLLs into the extension_dir folder and loading them from php.ini. For example, add the following line to your php.ini:
extension=php_extname.dll |
After doing this, restart the web server.
PEAR makes it easy to create shared PHP extensions. Using the pear command, do the following:
$ pear install extname |
This will download the source for extname, compile, and install extname.so into your extension_dir. extname.so may then be loaded via php.ini
By default, the pear command will not install packages that are marked with the alpha or beta state. If no stable packages are available, you may install a beta package using the following command:
$ pear install extname-beta |
You may also install a specific version using this variant:
$ pear install extname-0.1 |
Sometimes, using the pear installer is not an option. This could be because you're behind a firewall, or it could be because the extension you want to install is not available as a PEAR compatible package, such as unreleased extensions from CVS. If you need to build such an extension, you can use the lower-level build tools to perform the build manually.
The phpize command is used to prepare the build environment for a PHP extension. In the following sample, the sources for an extension are in a directory named extname:
$ cd extname $ phpize $ ./configure $ make # make install |
A successful install will have created extname.so and put it into the PHP extensions directory. You'll need to and adjust php.ini and add an extension=extname.so line before you can use the extension.
You might find that you need to build a PECL extension statically into your PHP binary. To do this, you'll need to place the extension source under the php-src/ext/ directory and tell the PHP build system to regenerate its configure script.
$ cd /your/phpsrcdir/ext $ pear download extname $ gzip -d < extname.tgz | tar -xvf - $ mv extname-x.x.x extname |
This will result in the following directory:
/your/phpsrcdir/ext/extname |
From here, force PHP to rebuild the configure script, and then build PHP as normal:
$ cd /your/phpsrcdir $ rm configure $ ./buildconf --force $ ./configure --help $ ./configure --with-extname --enable-someotherext --with-foobar $ make $ make install |
Nota: To run the 'buildconf' script you need autoconf 2.13 and automake 1.4+ (newer versions of autoconf may work, but are not supported).
Whether --enable-extname or --with-extname is used depends on the extension. Typically an extension that does not require external libraries uses --enable. To be sure, run the following after buildconf:
$ ./configure --help | grep extname |
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/support.php. 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, modalità sicura, 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!
The configuration file (called php3.ini in PHP 3, and simply php.ini as of PHP 4) is read when PHP starts up. For the server module versions of PHP, this happens only once when the web server is started. For the CGI and CLI version, it happens on every invocation.
php.ini is searched in these locations (in order):
SAPI module specific location (PHPIniDir directive in Apache 2, -c command line option in CGI and CLI, php_ini parameter in NSAPI, PHP_INI_PATH environment variable in THTTPD)
HKEY_LOCAL_MACHINE\SOFTWARE\PHP\IniFilePath (Windows Registry location)
The PHPRC environment variable
Current working directory (for CLI)
The web server's directory (for SAPI modules), or directory of PHP (otherwise in Windows)
Windows directory (C:\windows or C:\winnt) (for Windows), or --with-config-file-path compile time option
If php-SAPI.ini exists (where SAPI is used SAPI, so the filename is e.g. php-cli.ini or php-apache.ini), it's used instead of php.ini. SAPI name can be determined by php_sapi_name().
Nota: The Apache web server changes the directory to root at startup causing PHP to attempt to read php.ini from the root filesystem if it exists.
The php.ini directives handled by extensions are documented respectively on the pages of the extensions themselves. The list of the core directives is available in the appendix. Probably not all PHP directives are documented in the manual though. For a complete list of directives available in your PHP version, please read your well commented php.ini file. Alternatively, you may find the the latest php.ini from CVS helpful too.
Esempio 9-1. php.ini example
|
Since PHP 5.1.0, it is possible to refer to existing .ini variables from within .ini files. Example: open_basedir = ${open_basedir} ":/new/dir".
When using PHP as an Apache module, you can also change the configuration settings using directives in Apache configuration files (e.g. httpd.conf) and .htaccess files. You will need "AllowOverride Options" or "AllowOverride All" privileges to do so.
With PHP 4 and PHP 5, there are several Apache directives that allow you to change the PHP configuration from within the Apache configuration files. For a listing of which directives are PHP_INI_ALL, PHP_INI_PERDIR, or PHP_INI_SYSTEM, have a look at the List of php.ini directives appendix.
Nota: With PHP 3, there are Apache directives that correspond to each configuration setting in the php3.ini name, except the name is prefixed by "php3_".
Sets the value of the specified directive. Can be used only with PHP_INI_ALL and PHP_INI_PERDIR type directives. To clear a previously set value use none as the value.
Nota: Don't use php_value to set boolean values. php_flag (see below) should be used instead.
Used to set a boolean configuration directive. Can be used only with PHP_INI_ALL and PHP_INI_PERDIR type directives.
Sets the value of the specified directive. This can not be used in .htaccess files. Any directive type set with php_admin_value can not be overridden by .htaccess or virtualhost directives. To clear a previously set value use none as the value.
Used to set a boolean configuration directive. This can not be used in .htaccess files. Any directive type set with php_admin_flag can not be overridden by .htaccess or virtualhost directives.
Esempio 9-2. Apache configuration example
|
Attenzione |
PHP constants do not exist outside of PHP. For example, in httpd.conf you can not use PHP constants such as E_ALL or E_NOTICE to set the error_reporting directive as they will have no meaning and will evaluate to 0. Use the associated bitmask values instead. These constants can be used in php.ini |
When running PHP on Windows, the configuration values can be modified on a per-directory basis using the Windows registry. The configuration values are stored in the registry key HKLM\SOFTWARE\PHP\Per Directory Values, in the sub-keys corresponding to the path names. For example, configuration values for the directory c:\inetpub\wwwroot would be stored in the key HKLM\SOFTWARE\PHP\Per Directory Values\c\inetpub\wwwroot. The settings for the directory would be active for any script running from this directory or any subdirectory of it. The values under the key should have the name of the PHP configuration directive and the string value. PHP constants in the values are not parsed. However, only configuration values changeable in PHP_INI_USER can be set this way, PHP_INI_PERDIR values can not.
Regardless of how you run PHP, you can change certain values at runtime of your scripts through ini_set(). See the documentation on the ini_set() page for more information.
If you are interested in a complete list of configuration settings on your system with their current values, you can execute the phpinfo() function, and review the resulting page. You can also access the values of individual configuration directives at runtime using ini_get() or get_cfg_var().
Quando il PHP inizia a esaminare un file, cerca i tag di apertura e di chiusura, che indicano dove iniziare e terminare l'interpretazione del codice. Questa tecnica permette al PHP di essere incorporato in tutte le tipologie di documenti, poichè ogni cosa esterna ai tag di apertura e di chiusura viene ignoarat dal parser PHP. Il più delle volte si vedrà codice PHP racchiuso in documenti HTML, come nel seguente esempio.
<p>This is going to be ignored.</p> <?php echo 'While this is going to be parsed.'; ?> <p>This will also be ignored.</p> |
Si possono usare anche strutture più avanzate:
Esistono 4 set di tag che possono essere utilizzati per delimitare blocchi di codice PHP. Soltanto due di questi (<?php. . .?> e <script language="php">. . .</script>) sono sempre disponibili. Gli altri due sono i tag brevi e i tag stile ASP e possono essere attivati o disattivati tramite il file di configurazione php.ini. Sebbene i tag brevi o quelli in stile ASP possano essere pratici, questi sono meno portabili e, in generale, sconsigliati.
Nota: Occorre notare che se si intende inserire codice PHP all'interno di testi XMl o XHTML, occorre utilizzare <?php ?> per essere conformi allo standard XML.
Esempio 10-2. Tag di apertura e di chiusura
|
Sebbene i tag utilizzati negli esempi 1 e 2 siano sempre disponibili, l'esempio uno rappresenta la situazione più comunemente utilizzata, e la più raccomandata dei due.
I tag brevi (esempio tre) sono disponibili soltanto se sono stati abilitati tramite il parametro short_open_tag del php.ini, oppure se il PHP è stato configurato con --enable-short-tags.
Nota: Se si utilizza il PHP 3 si può anche avere disponibili i tag brevi tramite la funzione short_tags(). Questo vale solo per il PHP 3!
I tag in stile ASP (esempio quattro) sono disponibili soltanto quando sono abilitati tramite il parametro asp_tags del php.ini
Nota: Il supporto per i tag nello stile ASP è stato aggiunto nella versione 3.0.4.
Nota: L'utilizzo dei tag brevi dovrebbe essere evitato nello sviluppo di applicazioni o librerie destinate alla distribuzione o destinati a server di produzione PHP di cui non si ha il controllo poichè questi tag potrebbero non essere attivi sul server di destinazione. Per avere maggiore portabilità, codice redistribuibile, occorre essere certi di non utilizzare i tag brevi.
Come in C od in Perl, il PHP richiede che le istruzioni siano chiuse dal punto e virgola al termine di ogni istruzione. I tag di chiusura di un blocco di codice PHP implicano in automatico il punto e virgola; non occorre, pertanto, inserire il punto e virgola per chiudere l'ultima riga di un blocco PHP. Il tag di chiusura del blocco include il newline immediatamente seguente, se presente.
Il PHP supporta i commenti dei linguaggi 'C', 'C++' e stile shell (stile Perl) di Unix. Per esempio:
<?php echo 'Questo ` un test'; // Questo è un commento su una linea nella stile c++ /* Questo è un commento su più linee ancora un'altra linea di commento */ echo 'Questo è un altro test'; echo 'Un ultimo test'; # Questo è un commento stile shell Unix ?> |
Lo stile di commento su "una linea", attualmente commenta solo fino alla fine della linea o del blocco corrente di codice PHP. Questo significa che l'eventuale codice HTML posto dopo // ?> sarà stampato: ?> esce dalla modalità PHP e ritorna in modalità HTML, e quindi // non può influenzare quest'ultima. Se l'impostazione asp_tags è abilitata, il PHP si comporta allo stesso modo con // %>. Tuttavia il tag </script> non esce dalla modalità PHP nei commenti di una linea.
<h1>Questo è un <?# echo 'semplice';?> esempio.</h1> <p>L'intestazione qui sopra dirà 'Questo è un esempio'.</p> |
I commenti in stile C terminano alla prima occorrenza di */. Occorre fare attenzione nel non annidare i commenti di stile C, situazione che si presenta quando si commentano larghi blocchi di codice.
PHP supports eight primitive types.
Four scalar types:
Two compound types: And finally two special types: This manual also introduces some pseudo-types for readability reasons: You may also find some references to the type "double". Consider double the same as float, the two names exist only for historic reasons.The type of a variable is usually not set by the programmer; rather, it is decided at runtime by PHP depending on the context in which that variable is used.
Nota: If you want to check out the type and value of a certain expression, use var_dump().
Nota: If you simply want a human-readable representation of the type for debugging, use gettype(). To check for a certain type, do not use gettype(), but use the is_type functions. Some examples:
<?php $bool = TRUE; // a boolean $str = "foo"; // a string $int = 12; // an integer echo gettype($bool); // prints out "boolean" echo gettype($str); // prints out "string" // If this is an integer, increment it by four if (is_int($int)) { $int += 4; } // If $bool is a string, print it out // (does not print out anything) if (is_string($bool)) { echo "String: $bool"; } ?>
If you would like to force a variable to be converted to a certain type, you may either cast the variable or use the settype() function on it.
Note that a variable may be evaluated with different values in certain situations, depending on what type it is at the time. For more information, see the section on Type Juggling. Also, you may be interested in viewing the type comparison tables, as they show examples of various type related comparisons.
This is the easiest type. A boolean expresses a truth value. It can be either TRUE or FALSE.
Nota: The boolean type was introduced in PHP 4.
To specify a boolean literal, use either the keyword TRUE or FALSE. Both are case-insensitive.
Usually you use some kind of operator which returns a boolean value, and then pass it on to a control structure.
To explicitly convert a value to boolean, use either the (bool) or the (boolean) cast. However, in most cases you do not need to use the cast, since a value will be automatically converted if an operator, function or control structure requires a boolean argument.
See also Type Juggling.
When converting to boolean, the following values are considered FALSE:
the boolean FALSE itself
the integer 0 (zero)
the float 0.0 (zero)
an array with zero elements
an object with zero member variables (PHP 4 only)
the special type NULL (including unset variables)
Avvertimento |
-1 is considered TRUE, like any other non-zero (whether negative or positive) number! |
<?php var_dump((bool) ""); // bool(false) var_dump((bool) 1); // bool(true) var_dump((bool) -2); // bool(true) var_dump((bool) "foo"); // bool(true) var_dump((bool) 2.3e5); // bool(true) var_dump((bool) array(12)); // bool(true) var_dump((bool) array()); // bool(false) var_dump((bool) "false"); // bool(true) ?> |
An integer is a number of the set Z = {..., -2, -1, 0, 1, 2, ...}.
See also: Arbitrary length integer / GMP, Floating point numbers, and Arbitrary precision / BCMath
Integers can be specified in decimal (10-based), hexadecimal (16-based) or octal (8-based) notation, optionally preceded by a sign (- or +).
If you use the octal notation, you must precede the number with a 0 (zero), to use hexadecimal notation precede the number with 0x.
If you specify a number beyond the bounds of the integer type, it will be interpreted as a float instead. Also, if you perform an operation that results in a number beyond the bounds of the integer type, a float will be returned instead.
<?php $large_number = 2147483647; var_dump($large_number); // output: int(2147483647) $large_number = 2147483648; var_dump($large_number); // output: float(2147483648) // this doesn't go for hexadecimal specified integers: var_dump( 0x100000000 ); // output: int(2147483647) $million = 1000000; $large_number = 50000 * $million; var_dump($large_number); // output: float(50000000000) ?> |
Avvertimento |
Unfortunately, there was a bug in PHP so that this does not always work correctly when there are negative numbers involved. For example: when you do -50000 * $million, the result will be -429496728. However, when both operands are positive there is no problem. This is solved in PHP 4.1.0. |
There is no integer division operator in PHP. 1/2 yields the float 0.5. You can cast the value to an integer to always round it downwards, or you can use the round() function.
To explicitly convert a value to integer, use either the (int) or the (integer) cast. However, in most cases you do not need to use the cast, since a value will be automatically converted if an operator, function or control structure requires an integer argument. You can also convert a value to integer with the function intval().
See also type-juggling.
When converting from float to integer, the number will be rounded towards zero.
If the float is beyond the boundaries of integer (usually +/- 2.15e+9 = 2^31), the result is undefined, since the float hasn't got enough precision to give an exact integer result. No warning, not even a notice will be issued in this case!
Avvertimento |
Never cast an unknown fraction to integer, as this can sometimes lead to unexpected results. See for more information the warning about float-precision. |
Attenzione |
Behaviour of converting to integer is undefined for other types. Currently, the behaviour is the same as if the value was first converted to boolean. However, do not rely on this behaviour, as it can change without notice. |
Floating point numbers (AKA "floats", "doubles" or "real numbers") can be specified using any of the following syntaxes:
Formally:LNUM [0-9]+ DNUM ([0-9]*[\.]{LNUM}) | ({LNUM}[\.][0-9]*) EXPONENT_DNUM ( ({LNUM} | {DNUM}) [eE][+-]? {LNUM}) |
Floating point precision |
It is quite usual that simple decimal fractions like 0.1 or 0.7 cannot be converted into their internal binary counterparts without a little loss of precision. This can lead to confusing results: for example, floor((0.1+0.7)*10) will usually return 7 instead of the expected 8 as the result of the internal representation really being something like 7.9999999999.... This is related to the fact that it is impossible to exactly express some fractions in decimal notation with a finite number of digits. For instance, 1/3 in decimal form becomes 0.3333333. . .. So never trust floating number results to the last digit and never compare floating point numbers for equality. If you really need higher precision, you should use the arbitrary precision math functions or gmp functions instead. |
For information on when and how strings are converted to floats, see the section titled String conversion to numbers. For values of other types, the conversion is the same as if the value would have been converted to integer and then to float. See the Converting to integer section for more information. As of PHP 5, notice is thrown if you try to convert object to float.
A string is series of characters. In PHP, a character is the same as a byte, that is, there are exactly 256 different characters possible. This also implies that PHP has no native support of Unicode. See utf8_encode() and utf8_decode() for some Unicode support.
Nota: It is no problem for a string to become very large. There is no practical bound to the size of strings imposed by PHP, so there is no reason at all to worry about long strings.
A string literal can be specified in three different ways.
The easiest way to specify a simple string is to enclose it in single quotes (the character ').
To specify a literal single quote, you will need to escape it with a backslash (\), like in many other languages. If a backslash needs to occur before a single quote or at the end of the string, you need to double it. Note that if you try to escape any other character, the backslash will also be printed! So usually there is no need to escape the backslash itself.
Nota: In PHP 3, a warning will be issued at the E_NOTICE level when this happens.
Nota: Unlike the two other syntaxes, variables and escape sequences for special characters will not be expanded when they occur in single quoted strings.
<?php echo 'this is a simple string'; echo 'You can also have embedded newlines in strings this way as it is okay to do'; // Outputs: Arnold once said: "I'll be back" echo 'Arnold once said: "I\'ll be back"'; // Outputs: You deleted C:\*.*? echo 'You deleted C:\\*.*?'; // Outputs: You deleted C:\*.*? echo 'You deleted C:\*.*?'; // Outputs: This will not expand: \n a newline echo 'This will not expand: \n a newline'; // Outputs: Variables do not $expand $either echo 'Variables do not $expand $either'; ?> |
If the string is enclosed in double-quotes ("), PHP understands more escape sequences for special characters:
Tabella 11-1. Escaped characters
sequence | meaning |
---|---|
\n | linefeed (LF or 0x0A (10) in ASCII) |
\r | carriage return (CR or 0x0D (13) in ASCII) |
\t | horizontal tab (HT or 0x09 (9) in ASCII) |
\\ | backslash |
\$ | dollar sign |
\" | double-quote |
\[0-7]{1,3} | the sequence of characters matching the regular expression is a character in octal notation |
\x[0-9A-Fa-f]{1,2} | the sequence of characters matching the regular expression is a character in hexadecimal notation |
Again, if you try to escape any other character, the backslash will be printed too!
But the most important feature of double-quoted strings is the fact that variable names will be expanded. See string parsing for details.
Another way to delimit strings is by using heredoc syntax ("<<<"). One should provide an identifier after <<<, then the string, and then the same identifier to close the quotation.
The closing identifier must begin in the first column of the line. Also, the identifier used must follow the same naming rules as any other label in PHP: it must contain only alphanumeric characters and underscores, and must start with a non-digit character or underscore.
Avvertimento | |
It is very important to note that the line with the closing identifier contains no other characters, except possibly a semicolon (;). That means especially that the identifier may not be indented, and there may not be any spaces or tabs after or before the semicolon. It's also important to realize that the first character before the closing identifier must be a newline as defined by your operating system. This is \r on Macintosh for example. If this rule is broken and the closing identifier is not "clean" then it's not considered to be a closing identifier and PHP will continue looking for one. If in this case a proper closing identifier is not found then a parse error will result with the line number being at the end of the script. It is not allowed to use heredoc syntax in initializing class members. Use other string syntaxes instead. |
Heredoc text behaves just like a double-quoted string, without the double-quotes. This means that you do not need to escape quotes in your here docs, but you can still use the escape codes listed above. Variables are expanded, but the same care must be taken when expressing complex variables inside a heredoc as with strings.
Esempio 11-4. Heredoc string quoting example
|
Nota: Heredoc support was added in PHP 4.
When a string is specified in double quotes or with heredoc, variables are parsed within it.
There are two types of syntax: a simple one and a complex one. The simple syntax is the most common and convenient. It provides a way to parse a variable, an array value, or an object property.
The complex syntax was introduced in PHP 4, and can be recognised by the curly braces surrounding the expression.
If a dollar sign ($) is encountered, the parser will greedily take as many tokens as possible to form a valid variable name. Enclose the variable name in curly braces if you want to explicitly specify the end of the name.
<?php $beer = 'Heineken'; echo "$beer's taste is great"; // works, "'" is an invalid character for varnames echo "He drank some $beers"; // won't work, 's' is a valid character for varnames echo "He drank some ${beer}s"; // works echo "He drank some {$beer}s"; // works ?> |
Similarly, you can also have an array index or an object property parsed. With array indices, the closing square bracket (]) marks the end of the index. For object properties the same rules apply as to simple variables, though with object properties there doesn't exist a trick like the one with variables.
<?php // These examples are specific to using arrays inside of strings. // When outside of a string, always quote your array string keys // and do not use {braces} when outside of strings either. // Let's show all errors error_reporting(E_ALL); $fruits = array('strawberry' => 'red', 'banana' => 'yellow'); // Works but note that this works differently outside string-quotes echo "A banana is $fruits[banana]."; // Works echo "A banana is {$fruits['banana']}."; // Works but PHP looks for a constant named banana first // as described below. echo "A banana is {$fruits[banana]}."; // Won't work, use braces. This results in a parse error. echo "A banana is $fruits['banana']."; // Works echo "A banana is " . $fruits['banana'] . "."; // Works echo "This square is $square->width meters broad."; // Won't work. For a solution, see the complex syntax. echo "This square is $square->width00 centimeters broad."; ?> |
For anything more complex, you should use the complex syntax.
This isn't called complex because the syntax is complex, but because you can include complex expressions this way.
In fact, you can include any value that is in the namespace in strings with this syntax. You simply write the expression the same way as you would outside the string, and then include it in { and }. Since you can't escape '{', this syntax will only be recognised when the $ is immediately following the {. (Use "{\$" or "\{$" to get a literal "{$"). Some examples to make it clear:
<?php // Let's show all errors error_reporting(E_ALL); $great = 'fantastic'; // Won't work, outputs: This is { fantastic} echo "This is { $great}"; // Works, outputs: This is fantastic echo "This is {$great}"; echo "This is ${great}"; // Works echo "This square is {$square->width}00 centimeters broad."; // Works echo "This works: {$arr[4][3]}"; // This is wrong for the same reason as $foo[bar] is wrong // outside a string. In other words, it will still work but // because PHP first looks for a constant named foo, it will // throw an error of level E_NOTICE (undefined constant). echo "This is wrong: {$arr[foo][3]}"; // Works. When using multi-dimensional arrays, always use // braces around arrays when inside of strings echo "This works: {$arr['foo'][3]}"; // Works. echo "This works: " . $arr['foo'][3]; echo "You can even write {$obj->values[3]->name}"; echo "This is the value of the var named $name: {${$name}}"; ?> |
Characters within strings may be accessed and modified by specifying the zero-based offset of the desired character after the string in curly braces.
Nota: For backwards compatibility, you can still use array-brackets for the same purpose. However, this syntax is deprecated as of PHP 4.
Esempio 11-5. Some string examples
|
Strings may be concatenated using the '.' (dot) operator. Note that the '+' (addition) operator will not work for this. Please see String operators for more information.
There are a lot of useful functions for string modification.
See the string functions section for general functions, the regular expression functions for advanced find&replacing (in two tastes: Perl and POSIX extended).
There are also functions for URL-strings, and functions to encrypt/decrypt strings (mcrypt and mhash).
Finally, if you still didn't find what you're looking for, see also the character type functions.
You can convert a value to a string using the (string) cast, or the strval() function. String conversion is automatically done in the scope of an expression for you where a string is needed. This happens when you use the echo() or print() functions, or when you compare a variable value to a string. Reading the manual sections on Types and Type Juggling will make the following clearer. See also settype().
A boolean TRUE value is converted to the string "1", the FALSE value is represented as "" (empty string). This way you can convert back and forth between boolean and string values.
An integer or a floating point number (float) is converted to a string representing the number with its digits (including the exponent part for floating point numbers).
Arrays are always converted to the string "Array", so you cannot dump out the contents of an array with echo() or print() to see what is inside them. To view one element, you'd do something like echo $arr['foo']. See below for tips on dumping/viewing the entire contents.
Objects are always converted to the string "Object". If you would like to print out the member variable values of an object for debugging reasons, read the paragraphs below. If you would like to find out the class name of which an object is an instance of, use get_class(). As of PHP 5, __toString() method is used if applicable.
Resources are always converted to strings with the structure "Resource id #1" where 1 is the unique number of the resource assigned by PHP during runtime. If you would like to get the type of the resource, use get_resource_type().
NULL is always converted to an empty string.
As you can see above, printing out the arrays, objects or resources does not provide you any useful information about the values themselves. Look at the functions print_r() and var_dump() for better ways to print out values for debugging.
You can also convert PHP values to strings to store them permanently. This method is called serialization, and can be done with the function serialize(). You can also serialize PHP values to XML structures, if you have WDDX support in your PHP setup.
When a string is evaluated as a numeric value, the resulting value and type are determined as follows.
The string will evaluate as a float if it contains any of the characters '.', 'e', or 'E'. Otherwise, it will evaluate as an integer.
The value is given by the initial portion of the string. If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero). Valid numeric data is an optional sign, followed by one or more digits (optionally containing a decimal point), followed by an optional exponent. The exponent is an 'e' or 'E' followed by one or more digits.
<?php $foo = 1 + "10.5"; // $foo is float (11.5) $foo = 1 + "-1.3e3"; // $foo is float (-1299) $foo = 1 + "bob-1.3e3"; // $foo is integer (1) $foo = 1 + "bob3"; // $foo is integer (1) $foo = 1 + "10 Small Pigs"; // $foo is integer (11) $foo = 4 + "10.2 Little Piggies"; // $foo is float (14.2) $foo = "10.0 pigs " + 1; // $foo is float (11) $foo = "10.0 pigs " + 1.0; // $foo is float (11) ?> |
For more information on this conversion, see the Unix manual page for strtod(3).
If you would like to test any of the examples in this section, you can cut and paste the examples and insert the following line to see for yourself what's going on:
Do not expect to get the code of one character by converting it to integer (as you would do in C for example). Use the functions ord() and chr() to convert between charcodes and characters.
An array in PHP is actually an ordered map. A map is a type that maps values to keys. This type is optimized in several ways, so you can use it as a real array, or a list (vector), hashtable (which is an implementation of a map), dictionary, collection, stack, queue and probably more. Because you can have another PHP array as a value, you can also quite easily simulate trees.
Explanation of those data structures is beyond the scope of this manual, but you'll find at least one example for each of them. For more information we refer you to external literature about this broad topic.
An array can be created by the array() language-construct. It takes a certain number of comma-separated key => value pairs.
array( [key =>] value , ... ) // key may be an integer or string // value may be any value |
A key may be either an integer or a string. If a key is the standard representation of an integer, it will be interpreted as such (i.e. "8" will be interpreted as 8, while "08" will be interpreted as "08"). Floats in key are truncated to integer. There are no different indexed and associative array types in PHP; there is only one array type, which can both contain integer and string indices.
A value can be of any PHP type.
<?php $arr = array("somearray" => array(6 => 5, 13 => 9, "a" => 42)); echo $arr["somearray"][6]; // 5 echo $arr["somearray"][13]; // 9 echo $arr["somearray"]["a"]; // 42 ?> |
If you do not specify a key for a given value, then the maximum of the integer indices is taken, and the new key will be that maximum value + 1. If you specify a key that already has a value assigned to it, that value will be overwritten.
<?php // This array is the same as ... array(5 => 43, 32, 56, "b" => 12); // ...this array array(5 => 43, 6 => 32, 7 => 56, "b" => 12); ?> |
Avvertimento |
As of PHP 4.3.0, the index generation behaviour described above has changed. Now, if you append to an array in which the current maximum key is negative, then the next key created will be zero (0). Before, the new index would have been set to the largest existing key + 1, the same as positive indices are. |
Using TRUE as a key will evaluate to integer 1 as key. Using FALSE as a key will evaluate to integer 0 as key. Using NULL as a key will evaluate to the empty string. Using the empty string as key will create (or overwrite) a key with the empty string and its value; it is not the same as using empty brackets.
You cannot use arrays or objects as keys. Doing so will result in a warning: Illegal offset type.
You can also modify an existing array by explicitly setting values in it.
This is done by assigning values to the array while specifying the key in brackets. You can also omit the key, add an empty pair of brackets ("[]") to the variable name in that case.
$arr[key] = value; $arr[] = value; // key may be an integer or string // value may be any value |
<?php $arr = array(5 => 1, 12 => 2); $arr[] = 56; // This is the same as $arr[13] = 56; // at this point of the script $arr["x"] = 42; // This adds a new element to // the array with key "x" unset($arr[5]); // This removes the element from the array unset($arr); // This deletes the whole array ?> |
Nota: As mentioned above, if you provide the brackets with no key specified, then the maximum of the existing integer indices is taken, and the new key will be that maximum value + 1 . If no integer indices exist yet, the key will be 0 (zero). If you specify a key that already has a value assigned to it, that value will be overwritten.
Avvertimento As of PHP 4.3.0, the index generation behaviour described above has changed. Now, if you append to an array in which the current maximum key is negative, then the next key created will be zero (0). Before, the new index would have been set to the largest existing key + 1, the same as positive indices are.
Note that the maximum integer key used for this need not currently exist in the array. It simply must have existed in the array at some time since the last time the array was re-indexed. The following example illustrates:
<?php // Create a simple array. $array = array(1, 2, 3, 4, 5); print_r($array); // Now delete every item, but leave the array itself intact: foreach ($array as $i => $value) { unset($array[$i]); } print_r($array); // Append an item (note that the new key is 5, instead of 0 as you // might expect). $array[] = 6; print_r($array); // Re-index: $array = array_values($array); $array[] = 7; print_r($array); ?>Il precedente esempio visualizzerà:
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 ) Array ( ) Array ( [5] => 6 ) Array ( [0] => 6 [1] => 7 )
There are quite a few useful functions for working with arrays. See the array functions section.
Nota: The unset() function allows unsetting keys of an array. Be aware that the array will NOT be reindexed. If you only use "usual integer indices" (starting from zero, increasing by one), you can achieve the reindex effect by using array_values().
The foreach control structure exists specifically for arrays. It provides an easy way to traverse an array.
You should always use quotes around a string literal array index. For example, use $foo['bar'] and not $foo[bar]. But why is $foo[bar] wrong? You might have seen the following syntax in old scripts:
This is wrong, but it works. Then, why is it wrong? The reason is that this code has an undefined constant (bar) rather than a string ('bar' - notice the quotes), and PHP may in future define constants which, unfortunately for your code, have the same name. It works because PHP automatically converts a bare string (an unquoted string which does not correspond to any known symbol) into a string which contains the bare string. For instance, if there is no defined constant named bar, then PHP will substitute in the string 'bar' and use that.Nota: This does not mean to always quote the key. You do not want to quote keys which are constants or variables, as this will prevent PHP from interpreting them.
<?php error_reporting(E_ALL); ini_set('display_errors', true); ini_set('html_errors', false); // Simple array: $array = array(1, 2); $count = count($array); for ($i = 0; $i < $count; $i++) { echo "\nChecking $i: \n"; echo "Bad: " . $array['$i'] . "\n"; echo "Good: " . $array[$i] . "\n"; echo "Bad: {$array['$i']}\n"; echo "Good: {$array[$i]}\n"; } ?>Nota: Il precedente esempio visualizzerà:
Checking 0: Notice: Undefined index: $i in /path/to/script.html on line 9 Bad: Good: 1 Notice: Undefined index: $i in /path/to/script.html on line 11 Bad: Good: 1 Checking 1: Notice: Undefined index: $i in /path/to/script.html on line 9 Bad: Good: 2 Notice: Undefined index: $i in /path/to/script.html on line 11 Bad: Good: 2
More examples to demonstrate this fact:
<?php // Let's show all errors error_reporting(E_ALL); $arr = array('fruit' => 'apple', 'veggie' => 'carrot'); // Correct print $arr['fruit']; // apple print $arr['veggie']; // carrot // Incorrect. This works but also throws a PHP error of // level E_NOTICE because of an undefined constant named fruit // // Notice: Use of undefined constant fruit - assumed 'fruit' in... print $arr[fruit]; // apple // Let's define a constant to demonstrate what's going on. We // will assign value 'veggie' to a constant named fruit. define('fruit', 'veggie'); // Notice the difference now print $arr['fruit']; // apple print $arr[fruit]; // carrot // The following is okay as it's inside a string. Constants are not // looked for within strings so no E_NOTICE error here print "Hello $arr[fruit]"; // Hello apple // With one exception, braces surrounding arrays within strings // allows constants to be looked for print "Hello {$arr[fruit]}"; // Hello carrot print "Hello {$arr['fruit']}"; // Hello apple // This will not work, results in a parse error such as: // Parse error: parse error, expecting T_STRING' or T_VARIABLE' or T_NUM_STRING' // This of course applies to using autoglobals in strings as well print "Hello $arr['fruit']"; print "Hello $_GET['foo']"; // Concatenation is another option print "Hello " . $arr['fruit']; // Hello apple ?> |
When you turn error_reporting() up to show E_NOTICE level errors (such as setting it to E_ALL) then you will see these errors. By default, error_reporting is turned down to not show them.
As stated in the syntax section, there must be an expression between the square brackets ('[' and ']'). That means that you can write things like this:
This is an example of using a function return value as the array index. PHP also knows about constants, as you may have seen the E_* ones before.<?php $error_descriptions[E_ERROR] = "A fatal error has occured"; $error_descriptions[E_WARNING] = "PHP issued a warning"; $error_descriptions[E_NOTICE] = "This is just an informal notice"; ?> |
<?php $error_descriptions[1] = "A fatal error has occured"; $error_descriptions[2] = "PHP issued a warning"; $error_descriptions[8] = "This is just an informal notice"; ?> |
As we already explained in the above examples, $foo[bar] still works but is wrong. It works, because bar is due to its syntax expected to be a constant expression. However, in this case no constant with the name bar exists. PHP now assumes that you meant bar literally, as the string "bar", but that you forgot to write the quotes.
At some point in the future, the PHP team might want to add another constant or keyword, or you may introduce another constant into your application, and then you get in trouble. For example, you already cannot use the words empty and default this way, since they are special reserved keywords.
Nota: To reiterate, inside a double-quoted string, it's valid to not surround array indexes with quotes so "$foo[bar]" is valid. See the above examples for details on why as well as the section on variable parsing in strings.
For any of the types: integer, float, string, boolean and resource, if you convert a value to an array, you get an array with one element (with index 0), which is the scalar value you started with.
If you convert an object to an array, you get the properties (member variables) of that object as the array's elements. The keys are the member variable names.
If you convert a NULL value to an array, you get an empty array.
The array type in PHP is very versatile, so here will be some examples to show you the full power of arrays.
<?php // this $a = array( 'color' => 'red', 'taste' => 'sweet', 'shape' => 'round', 'name' => 'apple', 4 // key will be 0 ); // is completely equivalent with $a['color'] = 'red'; $a['taste'] = 'sweet'; $a['shape'] = 'round'; $a['name'] = 'apple'; $a[] = 4; // key will be 0 $b[] = 'a'; $b[] = 'b'; $b[] = 'c'; // will result in the array array(0 => 'a' , 1 => 'b' , 2 => 'c'), // or simply array('a', 'b', 'c') ?> |
Esempio 11-6. Using array()
|
Changing values of the array directly is possible since PHP 5 by passing them as reference. Prior versions need workaround:
Esempio 11-8. Collection
Il precedente esempio visualizzerà:
|
This example creates a one-based array.
Arrays are ordered. You can also change the order using various sorting functions. See the array functions section for more information. You can count the number of items in an array using the count() function.
Because the value of an array can be anything, it can also be another array. This way you can make recursive and multi-dimensional arrays.
Esempio 11-12. Recursive and multi-dimensional arrays
|
You should be aware that array assignment always involves value copying. You need to use the reference operator to copy an array by reference.
To initialize an object, you use the new statement to instantiate the object to a variable.
For a full discussion, please read the section Classes and Objects.
If an object is converted to an object, it is not modified. If a value of any other type is converted to an object, a new instance of the stdClass built in class is created. If the value was NULL, the new instance will be empty. Array converts to an object with properties named by array keys and with corresponding values. For any other value, a member variable named scalar will contain the value.
A resource is a special variable, holding a reference to an external resource. Resources are created and used by special functions. See the appendix for a listing of all these functions and the corresponding resource types.
Nota: The resource type was introduced in PHP 4
See also get_resource_type().
As resource types hold special handlers to opened files, database connections, image canvas areas and the like, you cannot convert any value to a resource.
Due to the reference-counting system introduced with PHP 4's Zend Engine, it is automatically detected when a resource is no longer referred to (just like Java). When this is the case, all resources that were in use for this resource are made free by the garbage collector. For this reason, it is rarely ever necessary to free the memory manually by using some free_result function.
Nota: Persistent database links are special, they are not destroyed by the garbage collector. See also the section about persistent connections.
The special NULL value represents that a variable has no value. NULL is the only possible value of type NULL.
Nota: The null type was introduced in PHP 4.
A variable is considered to be NULL if
it has been assigned the constant NULL.
it has not been set to any value yet.
it has been unset().
mixed indicates that a parameter may accept multiple (but not necessarily all) types.
gettype() for example will accept all PHP types, while str_replace() will accept strings and arrays.
Some functions like call_user_func() 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.
Esempio 11-13. Callback function examples
|
PHP does not require (or support) explicit type definition in variable declaration; a variable's type is determined by the context in which that variable is used. That is to say, if you assign a string value to variable $var, $var becomes a string. If you then assign an integer value to $var, it becomes an integer.
An example of PHP's automatic type conversion is the addition operator '+'. If any of the operands is a float, then all operands are evaluated as floats, and the result will be a float. Otherwise, the operands will be interpreted as integers, and the result will also be an integer. Note that this does NOT change the types of the operands themselves; the only change is in how the operands are evaluated.
<?php $foo = "0"; // $foo is string (ASCII 48) $foo += 2; // $foo is now an integer (2) $foo = $foo + 1.3; // $foo is now a float (3.3) $foo = 5 + "10 Little Piggies"; // $foo is integer (15) $foo = 5 + "10 Small Pigs"; // $foo is integer (15) ?> |
If the last two examples above seem odd, see String conversion to numbers.
If you wish to force a variable to be evaluated as a certain type, see the section on Type casting. If you wish to change the type of a variable, see settype().
If you would like to test any of the examples in this section, you can use the var_dump() function.
Nota: The behaviour of an automatic conversion to array is currently undefined.
Since PHP (for historical reasons) supports indexing into strings via offsets using the same syntax as array indexing, the example above leads to a problem: should $a become an array with its first element being "f", or should "f" become the first character of the string $a?
The current versions of PHP interpret the second assignment as a string offset identification, so $a becomes "f", the result of this automatic conversion however should be considered undefined. PHP 4 introduced the new curly bracket syntax to access characters in string, use this syntax instead of the one presented above:
See the section titled String access by character for more information.
Type casting in PHP works much as it does in C: the name of the desired type is written in parentheses before the variable which is to be cast.
The casts allowed are:
(int), (integer) - cast to integer
(bool), (boolean) - cast to boolean
(float), (double), (real) - cast to float
(string) - cast to string
(array) - cast to array
(object) - cast to object
Note that tabs and spaces are allowed inside the parentheses, so the following are functionally equivalent:
Nota: Instead of casting a variable to string, you can also enclose the variable in double quotes.
It may not be obvious exactly what will happen when casting between certain types. For more info, see these sections:
Variables in PHP are represented by a dollar sign followed by the name of the variable. The variable name is case-sensitive.
Variable names follow the same rules as other labels in PHP. A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thus: '[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*'
Nota: For our purposes here, a letter is a-z, A-Z, and the ASCII characters from 127 through 255 (0x7f-0xff).
For information on variable related functions, see the Variable Functions Reference.
<?php $var = 'Bob'; $Var = 'Joe'; echo "$var, $Var"; // outputs "Bob, Joe" $4site = 'not yet'; // invalid; starts with a number $_4site = 'not yet'; // valid; starts with an underscore $täyte = 'mansikka'; // valid; 'ä' is (Extended) ASCII 228. ?> |
In PHP 3, variables are always assigned by value. That is to say, when you assign an expression to a variable, the entire value of the original expression is copied into the destination variable. This means, for instance, that after assigning one variable's value to another, changing one of those variables will have no effect on the other. For more information on this kind of assignment, see the chapter on Expressions.
As of PHP 4, PHP offers another way to assign values to variables: assign by reference. This means that the new variable simply references (in other words, "becomes an alias for" or "points to") the original variable. Changes to the new variable affect the original, and vice versa. This also means that no copying is performed; thus, the assignment happens more quickly. However, any speedup will likely be noticed only in tight loops or when assigning large arrays or objects.
To assign by reference, simply prepend an ampersand (&) to the beginning of the variable which is being assigned (the source variable). For instance, the following code snippet outputs 'My name is Bob' twice:
<?php $foo = 'Bob'; // Assign the value 'Bob' to $foo $bar = &$foo; // Reference $foo via $bar. $bar = "My name is $bar"; // Alter $bar... echo $bar; echo $foo; // $foo is altered too. ?> |
One important thing to note is that only named variables may be assigned by reference.
PHP provides a large number of predefined variables to any script which it runs. Many of these variables, however, cannot be fully documented as they are dependent upon which server is running, the version and setup of the server, and other factors. Some of these variables will not be available when PHP is run on the command line. For a listing of these variables, please see the section on Reserved Predefined Variables.
Avvertimento |
In PHP 4.2.0 and later, the default value for the PHP directive register_globals is off. This is a major change in PHP. Having register_globals off affects the set of predefined variables available in the global scope. For example, to get DOCUMENT_ROOT you'll use $_SERVER['DOCUMENT_ROOT'] instead of $DOCUMENT_ROOT, or $_GET['id'] from the URL http://www.example.com/test.php?id=3 instead of $id, or $_ENV['HOME'] instead of $HOME. For related information on this change, read the configuration entry for register_globals, the security chapter on Using Register Globals , as well as the PHP 4.1.0 and 4.2.0 Release Announcements. Using the available PHP Reserved Predefined Variables, like the superglobal arrays, is preferred. |
From version 4.1.0 onward, PHP provides an additional set of predefined arrays containing variables from the web server (if applicable), the environment, and user input. These new arrays are rather special in that they are automatically global--i.e., automatically available in every scope. For this reason, they are often known as 'autoglobals' or 'superglobals'. (There is no mechanism in PHP for user-defined superglobals.) The superglobals are listed below; however, for a listing of their contents and further discussion on PHP predefined variables and their natures, please see the section Reserved Predefined Variables. Also, you'll notice how the older predefined variables ($HTTP_*_VARS) still exist. As of PHP 5.0.0, the long PHP predefined variable arrays may be disabled with the register_long_arrays directive.
Variable variables: Superglobals cannot be used as variable variables inside functions or class methods.
Nota: Even though both the superglobal and HTTP_*_VARS can exist at the same time; they are not identical, so modifying one will not change the other.
If certain variables in variables_order are not set, their appropriate PHP predefined arrays are also left empty.
PHP Superglobals
Contains a reference to every variable which is currently available within the global scope of the script. The keys of this array are the names of the global variables. $GLOBALS has existed since PHP 3.
Variables set by the web server or otherwise directly related to the execution environment of the current script. Analogous to the old $HTTP_SERVER_VARS array (which is still available, but deprecated).
Variables provided to the script via URL query string. Analogous to the old $HTTP_GET_VARS array (which is still available, but deprecated).
Variables provided to the script via HTTP POST. Analogous to the old $HTTP_POST_VARS array (which is still available, but deprecated).
Variables provided to the script via HTTP cookies. Analogous to the old $HTTP_COOKIE_VARS array (which is still available, but deprecated).
Variables provided to the script via HTTP post file uploads. Analogous to the old $HTTP_POST_FILES array (which is still available, but deprecated). See POST method uploads for more information.
Variables provided to the script via the environment. Analogous to the old $HTTP_ENV_VARS array (which is still available, but deprecated).
Variables provided to the script via the GET, POST, and COOKIE input mechanisms, and which therefore cannot be trusted. The presence and order of variable inclusion in this array is defined according to the PHP variables_order configuration directive. This array has no direct analogue in versions of PHP prior to 4.1.0. See also import_request_variables().
Attenzione |
Since PHP 4.3.0, FILE information from $_FILES does not exist in $_REQUEST. |
Nota: When running on the command line , this will not include the argv and argc entries; these are present in the $_SERVER array.
Variables which are currently registered to a script's session. Analogous to the old $HTTP_SESSION_VARS array (which is still available, but deprecated). See the Session handling functions section for more information.
The scope of a variable is the context within which it is defined. For the most part all PHP variables only have a single scope. This single scope spans included and required files as well. For example:
Here the $a variable will be available within the included b.inc script. However, within user-defined functions a local function scope is introduced. Any variable used inside a function is by default limited to the local function scope. For example:
<?php $a = 1; /* global scope */ function Test() { echo $a; /* reference to local scope variable */ } Test(); ?> |
This script will not produce any output because the echo statement refers to a local version of the $a variable, and it has not been assigned a value within this scope. You may notice that this is a little bit different from the C language in that global variables in C are automatically available to functions unless specifically overridden by a local definition. This can cause some problems in that people may inadvertently change a global variable. In PHP global variables must be declared global inside a function if they are going to be used in that function.
First, an example use of global:
The above script will output "3". By declaring $a and $b global within the function, all references to either variable will refer to the global version. There is no limit to the number of global variables that can be manipulated by a function.
A second way to access variables from the global scope is to use the special PHP-defined $GLOBALS array. The previous example can be rewritten as:
The $GLOBALS array is an associative array with the name of the global variable being the key and the contents of that variable being the value of the array element. Notice how $GLOBALS exists in any scope, this is because $GLOBALS is a superglobal. Here's an example demonstrating the power of superglobals:
Esempio 12-3. Example demonstrating superglobals and scope
|
Another important feature of variable scoping is the static variable. A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope. Consider the following example:
This function is quite useless since every time it is called it sets $a to 0 and prints "0". The $a++ which increments the variable serves no purpose since as soon as the function exits the $a variable disappears. To make a useful counting function which will not lose track of the current count, the $a variable is declared static:
Now, every time the Test() function is called it will print the value of $a and increment it.
Static variables also provide one way to deal with recursive functions. A recursive function is one which calls itself. Care must be taken when writing a recursive function because it is possible to make it recurse indefinitely. You must make sure you have an adequate way of terminating the recursion. The following simple function recursively counts to 10, using the static variable $count to know when to stop:
Nota: Static variables may be declared as seen in the examples above. Trying to assign values to these variables which are the result of expressions will cause a parse error.
The Zend Engine 1, driving PHP 4, implements the static and global modifier for variables in terms of references. For example, a true global variable imported inside a function scope with the global statement actually creates a reference to the global variable. This can lead to unexpected behaviour which the following example addresses:
<?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); ?> |
Executing this example will result in the following output:
NULL object(stdClass)(0) { } |
A similar behaviour applies to the static statement. References are not stored statically:
<?php function &get_instance_ref() { static $obj; echo 'Static object: '; var_dump($obj); if (!isset($obj)) { // Assign a reference to the static variable $obj = &new stdclass; } $obj->property++; return $obj; } function &get_instance_noref() { static $obj; echo 'Static object: '; var_dump($obj); if (!isset($obj)) { // Assign the object to the static variable $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(); ?> |
Executing this example will result in the following output:
Static object: NULL Static object: NULL Static object: NULL Static object: object(stdClass)(1) { ["property"]=> int(1) } |
This example demonstrates that when assigning a reference to a static variable, it's not remembered when you call the &get_instance_ref() function a second time.
Sometimes it is convenient to be able to have variable variable names. That is, a variable name which can be set and used dynamically. A normal variable is set with a statement such as:
A variable variable takes the value of a variable and treats that as the name of a variable. In the above example, hello, can be used as the name of a variable by using two dollar signs. i.e.
At this point two variables have been defined and stored in the PHP symbol tree: $a with contents "hello" and $hello with contents "world". Therefore, this statement:
produces the exact same output as:
i.e. they both produce: hello world.
In order to use variable variables with arrays, you have to resolve an ambiguity problem. That is, if you write $$a[1] then the parser needs to know if you meant to use $a[1] as a variable, or if you wanted $$a as the variable and then the [1] index from that variable. The syntax for resolving this ambiguity is: ${$a[1]} for the first case and ${$a}[1] for the second.
Avvertimento |
Please note that variable variables cannot be used with PHP's Superglobal arrays within functions or class methods. |
When a form is submitted to a PHP script, the information from that form is automatically made available to the script. There are many ways to access this information, for example:
Depending on your particular setup and personal preferences, there are many ways to access data from your HTML forms. Some examples are:
Esempio 12-9. Accessing data from a simple POST HTML form
|
Using a GET form is similar except you'll use the appropriate GET predefined variable instead. GET also applies to the QUERY_STRING (the information after the '?' in a URL). So, for example, http://www.example.com/test.php?id=3 contains GET data which is accessible with $_GET['id']. See also $_REQUEST and import_request_variables().
Nota: Superglobal arrays, like $_POST and $_GET, became available in PHP 4.1.0
As shown, before PHP 4.2.0 the default value for register_globals was on. And, in PHP 3 it was always on. The PHP community is encouraging all to not rely on this directive as it's preferred to assume it's off and code accordingly.
Nota: The magic_quotes_gpc configuration directive affects Get, Post and Cookie values. If turned on, value (It's "PHP!") will automagically become (It\'s \"PHP!\"). Escaping is needed for DB insertion. See also addslashes(), stripslashes() and magic_quotes_sybase.
PHP also understands arrays in the context of form variables (see the related faq). You may, for example, group related variables together, or use this feature to retrieve values from a multiple select input. For example, let's post a form to itself and upon submission display the data:
Esempio 12-10. More complex form variables
|
In PHP 3, the array form variable usage is limited to single-dimensional arrays. As of PHP 4, no such restriction applies.
When submitting a form, it is possible to use an image instead of the standard submit button with a tag like:
When the user clicks somewhere on the image, the accompanying form will be transmitted to the server with two additional variables, sub_x and sub_y. These contain the coordinates of the user click within the image. The experienced may note that the actual variable names sent by the browser contains a period rather than an underscore, but PHP converts the period to an underscore automatically.
PHP transparently supports HTTP cookies as defined by Netscape's Spec. Cookies are a mechanism for storing data in the remote browser and thus tracking or identifying return users. You can set cookies using the setcookie() function. Cookies are part of the HTTP header, so the SetCookie function must be called before any output is sent to the browser. This is the same restriction as for the header() function. Cookie data is then available in the appropriate cookie data arrays, such as $_COOKIE, $HTTP_COOKIE_VARS as well as in $_REQUEST. See the setcookie() manual page for more details and examples.
If you wish to assign multiple values to a single cookie variable, you may assign it as an array. For example:
<?php setcookie("MyCookie[foo]", 'Testing 1', time()+3600); setcookie("MyCookie[bar]", 'Testing 2', time()+3600); ?> |
That will create two separate cookies although MyCookie will now be a single array in your script. If you want to set just one cookie with multiple values, consider using serialize() or explode() on the value first.
Note that a cookie will replace a previous cookie by the same name in your browser unless the path or domain is different. So, for a shopping cart application you may want to keep a counter and pass this along. i.e.
Esempio 12-11. A setcookie() example
|
Typically, PHP does not alter the names of variables when they are passed into a script. However, it should be noted that the dot (period, full stop) is not a valid character in a PHP variable name. For the reason, look at it:
<?php $varname.ext; /* invalid variable name */ ?> |
For this reason, it is important to note that PHP will automatically replace any dots in incoming variable names with underscores.
Because PHP determines the types of variables and converts them (generally) as needed, it is not always obvious what type a given variable is at any one time. PHP includes several functions which find out what type a variable is, such as: gettype(), is_array(), is_float(), is_int(), is_object(), and is_string(). See also the chapter on Types.
Una costante è un identificatore (nome) per un valore. Come si può intuire, tale valore non può cambiare durante l'esecuzione dello script (fanno eccezione le costanti magiche, che, in realtà, non sono costanti). Una costante è "case-sensitive" per default. È convenzione comune che i nomi di costante siano sempre maiuscoli.
In PHP il nome di una costante segue le regole di qualsiasi "etichetta". Un nome di costante valido inizia con una lettera o underscore, seguita da un numero qualsiasi di caratteri alfanumerici o underscore. L'espressione regolare che esprime questa convenzione è: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*
Esempio 13-1. Nomi di costanti validi ed errati
|
Nota: In questo contesto una lettera è a-z, A-Z e i caratteri ASCII dal 127 al 255 (0x7f-0xff).
Come le superglobals, costante è sempre globale. Si può accedere alle costanti da qualsiasi punto dello script senza tenere conto della visibilità. Per maggiori dettagli sulla visibilità, leggere la sezione variable scope.
È possibile definire una variabile utilizzando la funzione define(). Una volta definita, a una costante non è possibile cambiare il valore o eliminarla.
Le costanti possono contenere solo dati di tipo scalare (boolean, integer, float e string).
Per ottenere il valore di una costante è sufficiente specificarne il nome. A differenza delle variabili, non è necessario anteporre il simbolo $ al nome di una variabile. Si può anche utilizzare la funzione constant(), per leggere il valore di una costante, nel caso in cui se ne ottenga dinamicamente il nome. Si utilizzi get_defined_constants() per ottenere una lista delle variabili definite.
Nota: Costanti e variabili (globali) si trovano in un "namespace" differente. Questo implica che generalmente TRUE e $TRUE sono differenti.
Se si utilizza il nome di una costante che non è definita, PHP assume che detto valore sia il nome della costante stessa, come se si fosse inserito il testo nel nome . Quando ciò accade PHP segnala il problema con un E_NOTICE. Vedere anche il capitolo del manuale sul perchè $foo[bar] è errata (a meno che prima non definisca bar come costante con define()). Per sapere se una costante è definita, si può utilizzare la funzione defined().
Di seguito sono riportate le principali differenze rispetto le variabili:
Le costanti non iniziano con il segno del dollaro ($);
Le costanti possono essere definite solo con la funzione define() e non tramite assegnazione;
Le costanti possono essere definite e utilizzate ovunque senza seguire le regole di visibilità;
Una volta impostate, le costanti non posso essere redefinite e ne annullate;
Le costanti possono essere solo valori scalari;
Il PHP mette a disposizione ad ogni script diverse costanti predefinite disponibili a tutti gli script. Alcune di queste, tuttavia, sono create dai vari moduli, e, pertanto, saranno disponibili solo quando questi moduli sono caricati, sia dinamicamente sia staticamente.
Esistono cinque costanti magiche il cui valore cambia in base al contesto in cui sono utilizzate. Ad esempio, il valore di __LINE__ dipende da quale linea si trova nel momento in cui è richiamata. Queste costanti speciali sono 'case-insensitive' e sono:
Tabella 13-1. Le costanti "magiche" del PHP
Nome | Descrizione |
---|---|
__LINE__ | Il numero di linea corrente. |
__FILE__ | Il nome e percorso assoluto del file. Se viene utilizzata all'interno di un'include, la costante restituisce il nome del file incluso. Dal PHP 4.0.2, __FILE__ contiene sempre il percorso assoluto del file, mentre nelle versioni precedenti, in base alle circostanze, poteva contenere il percorso relativo. |
__FUNCTION__ | Nome della funzione. (Aggiunta nel PHP 4.3.0.) Dal PHP 5 questa costante restituisce il nome della funzione così come è stato dichiarato (rispettando le lettere maiuscole). In PHP 4 è sempre minuscolo. |
__CLASS__ | Nome della classe. (Aggiunta nel PHP 4.3.0.). Dal PHP 5 questa costante restituisce il nome della classe così come è stato dichiarato (rispettando le lettere maiuscole). In PHP 4 è sempre minuscolo. |
__METHOD__ | Nome del metodo della classe. (Aggiunta nel PHP 5.0.0.). Questa costante restituisce il nome del metodo così come è stato dichiarato (rispettando le lettere maiuscole). |
Vedere anche get_class(), get_object_vars(), file_exists() e function_exists().
Expressions are the most important building stones of PHP. In PHP, almost anything you write is an expression. The simplest yet most accurate way to define an expression is "anything that has a value".
The most basic forms of expressions are constants and variables. When you type "$a = 5", you're assigning '5' into $a. '5', obviously, has the value 5, or in other words '5' is an expression with the value of 5 (in this case, '5' is an integer constant).
After this assignment, you'd expect $a's value to be 5 as well, so if you wrote $b = $a, you'd expect it to behave just as if you wrote $b = 5. In other words, $a is an expression with the value of 5 as well. If everything works right, this is exactly what will happen.
Slightly more complex examples for expressions are functions. For instance, consider the following function:
Assuming you're familiar with the concept of functions (if you're not, take a look at the chapter about functions), you'd assume that typing $c = foo() is essentially just like writing $c = 5, and you're right. Functions are expressions with the value of their return value. Since foo() returns 5, the value of the expression 'foo()' is 5. Usually functions don't just return a static value but compute something.
Of course, values in PHP don't have to be integers, and very often they aren't. PHP supports four scalar value types: integer values, floating point values (float), string values and boolean values (scalar values are values that you can't 'break' into smaller pieces, unlike arrays, for instance). PHP also supports two composite (non-scalar) types: arrays and objects. Each of these value types can be assigned into variables or returned from functions.
PHP takes expressions much further, in the same way many other languages do. PHP is an expression-oriented language, in the sense that almost everything is an expression. Consider the example we've already dealt with, '$a = 5'. It's easy to see that there are two values involved here, the value of the integer constant '5', and the value of $a which is being updated to 5 as well. But the truth is that there's one additional value involved here, and that's the value of the assignment itself. The assignment itself evaluates to the assigned value, in this case 5. In practice, it means that '$a = 5', regardless of what it does, is an expression with the value 5. Thus, writing something like '$b = ($a = 5)' is like writing '$a = 5; $b = 5;' (a semicolon marks the end of a statement). Since assignments are parsed in a right to left order, you can also write '$b = $a = 5'.
Another good example of expression orientation is pre- and post-increment and decrement. Users of PHP and many other languages may be familiar with the notation of variable++ and variable--. These are increment and decrement operators. In PHP/FI 2, the statement '$a++' has no value (is not an expression), and thus you can't assign it or use it in any way. PHP enhances the increment/decrement capabilities by making these expressions as well, like in C. In PHP, like in C, there are two types of increment - pre-increment and post-increment. Both pre-increment and post-increment essentially increment the variable, and the effect on the variable is identical. The difference is with the value of the increment expression. Pre-increment, which is written '++$variable', evaluates to the incremented value (PHP increments the variable before reading its value, thus the name 'pre-increment'). Post-increment, which is written '$variable++' evaluates to the original value of $variable, before it was incremented (PHP increments the variable after reading its value, thus the name 'post-increment').
A very common type of expressions are comparison expressions. These expressions evaluate to either FALSE or TRUE. PHP supports > (bigger than), >= (bigger than or equal to), == (equal), != (not equal), < (smaller than) and <= (smaller than or equal to). The language also supports a set of strict equivalence operators: === (equal to and same type) and !== (not equal to or not same type). These expressions are most commonly used inside conditional execution, such as if statements.
The last example of expressions we'll deal with here is combined operator-assignment expressions. You already know that if you want to increment $a by 1, you can simply write '$a++' or '++$a'. But what if you want to add more than one to it, for instance 3? You could write '$a++' multiple times, but this is obviously not a very efficient or comfortable way. A much more common practice is to write '$a = $a + 3'. '$a + 3' evaluates to the value of $a plus 3, and is assigned back into $a, which results in incrementing $a by 3. In PHP, as in several other languages like C, you can write this in a shorter way, which with time would become clearer and quicker to understand as well. Adding 3 to the current value of $a can be written '$a += 3'. This means exactly "take the value of $a, add 3 to it, and assign it back into $a". In addition to being shorter and clearer, this also results in faster execution. The value of '$a += 3', like the value of a regular assignment, is the assigned value. Notice that it is NOT 3, but the combined value of $a plus 3 (this is the value that's assigned into $a). Any two-place operator can be used in this operator-assignment mode, for example '$a -= 5' (subtract 5 from the value of $a), '$b *= 7' (multiply the value of $b by 7), etc.
There is one more expression that may seem odd if you haven't seen it in other languages, the ternary conditional operator:
If the value of the first subexpression is TRUE (non-zero), then the second subexpression is evaluated, and that is the result of the conditional expression. Otherwise, the third subexpression is evaluated, and that is the value.
The following example should help you understand pre- and post-increment and expressions in general a bit better:
<?php function double($i) { return $i*2; } $b = $a = 5; /* assign the value five into the variable $a and $b */ $c = $a++; /* post-increment, assign original value of $a (5) to $c */ $e = $d = ++$b; /* pre-increment, assign the incremented value of $b (6) to $d and $e */ /* at this point, both $d and $e are equal to 6 */ $f = double($d++); /* assign twice the value of $d before the increment, 2*6 = 12 to $f */ $g = double(++$e); /* assign twice the value of $e after the increment, 2*7 = 14 to $g */ $h = $g += 10; /* first, $g is incremented by 10 and ends with the value of 24. the value of the assignment (24) is then assigned into $h, and $h ends with the value of 24 as well. */ ?> |
Some expressions can be considered as statements. In this case, a statement has the form of 'expr' ';' that is, an expression followed by a semicolon. In '$b=$a=5;', $a=5 is a valid expression, but it's not a statement by itself. '$b=$a=5;' however is a valid statement.
One last thing worth mentioning is the truth value of expressions. In many events, mainly in conditional execution and loops, you're not interested in the specific value of the expression, but only care about whether it means TRUE or FALSE. The constants TRUE and FALSE (case-insensitive) are the two possible boolean values. When necessary, an expression is automatically converted to boolean. See the section about type-casting for details about how.
PHP provides a full and powerful implementation of expressions, and documenting it entirely goes beyond the scope of this manual. The above examples should give you a good idea about what expressions are and how you can construct useful expressions. Throughout the rest of this manual we'll write expr to indicate any valid PHP expression.
Un operatore è un qualcosa che si posiziona tra uno o più valori (od espressioni, in gergo tecnico) e produce un'altro valore (in modo tale che la costruzione stessa diventi a sua volta un'espressione). In questo modo si può considerare operatori le funzioni o costruzioni che restituiscono valori (tipo print), e quelle che non restituiscono nulla (come echo) possono essere considerate come altro tipo di funzione.
Esistono tre tipi di operatori. Una tipologia sono gli operatori unari, i quali richiedono un solo valore, ad esempio ! (l'operatore di negazione) oppure ++ (l'operatore di autoincremento). Nel secondo gruppo troviamo gli operatori binari; questi costituiscono la maggior parte degli operatori disponibili in PHP, un e elenco di questi è presente alla sezione Precednza degli operatori.
Il terzo gruppo è costituito dal operatore ternario: ?:. Questo si può utilizzare per selezionare un espressione tra due possibili, in base ad una terza; piuttosto che dovere scegliere tra due righe di istruzioni o diversi percorsi di esecuzione. Racchiudere l'operatore ternario tra parentesi tonde è una buona idea.
La precedenza di un operatore specifica come esso tenga legate assieme "strettamente" due espressioni. Per esempio, nell'espressione 1 + 5 * 3, la risposta è 16 e non 18 perché l'operatore di moltiplicazione ("*") ha una precedenza più alta rispetto all'operatore di addizione ("+"). Le parentesi possono essere usate per forzare la precedenza, se necessario. Per esempio: (1 + 5) * 3 viene valutata 18. Se la precedenza tra gli operatori è simile, si utilizza l'associazione da sinistra a destra.
La seguente tabella fornisce una lista della precedenza degli operatori con gli operatori a più alta precedenza elencati prima. Gli operatori presenti nella medesima linea hanno uguale precedenza, in questi casi la loro associativià decide l'ordine con cui sono valutati.
Tabella 15-1. Precedenza degli operatori
Associatività | Operatori | Informazioni aggiuntive |
---|---|---|
non associativi | new | new |
destra | [ | array() |
destra | ! ~ ++ -- (int) (float) (string) (array) (object) @ | incremento/decremento |
destra | ! ~ + - (int) (float) (string) (array) (object) @ | tipi |
sinistra | * / % | operatori aritmetici |
sinistra | + - . | operatori aritmetici e operatori su stringhe |
sinistra | << >> | operatori sui bit |
non associativi | < <= > >= | operatori di confronto |
non associativi | == != === !== | operatori di confronto |
sinistra | & | operatori sui bit e riferimenti |
sinistra | ^ | operatori sui bit |
sinistra | | | operatori sui bit |
sinistra | && | operatori logici |
sinistra | || | operatori logici |
sinistra | ? : | Operatore ternario |
sinistra | = += -= *= /= .= %= &= |= ^= ~= <<= >>= | operatori di assegnazione |
sinistra | and | operatori logici |
sinistra | xor | operatori logici |
sinistra | or | operatori logici |
sinistra | , | diversi usi |
L'associazione a sinistra indica che l'espressione viene valutata da sinistra verso destra, l'associazione destra indica il contrario.
Nota: Sebbene ! abbia una maggiore pecedenza rispetto a =, il PHP cintinua a permetter espressioni tipo la seguente: if (!$a = foo()), in questo caso l'output di foo() viene inserito in $a.
Ricordate l'aritmetica di base dalla scuola? Questi funzionano proprio come quelli.
Tabella 15-2. Operatori aritmetici
Esempio | Nome | Risultato |
---|---|---|
-$a | Negazione | Opposto di $a. |
$a + $b | Addizione | La somma di $a e $b. |
$a - $b | Sottrazione | La differenza di $a e $b. |
$a * $b | Moltiplicazione | il prodotto di $a e $b. |
$a / $b | Divisione | Quoziente di $a e $b. |
$a % $b | Modulo | Il resto di $a diviso da $b. |
L'operatore di divisione ("/") restituisce un valore float in ogni caso, anche se i due operandi sono interi (oppure stringhe che vengono convertite in interi).
Nota: Il resto $a % $b è negativo per $a negativo.
Vedere anche le pagine del manuale sulle funzioni matematiche.
L'operatore di base dell'assegnazione è "=". La vostra prima inclinazione potrebbe essere di pensare che ciò sia come "uguale a". No. Esso significa realmente che l'operando a sinistra assume il valore dell'espressione a destra (ciò significa, "assegna il valore a").
Il valore di un'espressione di assegnazione è il valore assegnato. Cioè il valore di "$a = 3" è 3. Questo vi permette di fare qualche trucchetto:
In aggiunta all'operatore di base dell'assegnazione, ci sono gli "operatori combinati" per tutta l'aritmetica binaria e gli operatori di stringa che vi consentono di usare un valore in un'espressione e poi impostare il suo valore al risultato di quell'espressione. Per esempio:
<?php $a = 3; $a += 5; // imposta $a a 8, come se avessimo detto: $a = $a + 5; $b = "Ciao "; $b .= "Lì!"; // imposta $b a "Ciao Lì!", proprio come $b = $b . "Lì!"; ?> |
Notare che l'assegnazione copia la variabile originale alla nuova (assegnazione per valore), così i cambiamenti ad una non si verificheranno nell' altra. Ciò può anche avere rilevanza se avete bisogno di copiare qualcosa come un grande array in un ciclo molto stretto. Dal PHP 4 viene supportato l'assegnazione per riferimento, usando la sintassi $var = &$othervar;, ma ciò non è possibile in PHP 3. 'L'assegnazione per riferimento' vuol dire che entrambe le variabili finiscono con il puntare agli stessi dati, e nulla è copiato in nessun posto. Per ulteriori approfondimenti sui riferimenti, consultare References explained.
Gli operatori bitwise vi permettono di alterare bit specifici in posizione on oppure off. Se entrambi i parametri di sinistra e destra sono stringhe, l'operatore bitwise opererà sui caratteri ASCII della stringa.
<?php echo 12 ^ 9; // L'output è '5' echo "12" ^ "9"; // L'output è il carattere Backspace (ascii 8) // ('1' (ascii 49)) ^ ('9' (ascii 57)) = #8 echo "hallo" ^ "hello"; // L'output è il valore ascii #0 #4 #0 #0 #0 // 'a' ^ 'e' = #4 ?> |
Tabella 15-3. Operatori bitwise
Esempio | Nome | Risultato |
---|---|---|
$a & $b | And | Sono impostati ad ON i bit che sono ON sia in $a che in $b. |
$a | $b | Or | Sono impostati ad ON i bit che sono ON in $a oppure in $b. |
$a ^ $b | Xor | Sono impostati ad ON i bit che sono ON in $a oppure in $b na non quelli che sono entrambi ON. |
~ $a | Not | Sono impostati ad ON i bit che sono OFF in $a, e viceversa. |
$a << $b | Shift left | Sposta i bit di $a a sinistra di $b passi (ogni passo significa "moltiplica per due") |
$a >> $b | Shift right | Sposta i bit di $a a destra di $b passi (ogni passo significa "dividi per due") |
Avvertimento |
Non spostare a destra per più di 32 bit sui sistemi a 32 bit. Non spostare a sinistra nei casi in cui il risultato è un numero più lungo di 32 bit. |
Gli operatori di confronto, come suggerisce il loro nome, permettono di confrontare due valori. Può essere interessante vedere la tabella di raffronto dei tipi, dato che mostra esempi di vari confronti tra i tipi di variabili.
Tabella 15-4. Operatori di confronto
Esempio | Nome | Risultato |
---|---|---|
$a == $b | Uguale | TRUE se $a è uguale a $b. |
$a === $b | Identico | TRUE se $a è uguale a $b, ed essi sono dello stesso tipo. (Dal PHP 4) |
$a != $b | Diversi | TRUE se $a è diverso da $b. |
$a <> $b | Diversi | TRUE se $a è diverso da $b. |
$a !== $b | Non identici | TRUE se $a è diverso da $b, o se essi non sono dello stesso tipo. (Dal PHP 4) |
$a < $b | Minore | TRUE se $a è strettamente minore di $b. |
$a > $b | Maggiore | TRUE se $a è strettamente maggiore di $b. |
$a <= $b | Minore o uguale | TRUE se $a è minore o uguale a $b. |
$a >= $b | Maggiore o uguale | TRUE se $a è maggiore o uguale a $b. |
Se si confronta interi con stringhe, la stringa viene convertita in numero. Se si confronta due stringhe numeriche, queste vengono confrontate come interi. Queste regole valgono anche per l'istruzione switch.
<?php var_dump(0 == "a"); // 0 == 0 -> true var_dump("1" == "01"); // 1 == 1 -> true switch ("a") { case 0: echo "0"; break; case "a": // mai raggiunta perchè "a" è già riconosciuta come 0 echo "a"; break; } ?> |
Se i tipi di operarandi utilizzati differiscono, il confronto viene svolto nell'ordine indicato della seguente tabella.
Tabella 15-5. Confronti con differenti tipi
Tipo dell'operando 1 | Tipo dell'operando 2 | Risultato |
---|---|---|
null oppure string | string | Si converte NULL in "", confronto numerico o lessicale |
bool oppure null | qualsiasi | Convertito in bool, FALSE < TRUE |
object | object | Le classi predefinite possono avere la propria funzione di confronto, differenti classi non sono confrontabili, classi uguali - hanno le medesime proprietà di confronto delle matrici (PHP 4), pre il PHP 5 vedere qui per maggiori spiegazioni. |
string, resource oppure number | string, resource oppure number | Stringhe e risorse sono converti in numeri, confronto matematico |
array | array | La matrice con meno membri è più piccola, se la chiave dell'operando 1 non si trova nell'operando 2 allora le matrici non si possono confrontare, in altri casi il confronto avviene valore per valore (vedere l'esempio seguente) |
array | qualsiasi | array è sempre più grande |
object | qualsiasi | object è sempre più grande |
Esempio 15-2. Trascrizione del confronto standard tra matrici
|
Vedere anche strcasecmp(), strcmp(), Array operators, e la sezione del manuale su Types.
Un'altro operatore condizionale è l'operatore ternario "?:".
Nota: Si noti che l'operatore ternario è un'istruzione, e non viene valutato come variabile, ma come risultato di un'istruzione. Questo è importante da sapere nel caso si desideri restituire una variabile per riferimento. La riga return $var == 42 ? $a : $b; in una funzione che restituisce per riferimento non funzionerà e, nelle ultime versioni di PHP, genererà un warning.
PHP supporta un operatore di controllo dell'errore: il carattere at (@). Quando prefisso ad una espressione in PHP, qualunque messaggio di errore che potesse essere generato da quella espressione sarà ignorato.
Se la caratteristica track_errors è abilitata, qualsiasi messaggio di errore generato dall'espressione sarà salvato nella variabile globale $php_errormsg. Questa variabile sarà sovrascritta ad ogni errore, così controllatela subito se volete usarla.
<?php /* Errore di file intenzionale */ $my_file = @file ('file_inesistente') or die ("Apertura del file fallita: l'errore è '$php_errormsg'"); // questo funziona per qualsiasi espressione, non solo funzioni: $value = @$cache[$key]; // non verrà generata una notifica se l'indice $key non esiste. ?> |
Nota: L'operatore @ funziona solo sulle espressioni. Una semplice regola è: se potete prendere il valore di qualcosa, potete anteporre ad esso l'operatore @. Per esempio, potete anteporre esso a variabili, funzioni e chiamate ad include(), costanti, e così via. non potete anteporre esso a definizioni di funzioni o classi, o strutture condizionali come if e foreach, e così via.
Vedere anche error_reporting() e la sezione del manuale Gestione degli errori e funzioni di log.
Avvertimento |
Attualmente il prefisso operatore di controllo dell'errore "@" disabiliterà la restituzione di errori per errori critici che interromperanno l'esecuzione dello script. Tra le altre cose, questo significa che se state usando "@" per sopprimere errori da una certa funzione ed essa non è disponibile oppure è stata scritta male, lo script terminerà senza dare indicazioni sul perché. |
PHP supporta un operatore di esecuzione: backticks (``). Notare che quelli non sono apostrofi! PHP cercherà di eseguire il contenuto dei backticks come comando di shell; sarà restituito l'output (i.e., non sarà semplicemente esportato come output; può essere assegnato ad una variabile). L'uso dell'operatore backtick è identico alla funzione shell_exec().
Nota: L'operatore backtick è disabilitato quando è abilitata modalità sicura oppure quando è disabilitata shell_exec().
Vedere anche la sezione del manuale Funzioni per l'esecuzione di programmi, popen(), proc_open() e Utilizzo del PHP da linea di comando.
PHP supporta lo stile C degli operatori di pre- e post-incremento e decremento.
Nota: Gli operatori di incremento e decremento non agiscono sui valori boolean. Anche decrementare il valore NULL non ha effetti, ma incrementarlo darà come risultato 1.
Tabella 15-6. Operatori di incremento/decremento
Esempio | Nome | Effetto |
---|---|---|
++$a | Pre-incremento | Incrementa $a di una unità, inoltre restituisce $a. |
$a++ | Post-incremento | Restituisce $a, inoltre incrementa $a di una unità. |
--$a | Pre-decremento | Decrementa $a di una unità, inoltre restituisce $a. |
$a-- | Post-decremento | Restituisce $a, inoltre decrementa $a di una unità. |
Qui c'è un semplice script di esempio:
<?php echo "<h3>Postincrement</h3>"; $a = 5; echo "Dovrebbe essere 5: " . $a++ . "<br />\n"; echo "Dovrebbe essere 6: " . $a . "<br />\n"; echo "<h3>Pre-incremento</h3>"; $a = 5; echo "Dovrebbe essere 6: " . ++$a . "<br />\n"; echo "Dovrebbe essere 6: " . $a . "<br />\n"; echo "<h3>Post-decremento</h3>"; $a = 5; echo "Dovrebbe essere 5: " . $a-- . "<br />\n"; echo "Dovrebbe essere 4: " . $a . "<br />\n"; echo "<h3>Pre-decremento</h3>"; $a = 5; echo "Dovrebbe essere 4: " . --$a . "<br />\n"; echo "Dovrebbe essere 4: " . $a . "<br />\n"; ?> |
Il PHP segue le convenzioni di Perl e non del C quando tratta le operazioni matematiche sui caratteri. Ad esempio, in Perl 'Z'+1 restituisce 'AA', mentre in C 'Z'+1 restituisce '[' ( ord('Z') == 90, ord('[') == 91 ). Attenzione che le variabili con caratteri possono essere sommate e non sottratte.
Incrementare o decrementare valori booleani non ha effetto.
Tabella 15-7. Operatori logici
Esempio | Nome | Risultato |
---|---|---|
$a and $b | And | TRUE se entrambi $a e $b sono TRUE. |
$a or $b | Or | TRUE se uno tra $a o $b è TRUE. |
$a xor $b | Xor | TRUE se uno tra $a o $b è TRUE, ma non entrambi. |
! $a | Not | TRUE se $a non è TRUE. |
$a && $b | And | TRUE se entrambi $a e $b sono TRUE. |
$a || $b | Or | TRUE se uno tra $a o $b è TRUE. |
La ragione per le due differenti variazioni degli operatori "and" e "or" è che essi operano con differenti precedenze. (Vedere Precedenza degli operatori.)
Ci sono due operatori di stringa. Il primo è l'operatore di concatenazione ('.'), che restituisce la concatenazione dei suoi argomenti di destra e di sinistra. Il secondo è l'operatore di assegnazione concatenata ('.='), che accoda l'argomento sul lato destro all'argomento sul lato sinistro. Per favore consultare Operatori di assegnazione per maggiori informazioni.
<?php $a = "Ciao "; $b = $a . "Mondo!"; // ora $b contiene "Ciao Mondo!" $a = "Ciao "; $a .= "Mondo!"; // ora $a contiene "Ciao Mondo!" ?> |
Vedere anche le sezioni Stringhe e Funzioni per le stringhe nel manuale.
Tabella 15-8. Operatori per matrici
Esempio | Nome | Risultato |
---|---|---|
$a + $b | Unione | Unione di $a e $b. |
$a == $b | Uguaglianza | TRUE se $a e $b hanno le stesse coppie di chiavi/valori. |
$a === $b | Identità | TRUE se $a e $b hanno le stesse coppie di chiavi/valori nel medesimo ordine e dl medesimo tipo. |
$a != $b | Disuguaglianza | TRUE se $a non è uguale a $b. |
$a <> $b | Disuguaglianza | TRUE se $a non è uguale a $b. |
$a !== $b | Non-identità | TRUE se $a non è identico a $b. |
L'operatore + aggiunge la matrice di destra a quella di sinistra, mentre le chiavi duplicate NON sono sovrascritte.
<?php $a = array("a" => "apple", "b" => "banana"); $b = array("a" => "pear", "b" => "strawberry", "c" => "cherry"); $c = $a + $b; // Unione di $a e $b echo "Union of \$a and \$b: \n"; var_dump($c); $c = $b + $a; // Unione di $b e $a echo "Union of \$b and \$a: \n"; var_dump($c); ?> |
Union of $a and $b: array(3) { ["a"]=> string(5) "apple" ["b"]=> string(6) "banana" ["c"]=> string(6) "cherry" } Union of $b and $a: array(3) { ["a"]=> string(4) "pear" ["b"]=> string(10) "strawberry" ["c"]=> string(6) "cherry" } |
Gli elementi di una matrice sono uguali nel confronto se hanno le stesse chiavi e gli stessi valori.
Vedere anche la sezione del manuale sulle Matrici e Funzioni per le matrici.
PHP ha un unico operatore di tipo: instanceof. instanceof è utilizzato per determinare se un dato oggetto appartiene ad una data classe di oggetti.
L'operatore instanceof è stato introdotto in PHP 5. Prima di questo si utilizzava is_a(), ma ora is_a() viene sconsigliato in favore di instanceof.
<?php class A { } class B { } $thing = new A; if ($thing instanceof A) { echo 'A'; } if ($thing instanceof B) { echo 'B'; } ?> |
Poichè $thing è un oggetto di tipo A, ma non di tipo B, sarà eseguito soltanto il blocco dipendente dal tipo A:
A |
Vedere anche get_class() e is_a().
Qualsiasi script PHP è costituito da una serie di istruzioni. Una istruzione può essere un'assegnazione, una chiamata di funzione, un loop, una istruzione condizionale che non fa nulla (istruzione vuota). Le istruzioni terminano con un punto e virgola. Inoltre, le istruzioni si possono raggruppare in blocchi di istruzioni racchiudendole tra parentesi graffa. Un gruppo di istruzioni è, a sua volta, un'istruzione. Il presente capitolo descrive i differenti tipi di istruzioni.
Il costrutto if è una delle più importanti caratteristiche di qualsiasi linguaggio, incluso PHP. Permette l'esecuzione condizionata di frammenti di codice. La struttura di controllo if di PHP è simile a quella del linguaggio C:
Come descritto nella sezione sulle espressioni, espressione restiruirà il suo valore booleano. Se espressione vale TRUE, PHP eseguirà istruzione, e se essa vale FALSE - la ignorerà. Più informazioni riguardo i valori valutati FALSE possono essere trovati nella sezione 'Conversione in booleano' .
L'esempio che segue visualizzerà a è maggiore di b se $a sarà maggiore di $b:
Spesso sarà necessario eseguire più di una istruzione condizionale. Naturalmente non è necessario, utilizzare una singola clausola if per ciascuna istruzione. Si possono raggruppare diverse istruzioni in un singolo gruppo di istruzioni. Per esempio, il codice che segue visualizzerà a è maggiore di b se $a è maggiore di $b, e successivamente assegnerà il valore della variabile $a alla variabile $b:
Si possono annidare indefinitamente istruzioni if, la qual cosa fornisce piena flessibilità per l'esecuzione di istruzioni condizionali in diversi punti del programma.
Spesso è necessario eseguire un'istruzione se una proposizione è vera e un'altra istruzione se la proposizione è falsa. Per questo si usa la clausola else. else estende il costrutto if aggiungendo la possibilità di eseguire un'istruzione se l'espressione nel ramo if è FALSE. L'esempio che segue visualizzerà a è maggiore di b se $a è maggiore di $b e a NON è maggiore di b altrimenti:
Il ramo else viene eseguito solo se l'espressione nel ramo if è FALSE, e, nel caso ci fossero delle clausole elseif, solamente se le espressioni in esse contenute fossero anch'esse FALSE (vedere elseif).elseif, come è facile intuire, è una combinazione di if ed else. Analogamente ad else, estende if aggiungendo la possibilità di eseguire un'altra istruzione nel caso in cui l'espressione contenuta nel ramo if sia FALSE. Però, a differenza di else, si eseguirà l'istruzione alternativa solamente se l'espressione contenuta nel ramo elseif sarà TRUE. L'esempio che segue, visualizzerà a è maggiore di b, a è uguale a b oppure a è minore di b:
<?php if ($a > $b) { echo "a è maggiore di b"; } elseif ($a == $b) { echo "a è uguale a b"; } else { echo "a è minore di b"; } ?> |
Nel medesimo blocco if possono essere presenti più di una clausola elseif. Verrà eseguita l'istruzione del primo ramo elseif la cui espressione sia TRUE. In PHP è possibile scrivere 'else if' (due parole) e il significato sarà lo stesso di 'elseif' (una sola parola). Il significato sintattico è leggermente differente (se si ha familiarità con il linguaggio C, esso ha lo stesso comportamento) però al lato pratico l'effetto è il medesimo.
L'istruzione di un ramo elseif verrà eseguita solo se l'espressione del ramo if e le espressioni dei rami elseif precedenti sono FALSE, e se l'espressione del ramo elseif è TRUE.
PHP offre una sintassi alternativa per alcune delle sue strutture di controllo; vale a dire, if, while, for, foreach e switch. Fondamentalmente la sintassi alternativa consiste nel sostituire la prima parentesi graffa con il carattere "duepunti" (:) e la seconda parentesi graffa con endif;, endwhile;, endfor;, endforeach;, oppure endswitch;, rispettivamente.
Nell'esempio precedente, il blocco HTML "a è uguale a 5" è incluso nel ramo if scritto utilizzando la sintassi alternativa. Il blocco HTML verrà visualizzato solamente se $a è uguale a 5.
La sintassi alternativa si applica anche ad else ed elseif. Nell'esempio che segue si mostra come utilizzare la sintassi alternativa nel caso di un if con elseif ed else:
Il ciclo while è la forma di ciclo più semplice tra quelle possibili in PHP. Si comporta come la sua controparte nel linguaggio C. La forma di base di un ciclo while è la seguente:
Il significato di un ciclo while è semplice. Istruisce l'interprete PHP perchè esegua l'istruzione (o le istruzioni) in esso racchiuse, ripetutamente, fintanto che l'espressione contenuta nella clausola while ha valore TRUE. Il valore dell'espressione viene verificato ogni volta che il ciclo si ripete (iterazione), così che anche se il valore dell'espressione cambia durante l'esecuzione dell'istruzione, il ciclo non termina fino all'iterazione successiva. Ovviamente, se l'espressione nella clausola while ha valore FALSE dall'inizio, l'istruzione racchiusa nel blocco non verrà eseguita nemmeno una volta.
Come nel caso della struttura di controllo if, si possono raggruppare più istruzioni nello medesimo ciclo while racchiudendo le istruzioni in parentesi graffa, oppure utilizzando la sintassi alternativa:
Gli esempi seguenti sono identici e entrambi visualizzano i numeri da 1 a 10:
Il ciclo do-while è simile al ciclo while, con l'unica differenza che il valore dell'espressione viene controllato alla fine di ogni iterazione anzichè all'inizio. La differenza più importante rispetto a while è che la prima iterazione di un blocco do-while verrà sempre eseguita (il valore dell'espressione viene controllato alla fine del ciclo), mentre non sarà necessariamente eseguito in un ciclo while (il valore dell'espressione viene controllato all'inizio del ciclo, e se tale valore è FALSE dall'inizio, l'esecuzione del ciclo termina immediatamente).
È ammessa una sola sintassi per il ciclo do-while:
Il ciclo precedente verrà eseguito un'unica volta, dal momento che alla prima iterazione, quando si controlla l'espressione, il suo valore sarà FALSE ($i non è maggiore di 0) e il ciclo di esecuzioni, termina.
Chi ha utilizzato il linguaggio C conosce probabilmente un'altro modo di utilizzare il ciclo do-while, che permette di terminare l'esecuzione delle istruzioni durante l'esecuzione stessa, utilizzando do-while(0), e usando l'istruzione break. Il codice che segue esemplifica questa possibilità:
<?php do { if ($i < 5) { echo "i non è abbastanza grande"; break; } $i *= $factor; if ($i < $minimum_limit) { break; } echo "i è ok"; /* processa i */ } while (0); ?> |
Non vi preoccupate se l'esempio non è sufficientemente chiaro. Si possono scrivere ottimi programmi PHP anche senza far ricorso a questa 'possibilità'.
Il ciclo for è il ciclo più complesso tra quelli disponibili in PHP. Si comporta come la sua controparte nel linguaggio C. La sintassi di un clico for è:
Il valore della prima espressione (espressione1) viene verificato (eseguito) una sola volta incondizionatamente all'inizio del ciclo.
Ad ogni iterazione, si controlla il valore di espressione2. Se è TRUE, il ciclo prosegue e viene eseguita l'istruzione (o le istruzioni) contenuta nel blocco; se è FALSE, l'esecuzione del ciclo termina.
Al termine di ogni iterazione, si verifica (si esegue) il valore di espressione3.
Le due espressioni possono anche non essere presenti. Se non esiste espressione2 significa che il ciclo deve essere eseguito indefinitamente (PHP considera implicitamente che il suo valore è TRUE, come in C). Questa possibilità in fondo non è utile come può sembrare perchè obbliga a terminare il ciclo utilizzando l'istruzione break invece di utilizzare le espressioni booleane del ciclo for .
Si considerino gli esempi seguenti. In ciascun caso si visualizzeranno i numeri da 1 a 10:
<?php /* esempio 1 */ for ($i = 1; $i <= 10; $i++) { echo $i; } /* esempio 2 */ for ($i= 1; ; $i++) { if ($i > 10) { break; } echo $i; } /* esempio 3 */ $i = 1; for (; ; ) { if ($i > 10) { break; } echo $i; $i++; } /* esempio 4 */ for ($i = 1; $i <= 10; print $i, $i++) ; ?> |
Naturalmente il primo esempio sembra il migliore (o forse il quarto), ma l'uso del ciclo for senza espressioni può essere utile in molti casi.
PHP offre una sintassi alternativa (con i "punto e virgola") per i cicli for.
PHP 4 (non PHP 3) permette l'uso della struttura di controllo foreach, alla stessa maniera del linguaggio Perl e altri. Ciò semplicemente fornisce una facile metodo per attraversare un array. foreach funziona solo con le matrici e genera un errore se si tenta di utilizzarlo con variabili di tipo diffente oppure non inizializzate. Esistono due possibili notazioni sintattiche; la seconda è un'utile estensione della prima:
foreach(array_expression as $value) istruzione foreach(array_expression as $key => $value) i struzione |
La prima attraversa l'array dato da array_expression. Ad ogni ciclo, si assegna il valore dell'elemento corrente a $value e il puntatore interno avanza di una posizione (in modo tale che al ciclo successivo l'elemento corrente sarà il successivo elemento dell'array).
La seconda esegue lo stesso ciclo con la differenza che il valore dell'indice corrente viene assegnato ad ogni ciclo, alla variabile $key.
Dal PHP sono anche possibili cicli sugli oggetti.
Nota: All'inizio dell'esecuzione di un ciclo foreach il puntatore interno viene automaticamente posizionato nella prima posizione. Questo significa che non è necessario utilizzare la funzione reset() prima di un ciclo foreach.
Nota: A meno che la matrice non sia per riferimento, foreach agisce su una copia e non sulla matrice stessa. Pertanto il puntatore dell'array originale non viene modificato come accade utilizzando la funzione each() e le modifiche agli elementi dell'array non appaiono nell'array originale. Tuttavia il puntatore interno della matrice originale viene avanzato durante l'elaborazione della matrice. Se si assume che il ciclo foreach giunga al termine, allorasi avrà che il puntatore interno della matrcie sarà al termine della matrice stessa.
Dal PHP 5 si può modificare facilmente gli elementi di una matrice anteponendo & a $value with &. Questo assegna un riferimento anzichè copiare il valore.
Questo è possibile soltanto se l'array indicato può essere referenziato (ad esempio è una variabile).
Nota: foreach non offre la possibilità di annullare la generazione di messaggi d'errore utilizzando il carattere '@'.
Avete probabilmente notato che i due cicli seguenti sono identici da un punto di vista funzionale:
<?php $arr = array("one", "two", "three"); reset ($arr); while (list(, $value) = each ($arr)) { echo "Valore: $value<br />\n"; } foreach ($arr as $value) { echo "Valore: $value<br />\n"; } ?> |
<?php $arr = array("one", "two", "three"); reset ($arr); while (list($key, $value) = each ($arr)) { echo "Chiave: $key; Valore: $value<br />\n"; } foreach ($arr as $key => $value) { echo "Chiave: $key; Valore: $value<br>\n"; } ?> |
Di seguito, altri esempi per mostrare possibili utilizzi:
<?php /* esempio 1 foreach: solo il valore */ $a = array(1, 2, 3, 17); foreach ($a as $v) { echo "Valore corrente di \$a: $v.\n"; } /* esempio 2 foreach: valore (con la chiave stampata) */ $a = array(1, 2, 3, 17); $i = 0; /* solo per un proposito illustrativo */ foreach ($a as $v) { echo "\$a[$i] => $v.\n"; $i++; } /* esempio 3 foreach: chiave e valore */ $a = array( "uno" => 1, "due" => 2, "tre" => 3, "diciassette" => 17 ); foreach ($a as $k => $v) { echo "\$a[$k] => $v.\n"; } /* esempio 4 foreach: array multidimensionali */ $a = array(); $a[0][0] = "a"; $a[0][1] = "b"; $a[1][0] = "y"; $a[1][1] = "z"; foreach ($a as $v1) { foreach ($v1 as $v2) { echo "$v2\n"; } } /* esempio 5 foreach: array dinamici */ foreach (array(1, 2, 3, 4, 5) as $v) { echo "$v\n"; } ?> |
break termina l'esecuzione di una struttura for, foreach, while, do-while o switch.
break accetta un argomento opzionale che definisce, nel caso di cicli annidati, il livello del ciclo che è da interrompere.
<?php $arr = array ('uno', 'due', 'tre', 'quattro', 'stop', 'cinque'); while (list (, $val) = each ($arr)) { if ($val == 'stop') { break; /* Qui si può anche usare 'break 1;'. */ } echo "$val<br />\n"; } /* Uso dell'argomento opzionale. */ $i = 0; while (++$i) { switch ($i) { case 5: echo "At 5<br />\n"; break 1; /* Interrompe solo awitch. */ case 10: echo "At 10; quitting<br />\n"; break 2; /* Interrompe switch e while. */ default: break; } } ?> |
continue si utilizza per interrompere l'esecuzione del ciclo corrente e continuare con l'esecuzione dall'inizio del ciclo successivo dopo avere valutato la condizione.
Nota: Si noti che in PHP l'istruzione switch è considerata un'elemento di loop per gli scopi di continue.
continue accetta un argomento numerico opzionale che definisce, nel caso di cicli annidati, il numero di cicli da interrompere e da cui iniziare l'esecuzione dell'iterazione successiva.
<?php while (list($key, $value) = each ($arr)) { if (!($key % 2)) { // salta odd members continue; } do_something_odd($value); } $i = 0; while ($i++ < 5) { echo "Esterno<br />\n"; while (1) { echo " Centrale<br />\n"; while (1) { echo " Interno<br />\n"; continue 3; } echo "Questo non sarà mai stampato.<br />\n"; } echo "Nemmeno questo.<br />\n"; } ?> |
L'omissione del punto e virgola dopo continue può creare confuzione. Nel sseguente esempio si illustra cosa non di deve fare.
<?php for ($i = 0; $i < 5; ++$i) { if ($i == 2) continue print "$i\n"; } ?> |
Ci si può aspettare come risultato:
1 3 4 |
invece si avrà:
2 |
poichè il valore restituida da print() è int(1) e sembrerà il numero opzionale indicato in precedenza.
switch è simile a una serie di if sulla stessa espressione. In molti casi può essere necessario confrontare una variabile (o espressione) con differenti valori ed eseguire un differente blocco di istruzioni a seconda del valore di detta variabile. Questo è esattamente quello che fa la struttura di controllo switch.
Nota: Si noti che a differenza di altri linguaggi, l'istruzione continue si può utilizzare anche con switch ed ha un comportamento simile a break. Se si ha uno switch all'interno di un ciclo e si desidera continuare con il prossimo ciclo del loop esterno, utilizzare continue 2.
Gli esempi seguenti mostrano due maniere differenti di scrivere la stessa cosa, uno utilizzando una serie di istruzioni if ed elseif l'altro utilizzando switch:
È importante comprendere esattamente come viene eseguita la clausola switch per evitare errori. Un'istruzione switch esegue linea dopo linea le istruzioni in essa contenuta. All'inizio non viene eseguito alcun codice. Solamente quando incontra una clausola case il cui valore è uguale al valore della viariabile, PHP inizia ad eseguire le istruzioni contenute nel blocco case. PHP continua l'esecuzione delle istruzioni fino alla termine del blocco switch, o quando incontra un'istruzione break. Se non esiste alcuna istruzione break al termine di un blocco case PHP continuerà l'esecuzione delle istruzioni del blocco case successivo. Per esempio:
<?php switch ($i) { case 0: echo "i è uguale a 0"; case 1: echo "i è uguale a 1"; case 2: echo "i è uguale a 2"; } ?> |
In questo caso se $i è uguale a 0, PHP eseguirà tutte le istruzioni echo!. Se $i è uguale a 1, PHP eseguirà le ultime due echo. Si sarebbe ottenuto il comportamento atteso ( visualizzazione di 'i uguale a 2') solamente se $i è uguale a 2. Pertanto è importante non dimenticare l'istruzione break (anche se in alcuni casi potrà essere necessario non utilizzarla).
In un'istruzione switch, la condizione in parentesi viene valutata una sola volta e il risultato viene confrontato con ciascun ramo case. Utilizzando elseif, la condizione viene valutata una seconda volta. Se tale condizione è più complessa di un semplice confronto e/o è in un ciclo piuttosto pesante, l'uso di switch dovrebbe garantire un minor tempo di esecuzione.
Un blocco case può anche non contenere istruzioni, nel qual caso il controllo passa semplicemente al successivo blocco case.
<?php switch ($i) { case 0: case 1: case 2: print "i è minore di 3 ma non negativo"; break; case 3: print "i è 3"; } ?> |
Un blocco case speciale è il il blocco case di default. Uguaglia tutte le condizioni non uguagliate nei blocchi case precedenti e dev'essere l'ultimo blocco case. Per esempio:
<?php switch ($i) { case 0: echo "i è uguale a 0"; break; case 1: echo "i è uguale a 1"; break; case 2: echo "i è uguale a 2"; break; default: echo "i è diverso da 0, 1 o 2"; } ?> |
L'espressione in un ramo case può essere qualsiasi espressione il cui valore sarà di tipo intero, decimale, numerico e stringa. Array e oggetti (objects) non sono ammessi a meno che non siano dereferenziati a un tipo di dato semplice tra quelli precedentemente elencati.
Come per altre strutture di controllo è possibile utilizzare una sintassi alternativa. Si veda Sintassi alternativa per le strutture di controllo per ulteriori esempi.
Il costrutto declare si usa per definire direttive di esecuzione per blocchi di istruzioni. La sintassi è simile alla sintassi di altre strutture di controllo:
La sezione direttiva permette di impostare il comportamento del blocco declare . Attualmente è riconosciuta una sola direttiva: la direttiva ticks. (Fare riferimento più in basso per ulteriori informazioni relative alla direttiva ticks)
Verrà eseguita la parte istruzione del blocco declare -- come verrà eseguita e quali effetti collaterali emergeranno durante l'esecuzione potrà dipendere dalla direttiva impostata nel blocco direttiva.
L'istruzione declare può essere usata anche con visubilità globale, influenzando tutto il codice che la segue.
<?php // queste righe hanno il medesimo effetto: // si può utitlizzare in questo modo: declare(ticks=1) { // inserire tutto il codice } // o in questo modo declare(ticks=1); // inserire tutto il codice ?> |
Un tick è un evento che si verifica per ogni N istruzioni di basso livello eseguite dal parser all'interno del blocco declare. Il valore per N viene specificato usando ticks=N all'interno della sezione direttiva del blocco declare.
L'evento (o gli eventi) che si verifica su ogni tick è specificato usando register_tick_function(). Vedere l'esempio più in basso per ulteriori dettagli. Notare che può verificarsi più di un evento per ogni tick.
Esempio 16-3. Segue una sezione di codice PHP
|
I tick sono ben adeguati per il debugging, l'implementazione di semplici multitasking, backgrounded I/O e molti altri compiti.
Vedere anche register_tick_function() e unregister_tick_function().
Se viene chiamato all'interno di una funzione, l'istruzione return() termina immediatamente l'esecuzione della funzione corrente, e restituisce il suo argomento come valore della funzione chiamata. return() terminerà anche l'esecuzione di un'istruzione eval() o di un file di script.
Se viene chiamato in uno scope globale, allora verrà terrminata l'esecuzione del file di script corrente. Nel caso in cui il file di script corrente sia un file chiamato da include() o require(), il controllo viene passato al file chiamante. Ciononostante, se il file di script corrente è un file chiamato da include(), allora il valore dato da return() verrà restituito come valore della chiamata include(). Se viene chiamato return() all'interno del file di script principale, allora l'esecuzione dello script terminerà. Se il file di script corrente è stato nominato da auto_prepend_file o auto_append_file con le opzioni di configurazione nelphp.ini, allora l'esecuzione di quello script termina.
Per maggiori informazioni, consultare Valori restituiti.
Nota: Notate che poichè return() è un costrutto di linguaggio e non una funzione, le parentesi che circondano i suoi argomenti sono soltanto richieste se l'argomento contiene un'espressione. E' comune non utilizzarle quando si ritorna una variabile, ed inoltre il PHP ha meno lavoro da svolgere in questo caso.
Nota: Non si dovrebbe mai utilizzare le parantesi intorno alle variabili restituite quando sono restituite per riferimento, poichè non funzionerebbe. Per riferimento si possono restituire solo variabili, non il risultato di un'istruzione. Se si utilizza return ($a); non si restituisce una variabile, ma il risultato dell'espressione ($a) (che, ovviamente, è il valore di $a).
L'istruzione require() include e valuta il file specifico.
require() include e valuta uno specifico file. Informazioni dettagliate su come funziona quest'inclusione sono descritte nella documentazione di include().
require() e include() sono identiche in ogni senso eccetto per come esse trattano gli errori. include() produce un Warning mentre require() restituisce un Fatal Error. In altre parole, non esitate ad usare require() se volete che un file mancante fermi l'esecuzione della pagina. include() non si comporta in questo modo, lo script continuerà nonostante tutto. Assicuratevi di avere un appropriato include_path impostato a dovere.
Esempio 16-4. Esempio di base con require()
|
Vedere la documentazione di include() per più esempi.
Nota: Prima di PHP 4.0.2, si applica la seguente logica: require() tenterà sempre di leggere il file chiamato, anche se la riga su cui si trova non verrà mai eseguita. L'istruzione condizionale non avrà effetto su require(). Comunque, se la riga su cui si verifica require() non viene eseguita, non sarà eseguito nemmeno il codice del file incluso. Similmente, le strutture cicliche non avranno effetto sul comportamento di require(). Sebbene il codice contenuto nel file incluso è ancora soggetto a ciclo, require() stesso si verifica solo una volta.
Nota: Poichè questo è un costrutto del linguaggio e non una funzione, non può essere chiamato con le variabili funzione
Avvertimento |
la versione per Windows di PHP antecedente la 4.3.0 non supporta l'accesso remoto ai file da parte di questa funzione, anche se allow_url_fopen è abilitato. |
Vedere anche include(), require_once(), include_once(), eval(), file(), readfile(), virtual() e include_path.
L'istruzione include() include e valuta il file specificato.
La documentazione seguente si applica anche a require(). I due costrutti sono identici in ogni aspetto eccetto per come essi trattano gli errori. include() produce un Warning mentre require() restituisce un Fatal Error. In altre parole, usate require() se volete che un file mancante fermi l'esecuzione della pagina. include() non si comporta in questo modo, lo script continuerà nonostante tutto. Assicuratevi di avere un appropriato include_path impostato a dovere. Attenzione che nelle versioni di PHP antecedenti la release 4.3.5 errori di parsing nei file inclusi non bloccavano l'esecuzione. Da questa versione lo fanno.
I file da includere sono prima cercati nella include_path relativa rispetto alla directory di lavoro e quindi nella include_path relativa alla directory dello script. Ad esempio, se la include_path è impostata a ., e la directory di lavoro corrente è /www/, si può includere include/a.php e qui vi è include "b.php", il file b.php verrà prima cercato in /www/ e quindi in /www/include/. Se il nome del file inizia con ../, viene cercato solo nella include_path relativa alla directory di lavoro corrente.
Quando un file viene incluso, il codice che esso contiene eredita lo scope delle variabili della riga in cui si verifica l'inclusione. Qualsiasi variabile disponibile in quella riga nella chiamata al file sarà disponibile all'interno del file chiamato, da quel punto in avanti. Tuttavia tutte le funzioni a le classi definite all'interno di un file di include hanno visibilità glibale.
Esempio 16-5. Esempio di base con include()
|
Se l'inclusione si verifica dentro una funzione all'interno del file chiamato, allora tutto il codice contenuto nel file chiamato si comporterà come se esso sia stato definito all'interno di una funzione. Così, esso seguirà lo scope delle variabili di quella funzione.
Esempio 16-6. Inclusione all'interno di funzioni
|
Quando un file viene incluso, il parsing esce dalla modalità PHP e entra in modalità HTML all'inizio del file incluso, e riprende alla fine. Per questa ragione, qualunque codice all'interno del file incluso che dovrebbe essere eseguito come codice PHP deve essere incluso all'interno dei tag PHP validi di apertura e chiusura.
Se "URL fopen wrappers" nel PHP sono abilitati (come nella configurazione di default), potete specificare il file da includere usando un URL (via HTTP o altri wrapper supportati - vedere Appendice M per avere la lista dei protocolli supportati ) invece che un percorso locale. Se il server chiamato interpreta il file incluso come codice PHP, le variabili possono essere passate al file incluso usando una stringa di richiesta URL come con l'utilizzo di HTTP GET. Non è proprio parlare della stessa cosa includere il file e averlo ereditato dallo scope di variabili del file chiamante; lo script è stato attualmente eseguito su un server remoto e il risultato è poi stato incluso nello script locale.
Avvertimento |
la versione per Windows di PHP antecedente la 4.3.0 non supporta l'accesso remoto ai file da parte di questa funzione, anche se allow_url_fopen è abilitato. |
Esempio 16-7. include() attraverso HTTP
|
Poichè include() e require() sono speciali costrutti di linguaggio, dovete includerli all'interno di blocchi di istruzioni se si trovano in un blocco condizionale.
Trattamento dei valori restituiti: È possibile eseguire un'istruzione return() in un file incluso per terminare l'esecuzione di quel file e restituirlo allo script che l'ha chiamato. È anche possibile restituire valori dai file inclusi. Potete prendere il valore di una chiamata di inclusione come fareste con una normale funzione. Tuttavia questo non è possibile quando si include file remoti, a meno che l'output del file remoto non contenga tag di inizio e fine codice validi in PHP (come i file locali). Si possono dichiarare variabili all'interno di questi tag e queste saranno inserite nel punto in cui il file è stato incluso.
Poichè include() è un costrutto del linguaggio speciale, non richiede le parentesi per i propri argomenti. Fare attenzione quando lo si confronta i valori restituiti.
Nota: In PHP 3, return potrebbe non apparire in un blocco a meno che esso sia un blocco di funzione, nel qual caso return() si applica a quella funzione e non all'intero file.
$bar ha valore 1 perchè l'inclusione è stata eseguita con successo. Notare la differenza tra gli esempi sopra. Il primo usa return() all'interno di un file incluso mentre l'altro no. Se il file non può essere incluso la funzione restituisce FALSE e genera un messaggio di E_WARNING
Se esistono funzioni definite nel file di include, queste possono essere utilizzate nel file principale a prescindere se esse siano prima o dopo il return(). Se un file viene incluso due volte, il PHP 5 genera un errore fatale, poichè le funzioni sono già dichiarate, mentre il PHP 4 non considera le funzioni dichiarate dopo il return(). Si raccomanda di utilizzare include_once() invece di verificare se un file è già stato incluso ed uscire tramite condizione dal file incluso.
Un'altro metodo per "includere" file PHP in una variabile consiste nel catturarne l'output tramite le funzioni di controllo dell'output ed include(). Ad esempio:
Esempio 16-11. Utilizzo del buffering dell'output per inserire un file PHP in una stringa
|
Per includere automaticamente dei file negli script vedere i parametri auto_prepend_file e auto_append_file nel php.ini.
Nota: Poichè questo è un costrutto del linguaggio e non una funzione, non può essere chiamato con le variabili funzione
Vedere anche require(), require_once(), include_once(), readfile(), virtual(), e include_path.
L'istruzione require_once() include e valuta il file specificato durante l'esecuzione dello script. È un comportamento simile all'istruzione require(), con la sola differenza che se il codice di un file è stato già incluso, esso non sarà incluso nuovamente. Vedere la documentazione di require() per maggiori informazioni su come funziona quest'istruzione.
require_once() dovrebbe essere usato nei casi dove lo stesso file potrebbe essere incluso e valutato più di una volta durante una particolare esecuzione di uno script, e volete essere sicuri che esso sia incluso esattamente una volta per evitare problemi con la ridefinizione di funzioni, riassegnazione di valori a variabili, etc.
Per esempi sull'utilizzo di require_once() e include_once(), consultare il codice PEAR incluso nell'ultima distribuzione del codice sorgente di PHP.
Il valore restituito è simile a include(). Se il file è già stato incluso, la funzione restituisce TRUE.
Nota: require_once() è stato aggiunto in PHP 4.0.1pl2
Nota: Fare attenzione al fatto che il comportamento di require_once() e include_once() può non essere quello atteso in sistemi che non distinguono le maiuscole dalle minuscole (tipo Windows).
Questo comportamento è stato modificato in PHP 5 - il percorso viene normalizzato, in modo tale che C:\PROGRA~1\A.php diventa simile a C:\Program Files\a.php e quindi il file vine incluso solo una volta.
Esempio 16-12. require_once() non distingue tra maiuscole e minuscole in Windows
<?php require_once("a.php"); // questo include include a.php require_once("A.php"); // questo include a.php ancora, in Windows! (solo PHP 4) ?>
Avvertimento |
la versione per Windows di PHP antecedente la 4.3.0 non supporta l'accesso remoto ai file da parte di questa funzione, anche se allow_url_fopen è abilitato. |
Vedere anche: require(), include(), include_once(), get_required_files(), get_included_files(), readfile() e virtual().
L'istruzione include_once() include e valuta il file specificato durante l'esecuzione dello script. È un comportamento simile all'istruzione include(), con la sola differenza che se il codice di un file è stato già incluso, esso non sarà incluso nuovamente. Come suggerisce il nome, esso sarà incluso solo una volta.
include_once() dovrebbe essere usato nei casi dove lo stesso file potrebbe essere incluso e valutato più di una volta durante una particolare esecuzione di uno script, e volete essere sicuri che esso sia incluso esattamente una volta per evitare problemi con la ridefinizione di funzioni, riassegnazione di valori a variabili, etc.
Per maggiori esempi sull'utilizzo di require_once() e include_once(), consultare il codice PEAR incluso nell'ultima distribuzione del codice sorgente di PHP.
Il valore restituito è il simile a include(). Se il file è già stato incluso, la funzione restituisce TRUE.
Nota: include_once() è stato aggiunto in PHP 4.0.1pl2
Nota: Fare attenzione al fatto che il comportamento di include_once() e require_once() può non essere quello atteso in sistemi che non distinguono le maiuscole dalle minuscole (tipo Windows).
Questo comportamento è stato modificato in PHP 5 - il percorso viene normalizzato, in modo tale che C:\PROGRA~1\A.php diventa simile a C:\Program Files\a.php e quindi il file vine incluso solo una volta.
Esempio 16-13. include_once() non distingue tra maiuscole e minuscole in Windows
<?php include_once("a.php"); // questo include include a.php include_once("A.php"); // questo include a.php ancora, in Windows! (solo PHP 4) ?>
Avvertimento |
la versione per Windows di PHP antecedente la 4.3.0 non supporta l'accesso remoto ai file da parte di questa funzione, anche se allow_url_fopen è abilitato. |
Vedere anche include(), require(), require_once(), get_required_files(), get_included_files(), readfile() e virtual().
Una funzione può essere definita usando la seguente sintassi:
All'interno di una funzione può apparire qualunque codice PHP valido, persino altre funzioni e definizioni di classe.
In PHP 3, le funzioni devono essere definite prima di essere referenziate. Non esiste nessun requisito in PHP 4. Tranne quando una funzione è definita condizionalmente come illustrato nei due esempi seguenti.
Quando una funzione è definita in modo condizionale, come illustrato nei seguenti esempi, occorre che ne venga processata prima la definizione poi venga chiamata la funzione stessa.
Esempio 17-2. Funzioni condizionali
|
Esempio 17-3. Funzioni dentro a funzioni
|
Tutte le funzioni e le classi, in PHP, hanno visibilità globale - possono essere chiamate dall'esterno di una funzione anche se sono definite all'interno di questa e vice-versa.
PHP non supporta l'overloading di funzioni, non è possibile indefinire o ridefinire funzioni precedentemente dichiarate.
Nota: I nomi delle funzioni non distinguono tra maiuscolo e minuscolo, ma, solitamente, è buona norma richiamare le funzioni nel modo con cui sono state definite.
PHP 3 non supporta un numero variabile di argomenti per le funzioni, sebbene siano supportati gli argomenti di default (vedere Argomenti con valori di default per maggiori informazioni). PHP 4 li supporta entrambi: vedere Liste di argomenti a lunghezza variabile e i riferimenti alle funzioni func_num_args(), func_get_arg() e func_get_args() per maggiori informazioni.
In PHP è possibile utilizzare le chiamate ricorsive. Tuttavia si consiglia di evitare funzioni/metodi ricorsivi profondi oltre 100-200 livelli, potrebbero riempire lo stack e bloccare l'esecuzione dello script.
L'informazione può essere passata alle funzioni tramite la lista degli argomenti, che sono liste di espressioni delimitati dalla virgola.
PHP supporta il passaggio di argomenti per valore (comportamento di default), il passaggio per riferimento, e i valori di default degli argomenti. Le liste di argomenti di lunghezza varabile sono supportate solo in PHP 4 e successivi; vedere Liste di argomenti a lunghezza variabile e i riferimenti alle funzioni func_num_args(), func_get_arg(), e func_get_args() per maggiori informazioni. Un effetto simile può essere ottenuto in PHP 3 passando una array di argomenti alla funzione.
Di default, gli argomenti della funzione sono passati per valore (così se cambiate il valore dell'argomento all'interno della funzione , esso non cambierà fuori della funzione). Se volete permettere ad una funzione di modificare i suoi argomenti, dovete passarli per riferimento.
Se volete che una argomento sia passato sempre per riferimento ad una funzione, dovete anteporre un ampersand (&) al nome dell'argomento nella definizione della funzione:
Una funzione può definire valori predefiniti in stile C++ per argomenti scalari come segue:
L'output dal frammento di sopra è:
Sto facendo una tazza di cappuccino. Sto facendo una tazza di espresso. |
Anche il PHP permette di utilizzare matrici ed il tipo speciale NULL come valore di default, ad esempio:
Esempio 17-8. Utilizzo di tipi non scalari come valori di default
|
Il valore predefinito deve essere un'espressione costante, non (per esempio) una variabile, un membro di classe o una chiamata ad una funzione.
Da notare che quando vengono usati argomenti predefiniti, qualunque argomento predefinito dovrebbe essere a destra degli argomenti non-predefiniti; diversamente, le cose non funzioneranno come ci si aspetti. Si consideri il seguente frammento di codice:
L'output dell'esempio di sopra è:
Warning: Missing argument 2 in call to fare_lo_yogurt() in /usr/local/etc/httpd/htdocs/php3test/functest.html on line 41 Fare una vaschetta di fragola a. |
Ora, si confronti il codice di sopra con questo:
L'output di questo esempio è:
Fare una vaschetta di yogurt a fragola. |
Nota: Dal PHP 5 i valori di default possono essere passati per riferimento.
PHP 4 ha il supporto per le liste di argomenti a lunghezza variabile nelle funzioni definite dall'utente. Ciò è realmente abbastanza semplice, usando le funzioni func_num_args(), func_get_arg(), e func_get_args().
Non è richiesta una speciale sintassi, e le liste di argomenti possono ancora essere provviste esplicitamente con le definizioni di funzioni e si comporteranno normalmente.
I valori vengono restituiti usando l'istruzione opzionale return. Può essere restituito qualsiasi tipo, incluse liste ed oggetti. Ciò provoca l'interruzione dell'esecuzione della funzione immediatamente e la restituzione del controllo alla linea da cui è stata chiamata. Vedere return() per maggiori informazioni.
Esempio 17-11. Esempio di uso di return()
|
Non possono essere restituiti valori multipli da una funzione, ma risultati simili possono essere ottenuti restituendo una lista.
Per restituire un riferimento da una funzione, è necessario usare l'operatore di passaggio per riferimento & in entrambe le dichiarazioni di funzioni e quando viene assegnato il valore restituito ad una variabile:
Per maggiori informazioni sui riferimenti, consultare References Explained.
PHP supporta il concetto di funzioni variabili. Ciò significa che se un nome di variabile ha le parentesi accodate ad esso, PHP cercherà una funzione con lo stesso nome del valore della variabile, e cercherà di eseguirla. Tra le altre cose, ciò puo essere usato per implementare delle callbacks, tabelle di funzioni e così via.
Le funzioni variabili non funzionano con costrutti di linguaggio come echo(), print(), unset(), isset(), empty(), include(), require() e like. Occorre costruire una propria funzione per utilizzare questi costrutti come variabili per funzioni.
Esempio 17-14. Esempio di funzioni variabili
|
Tramite le funzioni variabili si può eseguire anche metodi di oggetti.
Vedere anche call_user_func(), variabili variabili e function_exists().
Il PHP possiede diverse funzioni e costrutti standard. Esistono, inoltre, funzioni che richiedono la compila di specifici moduli del PHP, altrimenti si ottiene l'errore "undefined function" errors. Ad esempio, per utilizzare le funzioni image, tipo imagecreatetruecolor(), occorre che il PHP sia compilato con il supporto GD. Oppure, per utilizzare mysql_connect() occorre che il PHP sia compilato con il supporto per MySQL Esistono anche diversi funzioni di base incluse in ogni versione del PHP tipo le funzioni stringa e per variabili. L'esecuzione di phpinfo() o di get_loaded_extensions() visualizzerà quali moduli sono caricati nel PHP. Inoltre si noti che diverse estensioni sono abilitate per default e che il manule PHP è suddiviso per estensione. Vedere i capitoli configurazione, installazione, ed i capitoli dei singoli moduli per avere maggiori dettagli su come configurare il PHP.
Come leggere e comprendere il prototipo di una funzione è spiegato nella sezione del manuale intitolata come leggere la definizione di una funzione. E' importante comprendere che cosa restituisce una funzione o se una funzione lavora direttamente sui dati passati. Ad esempio str_replace() restituisce la stringa modificata, mentre usort() lavora sulla variabile passata. Ciascuna pagina del manuale fornisce informazioni specifiche per ogni funzione tipo notizie sui parametri, modifiche di funzinamento, valori restituiti in caso di successo o di errore, ed altre informazioni disponibili. La conoscenza di queste differenze importanti è cruciale per la scrittura di codice PHP corretto.
Vedere anche function_exists(), the function reference, get_extension_funcs(), e dl().
Una classe è una collezione di variabili e funzioni che utilizzano queste variabili. Una classe si definisce usando la seguente sintassi:
<?php class Cart { var $items; // Articoli nel carrello // Aggiunge $num articoli di $artnr nel carrello function add_item ($artnr, $num) { $this->items[$artnr] += $num; } // Prende $num articoli di $artnr e li rimuove dal carrello function remove_item ($artnr, $num) { if ($this->items[$artnr] > $num) { $this->items[$artnr] -= $num; return true; } elseif ($this->items[$artnr] == $num) { unset($this->items[$artnr]); return true; } else { return false; } } } ?> |
Il codice definisce una classe chiamata Cart composta da un array associativo che archivia gli articoli nel carrello e due funzioni per aggiungere e rimuovere gli articoli dal carrello stesso.
Avvertimento |
NON spezzate una definizione di classe in più file o in più blocchi PHP. Si può anche EVITARE di spezzare la definizione di una classe in più blocchi PHP, a meno che la suddivisione non sia all'interno della dichiarazione di un metodo. Il seguente codice non funziona:
Tuttavia è permessa la seguente struttura:
|
Le seguenti note cautelative sono valide per PHP 4.
Attenzione |
Il nome stdClass è usato esclusivamente da Zend ed è riservato. Non è quindi possibile creare una classe chiamata stdClass in PHP. |
Attenzione |
I nomi di funzione __sleep e __wakeup sono riservati e magici nelle classi PHP. Non è possibile creare funzioni con questi nomi nelle classi definite dall'utente, a meno che non sia desiderata la funzionalità magica connessa a questi nomi. Si veda sotto per avere più informazioni. |
Attenzione |
PHP riserva tutti i nomi di funzione che iniziano con __ a funzioni magiche. Si suggerisce di non usare nomi di funzioni che utilizzano con i caratteri __ in PHP a meno che non si desideri implementare una funzionalità magica. |
In PHP 4, sono permesse inizializzazioni di variabili con valori costanti solamente grazie all'uso di var. Per inizializzare variabili con valori non-costanti, bisogna creare una funzione d'inizializzazione che è chiamata automaticamente all'istanziazione di un oggetto da una classe. Questo tipo di funzione si chiama costruttore (vedi sotto).
<?php class Cart { /* questo non funziona in PHP 4. */ var $todays_date = date("Y-m-d"); var $name = $firstname; var $owner = 'Fred ' . 'Jones'; /* E' permesso l'uso di matrici contenenti costanti */ var $items = array("VCR", "TV"); } /* Questo è corretto. */ class Cart { var $todays_date; var $name; var $owner; var $items; var $items = array("VCR", "TV"); function Cart() { $this->todays_date = date("Y-m-d"); $this->name = $GLOBALS['firstname']; /* etc ... */ } } ?> |
Le classi sono tipi del linguaggio, e sono modelli per variabili reali. Per creare una variabile oggetto si usa l'operatore new.
<?php $cart = new Cart; $cart->add_item("10", 1); $another_cart = new Cart; $another_cart->add_item("0815", 3); ?> |
Il codice sopra, genera gli oggetti $cart e $another_cart, dalla classe Cart. La funzione add_item() dell'oggetto $cart è chiamata per aggiungere una ricorrenza dell'articolo numero 10 a $cart. Ad $another_cart sono aggiunte 3 ricorrenze dell'articolo numero 0815.
Sia $cart che $another_cart dispongono delle funzioni add_item(), remove_item() e della variabile $items, ma per ogni oggetto queste sono funzioni e variabili sono distinte. Potete pensare agli oggetti come a qualcosa di simile alle directories di un filesystem. In un filesystem si possono avere due diversi files README.TXT, purchè siano in directories differenti. Così come in un filesystem dovete digitare il nome (percorso) completo per raggiungere un determinato file partendo da una directory toplevel, così dovete specificare il nome completo di una funzione o variabile che desiderate richiamare da un oggetto. Per PHP, la directory toplevel è il namespace globale dell'oggetto ed il separatore del pathname (/) è ->. Così $cart->items e $another_cart->items sono due diverse variabili che differiscono per il nome. Si noti che la variabile si chiama $cart->items, e non $cart->$items, questo perchè le variabili il PHP si scrivono con un unico simbolo di dollaro.
<?php // corretto con un singolo $ $cart->items = array("10" => 1); // non valido, perchè $cart->$items diventa $cart->"" $cart->$items = array("10" => 1); // corretto, ma non sempre può funzionare: // $cart->$myvar diventa $cart->items $myvar = 'items'; $cart->$myvar = array("10" => 1); ?> |
Quando si definisce una classe, non è possibile prevedere quale nome avrà l'oggetto istanziato nel programma. Quando la classe Cart è stata scritta, non si poteva prevedere che l'oggetto istanziato da essa si sarebbe potuto chiamare $cart o $another_cart. Quindi non è possibile scrivere $cart->items all'interno della classe Cart in fase di progettazione. Per poter accedere alle funzioni e alle variabili interne di una classe perciò si usa la pseudo-variabile $this che può essere letta come 'la mia\il mio' o 'di questo oggetto'. Quindi, '$this->items[$artnr] += $num' può essere letto come 'aggiungi $num al contatore $artnr al del mio array degli articoli' o 'aggiungi $num al contatore $artnr dell'array degli articoli di questo oggetto'.
Nota: La pseudo variabile $this di norma non è definita se il metodo in cui è utilizzata è richiamato staticamente. Tuttavia questa non è la regola: $this è definita se il metodo è chiamato staticamente da un'altro oggetto. In questo caso il valore di $this è l'oggetto chiamante. Tutto ciò viene illustrato dal seguente esempio:
<?php class A { function foo() { if (isset($this)) { echo '$this is defined ('; echo get_class($this); echo ")\n"; } else { echo "\$this is not defined.\n"; } } } class B { function bar() { A::foo(); } } $a = new A(); $a->foo(); A::foo(); $b = new B(); $b->bar(); B::bar(); ?>Il precedente esempio visualizzerà:
$this is defined (a) $this is not defined. $this is defined (b) $this is not defined.
Nota: Ci sono molte utili funzioni per manipolare classi ed oggetti. Se desiderate conoscerle potete dare un'occhiata alle Class/Object Functions.
Spesso si ha bisogno di avere classi con variabili e funzioni simili ad altre classi. É buona norma definire una classe in modo generico, sia per poterla riutilizzare spesso, sia per poterla adattare a scopi specifici.Per facilitare questa operazione, è possibile generare classi per estensione di altre classi. Una classe estesa o derivata ha tutte le variabili e le funzioni della classe di base (questo fenomeno è chiamato 'eredità', anche se non muore nessuno) più tutto ciò che viene aggiunto dall'estensione. Non è possibile che una sottoclasse, ridefinisca variabili e funzioni di una classe madre. Una classe estesa dipende sempre da una singola classe di base: l'eredità multipla non è supportata. Le classi si estendono usando la parola chiave 'extends'.
<?php class Named_Cart extends Cart { var $owner; function set_owner ($name) { $this->owner = $name; } } ?> |
Qui viene definita una classe Named_Cart che ha tutte le funzioni e variabili di Cart più la variabile $owner e la funzione set_owner(). Viene creato un carrello con nome con il metodo usato in precedenza, in più la classe estesa permette di settare o leggere il nome del carrello. Si possono usare variabili e funzioni sia di Cart che della sua estensione:
<?php $ncart = new Named_Cart; // Crea un carrello con nome $ncart->set_owner("kris"); // Assegna il nome al carrello print $ncart->owner; // stampa il nome del proprietario $ncart->add_item("10", 1); // (funzionalità ereditata da Cart) ?> |
La relazione mostrata è chiamata relazione "genitore-figlio". Si crea una classe di base, poi utilizzando extends si crea una nuova classe basata sulla classe genitore: la classe figlia. Successivamente si può usare la classe figlia come classe base per un'altra classe.
Nota: Una classe deve essere definita prima di essere utilizzata! Se si vuole la classe Named_Cart che estende la classe Cart, bisogna definire una classe Cart prima. Se si vuole creare un'altra classe chiamata Yellow_named_cart basata sulla classe Named_Cart bisogna definire la classe Named_Cart prima. Per farla breve: l'ordine di definizione delle classi è importante.
I costruttori sono funzioni che esistono in una classe e che sono chiamate automaticamente quando si crea una nuova istanza di una classe con new. In PHP 4, una funzione diventa un costruttore, quando ha lo stesso nome della classe. Se una classe non ha costruttore, allora si richiama il costruttore della classe base, se esiste.
Questo codice definisce una classe Auto_Cart, che non è altro che Cart più un costruttore che inizializza il carrello con una occorrenza dell'articolo numero "10" ogni volta che un nuovo Auto_Cart è creato con "new". I costruttori possono avere degli argomenti, e gli argomenti possono essere facoltativi, questo li rende molto versatili. Per poter usare una classe senza specificare parametri, tutti i parametri del costruttore devono essere resi facoltativi con valori di default.
<?php class Constructor_Cart extends Cart { function Constructor_Cart($item = "10", $num = 1) { $this->add_item ($item, $num); } } // Istanzia il vecchio e noioso carrello. $default_cart = new Constructor_Cart; // Un carrello nuovo ... $different_cart = new Constructor_Cart("20", 17); ?> |
E possibile utilizzare l'operatore @ per inibire gli errori provocati dal costruttore, es: @new.
<?php class A { function A() { echo "Sono il costtruttore di A.<br />\n"; } function B() { echo "Sono una normale funzione di nome B della classe A.<br>\n"; echo "Non sono il costruttore di A.<br>\n"; } } class B extends A { } // This will call B() as a constructor. $b = new B; ?> |
La funzione B() della classe A si transformerà improvvisamente in un costruttore per la classe B, anche se questo non era previsto. PHP 4 non si preoccupa se la funzione è stata definita nella classe B o se è stata ereditata.
Attenzione |
Il PHP 4 non richiama i costruttori di una classe base automaticamente da un costruttore di una classe derivata. È responsabilità del programmatore propagare la chiamata ai costruttori dove è necessario. |
I distruttori sono funzioni che sono chiamate automaticamente quando una variabile è distrutta con unset() o semplicemente uscendo dal suo ambito. Non ci sono distruttori in PHP. Si può utilizzare register_shutdown_function() per simulare gli effetti del distruttore.
Attenzione |
Ciò che segue è valido soltanto per PHP 4. |
A volte è utile riferirsi alle funzioni ed alle variabili di classi base o riferirsi alle funzioni di classi senza istanziarle. L'operatore :: è usato per questi scopi.
<?php class A { function example() { echo "Sono la funzione originale A::example().<br />\n"; } } class B extends A { function example() { echo "Sono la funzione ridefinita B::example().<br />\n"; A::example(); } } // non viene istanziato nessun oggetto dalla classe A. // ma il codice stampa // Sono la funzione originale A::example().<br /> A::example(); // crea un oggetto dalla classe B. $b = new B; // questo codice stampa // Sono la funzione ridefinita B::example().<br /> // Sono la funzione originale A::example().<br /> $b->example(); ?> |
L'esempio chiama la funzione example() della classe A, ma senza creare un'istanza di A, di modo che la funzione non si possa richiamare con $a->example(). example() è chiamata come 'funzione della classe', e non come funzione di un oggetto della classe.
Si possono usare funzioni della classe, ma non le variabili della classe. Infatti, non esiste nessun oggetto nel momento della chiamata della funzione. Quindi, la funzione della classe non può usare le variabili dell'oggetto (ma può usare le variabili locali e globali) e $this non può essere usato.
Nel suddetto esempio, la classe B ridefinisce la funzione example(). La funzione originale definita nella classe A è adombrata e non più disponibile, a meno che voi non chiamiate esplicitamente con l'operatore :: scrivendo A::example() per richiamare la funzione (è possibile anche scrivere parent::example(), come mostra la sezione seguente).
In questo contesto, c'è un oggetto corrente che può avere determinate variabili. Una volta usate da parte di una funzione dell'oggetto, potete usare $this per le variabili dell'oggetto.
E possibile ritrovarsi a scrivere classi con codice che si riferisce a variabili e funzioni di classi base. Ciò è particolarmente VERO se una classe derivata è un perfezionamento o una specializzazione di una classe base.
Invece di usare il nome letterale della classe, bisognerebbe usare il nome speciale parent, che si riferisce al nome della classe base definita nella dichiarazione di extends. Usando questo metodo, si evita di usare il nome della classe base nel codice scritto. Se l'albero di eredità cambiasse durante lo sviluppo della classe, il cambiamento si ridurrebbe semplicemente alla modifica della dichiarazione extends della classe.
<?php class A { function example() { echo "Sono A::example() e fornisco una funzionalità di base.<br />\n"; } } class B extends A { function example() { echo "Sono B::example() e fornisco una funzionalità aggiuntiva.<br />\n"; parent::example(); } } $b = new B; // Il codice chiama B::example(), che a sua volta chiama A::example(). $b->example(); ?> |
Nota: In PHP 3, gli oggetti perdono la loro associazione di classe durante il processo di serializzazione e di deserializzazione. La variabile risultante è di tipo oggetto, ma non ha classe e metodi, e diventa inutile (come un buffo array).
Attenzione |
Le seguenti informazioni sono valide soltanto per PHP 4. |
serialize() restituisce una stringa che contiene una rappresentazione byte-stream di tutti i valori che possono essere memorizzati in PHP. unserialize() può usare questa stringa per ricreare i valori variabili utilizzabili. Usando serialize() per salvare un oggetto si salveranno tutte le variabili dell'oggetto. Le funzioni dell'oggetto non sono salvate, viene salvato solo il nome della classe.
Per potere usare unserialize() su un oggetto, la classe dell'oggetto deve essere definita. Cioè se avete un oggetto $a della classe A su una pagina di nome page1.php e usate serialize(), otterrete una stringa che si riferisce alla classe A e contiene tutti i valori delle variabili contenute in $a. Se desiderate potere deserializzare l'oggetto in un'altra pagina chiamata page2.php, dovete ricreare $a dalla classe A, la definizione della classe A perciò deve essere presente nella pagina page2.php. Questo può essere fatto per esempio memorizzando la definizione della classe A in un file che viene incluso sia in page1.php che in page2.php.
<?php // classa.inc: class A { var $one = 1; function show_one() { echo $this->one; } } // page1.php: include("classa.inc"); $a = new A; $s = serialize($a); // memorizzare $s in qualche posto della page2. $fp = fopen("store", "w"); fwrite($fp, $s); fclose($fp); // page2.php: // questo è necessario perchè unserialize() funzioni correttamente. include("classa.inc"); $s = implode("", @file("store")); $a = unserialize($s); // ora usiamo la function show_one() dell'oggetto $a. $a->show_one(); ?> |
Se state usando le sessioni ed usate session_register() per registrare oggetti, questi oggetti vengono serializzati automaticamente alla fine di ogni pagina PHP e sono deserializzate automaticamente su ogni pagina della sessione. Ciò significa che gli oggetti possono mostrarsi in ogni pagina e che sono parte integrante della sessione.
Si suggerisce vivamente di includere le definizioni delle classi degli oggetti registrati su tutte le pagine, anche se le classi non sono usate su tutte le pagine. Se un oggetto viene deserializzato senza la relativa definizione della classe, perderà l'associazione ad essa e si transformerà in in un oggetto della classe stdClass senza nessuna funzione disponibile, diventando inutile.
Così se nell'esempio qui sopra $a diventasse parte di una sessione e fosse registrato con session_register("a"), dovreste includere un file classa.inc su tutte le pagine in cui è valida la sessione, non soltanto nella page1.php e nella page2.php.
serialize() controlla se la vostra classe ha una funzione dal nome magico __sleep. In caso affermativo, quella funzione viene eseguita prima di qualsiasi serializzazione. La funzione può pulire l'oggetto e restituire un array con i nomi di tutte le variabili di quell' oggetto che dovrebbero essere serializzate.
Si intende usare __sleep quando chiudendo un collegamento ad un database l'oggetto può avere dati pendenti e l'oggetto ha bisogno di essere ripulito. Inoltre, la funzione è utile se avete oggetti molto grandi che non devono essere salvati completamente.
Per contro, unserialize() controlla per vedere se c'è nella classe una funzione dal nome magico __wakeup. Se è presente questa funzione può ricostruire qualunque risorsa che l'oggetto aveva.
L'intento di __wakeup è quello di ristabilire le connessioni ai database che possono esser state persi durante la serializzazione ed effettuare altre mansioni reinizializzazione.
La creazione di riferimenti con costruttori può condurre a risultati confusi. Questa sezione in stile Tutorial vi aiuterà ad evitare problemi.
<?php class Foo { function Foo($name) { // crea un riferimento all'interno della variabile $globalref global $globalref; $globalref[] = &$this; // setta Name con il valore passato $this->setName($name); // e lo manda all'output $this->echoName(); } function echoName() { echo "<br>",$this->name; } function setName($name) { $this->name = $name; } } ?> |
Verifichiamo se c'è una differenza fra $bar1 che è stato creato usando l'operatore = e $bar2 che è stato creato usando l'operatore di riferimento =& ...
<?php $bar1 = new Foo('set in constructor'); $bar1->echoName(); $globalref[0]->echoName(); /* output: imposta nel costruttore imposta nel costruttore imposta nel costruttore */ $bar2 =& new Foo('set in constructor'); $bar2->echoName(); $globalref[1]->echoName(); /* output: imposta nel costruttore imposta nel costruttore imposta nel costruttore */ ?> |
Apparentemente non c'è differenza, ed in effetti questo è molto significativo: $bar1 e $globalref[0] _ NON _ sono riferimenti, ma sono due variabili diverse. Questo succede perché "new" non restituisce per default un riferimento, ma restituisce una copia.
Nota: Non c'è perdita di prestazioni (da php 4 in su si usa il riferimento) ad istanziare copie per riferimento. Al contrario spesso è meglio lavorare con copie istanziate per riferimento, perché creare copie reali richiede un certo tempo, mentre creare riferimenti virtuali è immediato, (a meno che non si parli di un grande array o un oggetto che viene modificato in modo successivo, allora sarebbe saggio usare i riferimenti per cambiargli tutti i valori simultaneamente).
<?php // ora cambieremo il nome che cosa vi aspettate? // potreste prevedere che $bar e $globalref[0] cambino i loro nomi ... $bar1->setName('set from outside'); // come accennato prima ecco il risultato. $bar1->echoName(); $globalref[0]->echoName(); /* output: set from outside set in constructor */ // vediamo le differenze tra $bar2 e $globalref[1] $bar2->setName('set from outside'); // fortunatamen sono solo uguali, ma sono la stessa variabile // $bar2->name e $globalref[1]->name sono la stessa cosa $bar2->echoName(); $globalref[1]->echoName(); /* output: set from outside set from outside */ ?> |
Un esempio finale, prova a farvi capire.
<?php class A { function A($i) { $this->value = $i; // provare a capire perchè qui non abbiamo bisogno d'un riferimento $this->b = new B($this); } function createRef() { $this->c = new B($this); } function echoValue() { echo "<br />","class ",get_class($this),': ',$this->value; } } class B { function B(&$a) { $this->a = &$a; } function echoValue() { echo "<br />","class ",get_class($this),': ',$this->a->value; } } // prova a capire perchè usando una semplice copia si avrebbe // in un risultato indesiderato nella riga segnata con * $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(); ?> |
Il precedente esempio visualizzerà:
class A: 10 class B: 10 class B: 10 class A: 11 class B: 11 class B: 11 |
In PHP 4, gli oggetti sono confrontati semplicemente, cioè: due istanze di oggetto sono uguali se hanno gli stessi attributi e valori, e sono istanze della stessa classe. Questa regola regola è applicata anche nel confronto di due oggetti utilizzando l'operatore di identità (===).
Eseguendo il codice seguente:
Esempio 18-1. Esempio di confronto di oggetti in PHP 4
Il precedente esempio visualizzerà:
|
Anche nei casi in cui l'oggetto è composto si applicano le stesse regole di confronto. Nell'esempio seguente creiamo una classe contenitore che archivia nell'array associativo Flag altri oggetti.
Esempio 18-2. Confronto di oggetti composti in PHP 4
Il precedente esempio visualizzerà:
|
In PHP 5 there is a new Object Model. PHP's handling of objects has been completely rewritten, allowing for better performance and more features.
Every class definition begins with the keyword class, followed by a class name, which can be any name that isn't a reserved word in PHP. Followed by a pair of curly braces, of which contains the definition of the classes members and methods. A pseudo-variable, $this is available when a method is called from within an object context. $this is a reference to the calling object (usually the object to which the method belongs, but can be another object, if the method is called statically from the context of a secondary object). This is illustrated in the following example:
<?php class A { function foo() { if (isset($this)) { echo '$this is defined ('; echo get_class($this); echo ")\n"; } else { echo "\$this is not defined.\n"; } } } class B { function bar() { A::foo(); } } $a = new A(); $a->foo(); A::foo(); $b = new B(); $b->bar(); B::bar(); ?> |
Il precedente esempio visualizzerà:
$this is defined (a) $this is not defined. $this is defined (b) $this is not defined. |
To create an instance of an object, a new object must be created and assigned to a variable. An object will always be assigned when creating a new object unless the object has a constructor defined that throws an exception on error.
When assigning an already created instance of an object to a new variable, the new variable will access the same instance as the object that was assigned. This behaviour is the same when passing instances to a function. A new instance of an already created object can be made by cloning it.
Esempio 19-3. Object Assignment
Il precedente esempio visualizzerà:
|
A class can inherit methods and members of another class by using the extends keyword in the declaration. It is not possible to extend multiple classes, a class can only inherit one base class.
The inherited methods and members can be overridden, unless the parent class has defined a method as final, by redeclaring them within the same name defined in the parent class. It is possible to access the overrided method or members by referencing them with parent::
Esempio 19-4. Simple Class Inherintance
Il precedente esempio visualizzerà:
|
Many developers writing object-oriented applications create one PHP source file per-class definition. One of the biggest annoyances is having to write a long list of needed includes at the beginning of each script (one for each class).
In PHP 5, this is no longer necessary. You may define an __autoload function which is automatically called in case you are trying to use a class which hasn't been defined yet. By calling this function the scripting engine is given a last chance to load the class before PHP fails with an error.
Nota: Exceptions thrown in __autoload function cannot be caught in the catch block and results in a fatal error.
PHP 5 allows developers to declare constructor methods for classes. Classes which have a constructor method call this method on each newly-created object, so it is suitable for any initialization that the object may need before it is used.
Nota: Parent constructors are not called implicitly if the child class defines a constructor. In order to run a parent constructor, a call to parent::__construct() within the child constructor is required.
Esempio 19-6. using new unified constructors
|
For backwards compatibility, if PHP 5 cannot find a __construct() function for a given class, it will search for the old-style constructor function, by the name of the class. Effectively, it means that the only case that would have compatibility issues is if the class had a method named __construct() which was used for different semantics.
PHP 5 introduces a destructor concept similar to that of other object-oriented languages, such as C++. The destructor method will be called as soon as all references to a particular object are removed or when the object is explicitly destroyed.
Like constructors, parent destructors will not be called implicitly by the engine. In order to run a parent destructor, one would have to explicitly call parent::__destruct() in the destructor body.
Nota: Destructor is called during the script shutdown so headers are always already sent.
Nota: Attempting to throw an exception from a desctructor causes a fatal error.
The visibility of a property or method can be defined by prefixing the declaration with the keywords: public, protected or private. Public declared items can be accessed everywhere. Protected limits access to inherited and parent classes (and to the class that defines the item). Private limits visibility only to the class that defines the item.
Class members must be defined with public, private, or protected.
Esempio 19-8. Member declaration
|
Nota: The PHP 4 method of declaring a variable with the var keyword is no longer valid for PHP 5 objects. For compatibility a variable declared in php will be assumed with public visibility, and a E_STRICT warning will be issued.
Class methods must be defined with public, private, or protected. Methods without any declaration are defined as public.
Esempio 19-9. Method Declaration
|
The Scope Resolution Operator (also called Paamayim Nekudotayim) or in simpler terms, the double colon, is a token that allows access to static, constant, and overridden members or methods of a class.
When referencing these items from outside the class definition, use the name of the class.
Paamayim Nekudotayim would, at first, seem like a strange choice for naming a double-colon. However, while writing the Zend Engine 0.5 (which powers PHP 3), that's what the Zend team decided to call it. It actually does mean double-colon - in Hebrew!
Two special keywords self and parent are used to access members or methods from inside the class definition.
When an extending class overrides the parents definition of a method, PHP will not call the parent's method. It's up to the extended class on whether or not the parent's method is called. This also applies to Constructors and Destructors, Overloading, and Magic method definitions.
Esempio 19-12. Calling a parent's method
|
Declaring class members or methods as static makes them accessible without needing an instantiation of the class. A member declared as static can not be accessed with an instantiated class object (though a static method can).
The static declaration must be after the visibility declaration. For compatibility with PHP 4, if no visibility declaration is used, then the member or method will be treated as if it was declared as public.
Because static methods are callable without an instance of the object created, the pseudo variable $this is not available inside the method declared as static.
In fact static method calls are resolved at compile time. When using an explicit class name the method is already identified completely and no inheritance rules apply. If the call is done by self then self is translated to the current class, that is the class the code belongs to. Here also no inheritance rules apply.
Static properties cannot be accessed through the object using the arrow operator ->.
Calling non-static methods statically generates an E_STRICT level warning.
Esempio 19-13. Static member example
|
It is possible to define constant values on a per-class basis remaining the same and unchangeable. Constants differ from normal variables in that you don't use the $ symbol to declare or use them. Like static members, constant values cannot be accessed from an instance of the object (using $object::constant).
The value must be a constant expression, not (for example) a variable, a class member, result of a mathematical operation or a function call.
PHP 5 introduces abstract classes and methods. It is not allowed to create an instance of a class that has been defined as abstract. Any class that contains at least one abstract method must also be abstract. Methods defined as abstract simply declare the method's signature they cannot define the implementation.
When inheriting from an abstract class, all methods marked abstract in the parent's class declaration must be defined by the child; additionally, these methods must be defined with the same (or weaker) visibillity. For example, if the abstract method is defined as protected, the function implementation must be defined as either protected or public.
Esempio 19-16. Abstract class example
Il precedente esempio visualizzerà:
|
Old code that has no user-defined classes or functions named 'abstract' should run without modifications.
Object interfaces allow you to create code which specifies which methods a class must implement, without having to define how these methods are handled.
Interfaces are defined using the interface keyword, in the same way as a standard class, but without any of the methods having their contents defined.
All methods declared in an interface must be public, this is the nature of an interface.
To implement an interface, the implements operator is used. All methods in the interface must be implemented within a class; failure to do so will result in a fatal error. Classes may implement more than one interface if desired by separating each interface with a comma.
Esempio 19-17. Interface example
|
See also the instanceof operator.
Both method calls and member accesses can be overloaded via the __call, __get and __set methods. These methods will only be triggered when your object or inherited object doesn't contain the member or method you're trying to access. All overloading methods must not be defined as static.
Since PHP 5.1.0 it is also possible to overload the isset() and unset() functions via the __isset and __unset methods respectively.
Class members can be overloaded to run custom code defined in your class by defining these specially named methods. The $name parameter used is the name of the variable that should be set or retrieved. The __set() method's $value parameter specifies the value that the object should set the $name.
Esempio 19-18. overloading with __get, __set, __isset and __unset example
Il precedente esempio visualizzerà:
|
Class methods can be overloaded to run custom code defined in your class by defining this specially named method. The $name parameter used is the name as the function name that was requested to be used. The arguments that were passed in the function will be defined as an array in the $arguments parameter. The value returned from the __call() method will be returned to the caller of the method.
Esempio 19-19. overloading with __call example
Il precedente esempio visualizzerà:
|
PHP 5 provides a way for objects to be defined so it is possible to iterate through a list of items, with, for example a foreach statement. By default, all visible properties will be used for the iteration.
Esempio 19-20. Simple Object Iteration
Il precedente esempio visualizzerà:
|
As the output shows, the foreach iterated through all visible variables that can be accessed. To take it a step further you can implement one of PHP 5's internal interface named Iterator. This allows the object to decide what and how the object will be iterated.
Esempio 19-21. Object Iteration implementing Iterator
Il precedente esempio visualizzerà:
|
You can also define your class so that it doesn't have to define all the Iterator functions by simply implementing the PHP 5 IteratorAggregate interface.
Esempio 19-22. Object Iteration implementing IteratorAggregate
Il precedente esempio visualizzerà:
|
Nota: For more examples of iterators, see the SPL Extension.
Patterns are ways to describe best practices and good designs. They show a flexible solution to common programming problems.
The Factory pattern allows for the instantiation of objects at runtime. It is called a Factory Pattern since it is responsible for "manufacturing" an object.
Esempio 19-23. Factory Method
Defining this method in a class allows drivers to be loaded on the fly. If the Example class was a database abstraction class, loading a MySQL and SQLite driver could be done as follows:
|
The Singleton pattern applies to situations in which there needs to be a single instance of a class. The most common example of this is a database connection. Implementing this pattern allows a programmer to make this single instance easily accessible by many other objects.
Esempio 19-24. Singleton Function
This allows a single instance of the Example class to be retrieved.
|
The function names __construct, __destruct (see Constructors and Destructors), __call, __get, __set, __isset, __unset (see Overloading), __sleep, __wakeup, __toString, __clone and __autoload are magical in PHP classes. You cannot have functions with these names in any of your classes unless you want the magic functionality associated with them.
Attenzione |
PHP reserves all function names starting with __ as magical. It is recommended that you do not use function names with __ in PHP unless you want some documented magic functionality. |
serialize() checks if your class has a function with the magic name __sleep. If so, that function is executed prior to any serialization. It can clean up the object and is supposed to return an array with the names of all variables of that object that should be serialized.
The intended use of __sleep is to close any database connections that the object may have, commit pending data or perform similar cleanup tasks. Also, the function is useful if you have very large objects which do not need to be saved completely.
Conversely, unserialize() checks for the presence of a function with the magic name __wakeup. If present, this function can reconstruct any resources that the object may have.
The intended use of __wakeup is to reestablish any database connections that may have been lost during serialization and perform other reinitialization tasks.
Esempio 19-25. Sleep and wakeup
|
The __toString method allows a class to decide how it will react when it is converted to a string.
It is worth noting that the __toString method will only be called when it is directly combined with echo() or print().
Esempio 19-27. Cases where __toString is called
|
PHP 5 introduces the final keyword, which prevents child classes from overriding a method by prefixing the definition with final. If the class itself is being defined final then it cannot be extended.
Esempio 19-28. Final methods example
|
Esempio 19-29. Final class example
|
Creating a copy of an object with fully replicated properties is not always the wanted behavior. A good example of the need for copy constructors, is if you have an object which represents a GTK window and the object holds the resource of this GTK window, when you create a duplicate you might want to create a new window with the same properties and have the new object hold the resource of the new window. Another example is if your object holds a reference to another object which it uses and when you replicate the parent object you want to create a new instance of this other object so that the replica has its own separate copy.
An object copy is created by using the clone keyword (which calls the object's __clone() method if possible). An object's __clone() method cannot be called directly.
When an object is cloned, PHP 5 will perform a shallow copy of all of the object's properties. Any properties that are references to other variables, will remain references. If a __clone() method is defined, then the newly created object's __clone() method will be called, to allow any necessary properties that need to be changed.
Esempio 19-30. Cloning an object
Il precedente esempio visualizzerà:
|
In PHP 5, object comparison is more complicated than in PHP 4 and more in accordance to what one will expect from an Object Oriented Language (not that PHP 5 is such a language).
When using the comparison operator (==), object variables are compared in a simple manner, namely: Two object instances are equal if they have the same attributes and values, and are instances of the same class.
On the other hand, when using the identity operator (===), object variables are identical if and only if they refer to the same instance of the same class.
An example will clarify these rules.
Esempio 19-31. Example of object comparison in PHP 5
Il precedente esempio visualizzerà:
|
PHP 5 comes with a complete reflection API that adds the ability to reverse-engineer classes, interfaces, functions and methods as well as extensions. Additionally, the reflection API also offers ways of retrieving doc comments for functions, classes and methods.
The reflection API is an object-oriented extension to the Zend Engine, consisting of the following classes:
<?php class Reflection { } interface Reflector { } class ReflectionException extends Exception { } class ReflectionFunction implements Reflector { } class ReflectionParameter implements Reflector { } class ReflectionMethod extends ReflectionFunction { } class ReflectionClass implements Reflector { } class ReflectionObject extends ReflectionClass { } class ReflectionProperty implements Reflector { } class ReflectionExtension implements Reflector { } ?> |
Nota: For details on these classes, have a look at the next chapters.
If we were to execute the code in the example below:
Esempio 19-32. Basic usage of the reflection API
Il precedente esempio visualizzerà:
|
ReflectionException extends the standard Exception and is thrown by Reflection API. No specific methods or properties are introduced.
The ReflectionFunction class lets you reverse-engineer functions.
<?php class ReflectionFunction implements Reflector { final private __clone() public object __construct(string name) public string __toString() public static string export() public string getName() public bool isInternal() public bool isUserDefined() public string getFileName() public int getStartLine() public int getEndLine() public string getDocComment() public array getStaticVariables() public mixed invoke(mixed* args) public mixed invokeArgs(array args) public bool returnsReference() public ReflectionParameter[] getParameters() public int getNumberOfParameters() public int getNumberOfRequiredParameters() } ?> |
Nota: getNumberOfParameters() and getNumberOfRequiredParameters() were added in PHP 5.0.3, while invokeArgs() was added in PHP 5.1.0.
To introspect a function, you will first have to create an instance of the ReflectionFunction class. You can then call any of the above methods on this instance.
Esempio 19-33. Using the ReflectionFunction class
|
Nota: The method invoke() accepts a variable number of arguments which are passed to the function just as in call_user_func().
The ReflectionParameter class retrieves information about a function's or method's parameters.
<?php class ReflectionParameter implements Reflector { final private __clone() public object __construct(string name) public string __toString() public static string export() public string getName() public bool isPassedByReference() public ReflectionClass getClass() public bool isArray() public bool allowsNull() public bool isOptional() public bool isDefaultValueAvailable() public mixed getDefaultValue() } ?> |
Nota: getDefaultValue(), isDefaultValueAvailable() and isOptional() were added in PHP 5.0.3, while isArray() was added in PHP 5.1.0.
To introspect function parameters, you will first have to create an instance of the ReflectionFunction or ReflectionMethod classes and then use their getParameters() method to retrieve an array of parameters.
Esempio 19-34. Using the ReflectionParameter class
|
The ReflectionClass class lets you reverse-engineer classes.
<?php class ReflectionClass implements Reflector { final private __clone() public object __construct(string name) public string __toString() public static string export() public string getName() public bool isInternal() public bool isUserDefined() public bool isInstantiable() public bool hasConstant(string name) public bool hasMethod(string name) public bool hasProperty(string name) public string getFileName() public int getStartLine() public int getEndLine() public string getDocComment() public ReflectionMethod getConstructor() public ReflectionMethod getMethod(string name) public ReflectionMethod[] getMethods() public ReflectionProperty getProperty(string name) public ReflectionProperty[] getProperties() public array getConstants() public mixed getConstant(string name) public ReflectionClass[] getInterfaces() public bool isInterface() public bool isAbstract() public bool isFinal() public int getModifiers() public bool isInstance(stdclass object) public stdclass newInstance(mixed* args) public ReflectionClass getParentClass() public bool isSubclassOf(ReflectionClass class) public array getStaticProperties() public mixed getStaticPropertyValue(string name [, mixed default]) public void setStaticPropertyValue(string name, mixed value) public array getDefaultProperties() public bool isIterateable() public bool implementsInterface(string name) public ReflectionExtension getExtension() public string getExtensionName() } ?> |
Nota: hasConstant(), hasMethod(), hasProperty(), getStaticPropertyValue() and setStaticPropertyValue() were added in PHP 5.1.0.
To introspect a class, you will first have to create an instance of the ReflectionClass class. You can then call any of the above methods on this instance.
Esempio 19-35. Using the ReflectionClass class
|
Nota: The method newInstance() accepts a variable number of arguments which are passed to the function just as in call_user_func().
Nota: $class = new ReflectionClass('Foo'); $class->isInstance($arg) is equivalent to $arg instanceof Foo or is_a($arg, 'Foo').
The ReflectionMethod class lets you reverse-engineer class methods.
<?php class ReflectionMethod extends ReflectionFunction { public __construct(mixed class, string name) public string __toString() public static string export() public mixed invoke(stdclass object, mixed* args) public mixed invokeArgs(stdclass object, array args) public bool isFinal() public bool isAbstract() public bool isPublic() public bool isPrivate() public bool isProtected() public bool isStatic() public bool isConstructor() public bool isDestructor() public int getModifiers() public ReflectionClass getDeclaringClass() // Inherited from ReflectionFunction final private __clone() public string getName() public bool isInternal() public bool isUserDefined() public string getFileName() public int getStartLine() public int getEndLine() public string getDocComment() public array getStaticVariables() public bool returnsReference() public ReflectionParameter[] getParameters() public int getNumberOfParameters() public int getNumberOfRequiredParameters() } ?> |
To introspect a method, you will first have to create an instance of the ReflectionMethod class. You can then call any of the above methods on this instance.
Esempio 19-36. Using the ReflectionMethod class
|
Nota: Trying to invoke private, protected or abstract methods will result in an exception being thrown from the invoke() method.
Nota: For static methods as seen above, you should pass NULL as the first argument to invoke(). For non-static methods, pass an instance of the class.
The ReflectionProperty class lets you reverse-engineer class properties.
<?php class ReflectionProperty implements Reflector { final private __clone() public __construct(mixed class, string name) public string __toString() public static string export() public string getName() public bool isPublic() public bool isPrivate() public bool isProtected() public bool isStatic() public bool isDefault() public int getModifiers() public mixed getValue(stdclass object) public void setValue(stdclass object, mixed value) public ReflectionClass getDeclaringClass() public string getDocComment() } ?> |
Nota: getDocComment() was added in PHP 5.1.0.
To introspect a property, you will first have to create an instance of the ReflectionProperty class. You can then call any of the above methods on this instance.
Esempio 19-37. Using the ReflectionProperty class
|
Nota: Trying to get or set private or protected class property's values will result in an exception being thrown.
The ReflectionExtension class lets you reverse-engineer extensions. You can retrieve all loaded extensions at runtime using the get_loaded_extensions().
<?php class ReflectionExtension implements Reflector { final private __clone() public __construct(string name) public string __toString() public static string export() public string getName() public string getVersion() public ReflectionFunction[] getFunctions() public array getConstants() public array getINIEntries() public ReflectionClass[] getClasses() public array getClassNames() } ?> |
To introspect an extension, you will first have to create an instance of the ReflectionExtension class. You can then call any of the above methods on this instance.
Esempio 19-38. Using the ReflectionExtension class
|
In case you want to create specialized versions of the built-in classes (say, for creating colorized HTML when being exported, having easy-access member variables instead of methods or having utility methods), you may go ahead and extend them.
Esempio 19-39. Extending the built-in classes
|
Nota: Caution: If you're overwriting the constructor, remember to call the parent's constructor _before_ any code you insert. Failing to do so will result in the following: Fatal error: Internal error: Failed to retrieve the reflection object
PHP 5 introduces Type Hinting. Functions are now able to force parameters to be objects (by specifying the name of the class in the function prototype) or arrays (since PHP 5.1).
Esempio 19-40. Type Hinting examples
Failing to satisfy the type hint results in a fatal error.
Type hinting also works with functions:
|
Type Hints can only be of the object and array (since PHP 5.1) type. Traditional type hinting with int and string isn't supported.
PHP 5 has an exception model similar to that of other programming languages. An exception can be thrown, try and caught within PHP. A Try block must include at least one catch block. Multiple catch blocks can be used to catch different classtypes; execution will continue after that last catch block defined in sequence. Exceptions can be thrown within catch blocks.
When an exception is thrown, code following the statement will not be executed and PHP will attempt to find the first matching catch block. If an exception is not caught a PHP Fatal Error will be issued with an Uncaught Exception message, unless there has been a handler defined with set_exception_handler().
Esempio 20-1. Throwing an Exception
|
A User defined Exception class can be defined by extending the built-in Exception class. The members and properties below, show what is accessible within the child class that derives from the built-in Exception class.
Esempio 20-2. The Built in Exception class
|
If a class extends the built-in Exception class and re-defines the constructor, it is highly recomended that it also call parent::__construct() to ensure all available data has been properly assigned. The __toString() method can be overriden to provide a custom output when the object is presented as a string.
Esempio 20-3. Extending the Exception class
|
I riferimenti in PHP sono il mezzo per accedere ad uno stesso contenuto di variabile utilizzando diversi nomi. Non si sta parlando di puntatori come in C, ma di alias nella tabella dei simboli. Si noti che in PHP, il nome delle variabili e il loro contenuto sono cose diverse, uno stesso contenuto infatti può avere nomi diversi. L'analogia più prossima è quella con i nomi dei file e i file stessi in Unix - i nomi delle variabili sono come directory, mentre il contenuto delle variabili è il file stesso. I riferimenti possono essere pensati come hardlink del filesystem Unix.
I riferimenti permettono di creare due o più variabili che si riferiscono allo stesso contenuto. Questo significa, che scrivendo:
$a e $b puntano allo stesso contenuto.Nota: $a e $b sono completamente uguali, ma $a non è un puntatore a $b o vice versa, $a e $b puntano semplicemente nello stesso posto.
Nota: Se si copia una matrice contenete dei riferimenti, i valori non sono dereferenziati. Questo vale anche per le matrici passate per valore alle funzioni.
Questa sintassi si può usare con le funzioni, nella restituzione per riferimento, e con l'operatore new (da PHP 4.0.4 in poi):
Nota: Se non si usa l'operatore & l'oggeto appena creato viene copiato. Usando $this in una classe, opererà sulla sua istanza corrente. L'assegnazione senza & copia perciò l'istanza (l'oggetto) e $this opera sulla copia, che non è sempre ciò che si desidera. Normalmente si lavora su una singola istanza di oggetto, sia per motivi di prestazioni che di consumo di memoria.
Utilizzando l'operatore @ con new, si sopprimono gli errori nel costruttore in questo modo @new, il metodo però non funziona se si usa l'istruzione &new. Questa è una limitazione dello Zend Engine e provoca un parser error.
Avvertimento | ||
Se si assegna un riferimento ad una varibile dichiarata global dall'interno di una funzione, il riferimento sarà visibile solo all'interno della funzione stessa. Si può evitare tutto ciò utilizzando la matrice $GLOBALS.
|
Nota: Se si assegna un valore ad una variabile con riferimenti in una istruzione foreach, anche la variabile a cui si fa riferimento sarà modificata.
Avvertimento | |
Spesso le matrici complesse sono copiate che referenziate. Il seguente esempio non gira come atteso. |
Il secondo utilizzo del riferimento è il passaggio di una variabile per riferimento. Questo si fa dichiarando una variabile locale di una funzione e una variabile nell'ambito della chiamata del riferimento con lo stesso contenuto. Esempio:
$a assume il valore 6. Questo accade perchè nella funzione foo, la variabile $var si riferisce allo stesso contenuto di $a. Si vedano le spiegazioni più dettagliate per passaggio per riferimento.Il terzo utilizzo del riferimento è il ritorno per riferimento.
Come detto prima, i riferimenti non sono puntatori. Questo significa, che il seguente costrutto non fà quello che ci si aspetterebbe:
Nell'esempio $var in foo viene scambiato con $bar nella chiamata, e poi riscambiato con $GLOBALS["baz"]. Questo non è il modo per collegare $bar nell'ambito della chiamata con qualcos'altro usando il meccanismo di riferimento, poichè $bar non è disponibile nella funzione foo (è rappresentato da $var, ma $var possiede soltanto il contenuto della variabile e non il nome del valore collegato nella tabella dei simboli). Si può utilizzare restiture i riferimenti per fare riferimenti a variabili selezionate dalla funzione.
Si può passare una variabile ad una funzione per riferimento, modificandone gli argomenti. La sintassi è la seguente:
Nota che non si usa il segno di riferimento nella chiamata della funzione, ma solo nella definizione. La definizione della funzione basta da sola per passare correttamente un argomento per riferimento. Nelle versioni recenti di PHP si avrà un warning indicante che "Call-time pass-by-reference" è deprecato quando si usa & foo(&$a); .Le seguenti cose possono essere passate per riferimento:
Variabili, es. foo($a)
Operatore New, es. foo(new foobar())
Riferimento restituito da una funazione, es.
Vedi anche le spiegazioni sulla restituzione per riferimento.Qualunque altra cosa non dovrebbe essere passata per riferimento, poichè il risultato sarebbe indefinito. Per esempio, il seguente passaggio per riferimento non è valido:
Questi requisiti sono validi per PHP 4.0.4 e seguenti.La restituzione per riferimento è utile quando si vuole usare una funzione per trovare quale variabile un riferimento dovrebbe limitare. non utilizzare il ritorno per riferimento per incrementare le prestazioni, l'engine è abbastanza abile da ottimizzare il codice per proprio conto. Restituire valori per riferimento solo se si hanno validi motivi tecnici! Per restituire per riferimento, si usa questa sintassi:
<?php function &find_var($param) { ...codice... return $found_var; } $foo =& find_var($bar); $foo->x = 2; ?> |
Nota: Diversamente dal passaggio di un parametro, bisogna utilizzare & in entrambi i posti - nella dichiarazione per indicare che si vuole restituire per riferimento, e non per copia come di consueto, e per indicare nella chiamata, il collegamento del riferimento, piuttosto che l'usuale assegnazione che verrebbe fatta per $foo.
Nota: Se si tenta di restituire un valore per riferimento da una funzione con la sintassi: return ($found_var); questo non funzionerà poichè si sta tntando di restituire per riferimento il risultato di un' espressione, e non una variabile. Da una funzione, si possono restituire per riferimento solo le variabili.
Quando si cancella un riferimento, si rompe il collegamento tra il nome della variabile e il contenuto della variabile. Questo non significa che il contenuto della variabile venga distrutto. Per esempio:
non cancella $b, ma solo $a.Di nuovo, può essere utile pensare a questo con un'analogia col comendo Unix unlink.
Diversi costrutti in PHP sono implementati attraverso il meccanismo dei riferimenti, dove ogni cosa detta precedentemente, si applica anche a questi costrutti. Alcuni, come il passaggio e la restituzione per riferimento, sono stati menzionati sopra, gli altri sono:
Quando si dichiara una variabile come global $var di fatto si crea un riferimento ad una variabile globale. Questo ha lo stesso significato, dell'espressione:
Questo significa, per esempio, che cancellando $var non si cancella la variabile globale.
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 unobtrusive 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 considered 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 a 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 accessible 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 abilities 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.
Esempio 26-2. ... A filesystem attack
|
Only allow limited permissions to the PHP web user binary.
Check all variables which are submitted.
Esempio 26-3. More secure file name checking
|
Esempio 26-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 information can be stored in a database, you should strongly consider protecting your databases.
To retrieve or to store any information you need to connect to the database, send a legitimate query, fetch the result, and close the connection. 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 surmise, 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: defense in depth. The more places you take action to increase the protection of your database, the less probability of an attacker succeeding in exposing or abusing any stored 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 one from a third party. 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 your applications 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 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 re-implement 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 establish 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 these is used, then monitoring your traffic and gaining information about your database will be difficult for a would-be attacker.
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 with several extensions, such as Mcrypt and Mhash, covering a wide variety of encryption algorithms. The script encrypts the data before inserting it into the database, and decrypts it when retrieving. See the references for further examples of how encryption works.
In case of truly hidden data, if its raw representation is not needed (i.e. not be displayed), hashing may also be 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().
Esempio 27-1. 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.
0; insert into pg_shadow(usename,usesysid,usesuper,usecatupd,passwd) select 'crack', usesysid, 't','t','crack' from pg_shadow where usename='postgres'; -- |
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. The only thing the attacker needs to do is to see if there are any submitted variables used in SQL statements which are 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 UPDATE's are also susceptible to attack. 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 examining the form variable names, or just simply brute forcing. There are not so many naming conventions for fields storing passwords or usernames.
<?php // $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.
<?php $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 similarly vulnerable in another 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 any kind of input, especially that 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) and onwards to the Perl compatible Regular Expressions support.
If the application waits for numerical input, consider verifying data with is_numeric(), or silently change its type using settype(), or use its numeric representation by sprintf().
Esempio 27-6. A more secure way to compose a query for paging
|
Quote each non numeric user supplied value that is passed to the database with the database-specific string escape function (e.g. mysql_escape_string(), sql_escape_string(), etc.). If a database-specific string escape mechanism is not available, the addslashes() and str_replace() functions may be useful (depending on database type). See the first example. As the example shows, adding quotes to the static part of the query is not enough, making this query easily crackable.
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 logging. 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. More detail is generally better than less.
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 occurred 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, you should either disable error reporting completely by setting error_reporting() to 0, or turn off the error display using the php.ini option display_errors, to insulate your code from probing. If you choose to do the latter, you should also define the path to your log file using the error_log ini directive, and turn log_errors on.
Perhaps the most controversial change in PHP is when the default value for the PHP directive register_globals went from ON to OFF in PHP 4.2.0. Reliance on this directive was quite common and many people didn't even know it existed and assumed it's just how PHP works. This page will explain how one can write insecure code with this directive but keep in mind that the directive itself isn't insecure but rather it's the misuse of it.
When on, register_globals will inject your scripts with all sorts of variables, like request variables from HTML forms. This coupled with the fact that PHP doesn't require variable initialization means writing insecure code is that much easier. It was a difficult decision, but the PHP community decided to disable this directive by default. When on, people use variables yet really don't know for sure where they come from and can only assume. Internal variables that are defined in the script itself get mixed up with request data sent by users and disabling register_globals changes this. Let's demonstrate with an example misuse of register_globals:
Esempio 29-1. Example misuse with register_globals = on
|
When register_globals = on, our logic above may be compromised. When off, $authorized can't be set via request so it'll be fine, although it really is generally a good programming practice to initialize variables first. For example, in our example above we might have first done $authorized = false. Doing this first means our above code would work with register_globals on or off as users by default would be unauthorized.
Another example is that of sessions. When register_globals = on, we could also use $username in our example below but again you must realize that $username could also come from other means, such as GET (through the URL).
Esempio 29-2. Example use of sessions with register_globals on or off
|
It's even possible to take preventative measures to warn when forging is being attempted. If you know ahead of time exactly where a variable should be coming from, you can check to see if the submitted data is coming from an inappropriate kind of submission. While it doesn't guarantee that data has not been forged, it does require an attacker to guess the right kind of forging. If you don't care where the request data comes from, you can use $_REQUEST as it contains a mix of GET, POST and COOKIE data. See also the manual section on using variables from outside of PHP.
Esempio 29-3. Detecting simple variable poisoning
|
Of course, simply turning off register_globals does not mean your code is secure. For every piece of data that is submitted, it should also be checked in other ways. Always validate your user data and initialize your variables! To check for uninitialized variables you may turn up error_reporting() to show E_NOTICE level errors.
For information about emulating register_globals being On or Off, see this FAQ.
Matrici superglobali: note di disponibilità: A partire da PHP 4.1.0, sono disponibili le matrici superglobali quali $_GET , $_POST, e $_SERVER, ecc. Per maggiori dettagli, si rimanda al capitolo superglobals del manuale
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.
Esempio 30-1. 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).
Magic Quotes is a process that automagically escapes incoming data to the PHP script. It's preferred to code with magic quotes off and to instead escape the data at runtime, as needed.
When on, all ' (single-quote), " (double quote), \ (backslash) and NULL characters are escaped with a backslash automatically. This is identical to what addslashes() does.
There are three magic quote directives:
Affects HTTP Request data (GET, POST, and COOKIE). Cannot be set at runtime, and defaults to on in PHP.
See also get_magic_quotes_gpc().
If enabled, most functions that return data from an external source, including databases and text files, will have quotes escaped with a backslash. Can be set at runtime, and defaults to off in PHP.
See also set_magic_quotes_runtime() and get_magic_quotes_runtime().
If enabled, a single-quote is escaped with a single-quote instead of a backslash. If on, it completely overrides magic_quotes_gpc. Having both directives enabled means only single quotes are escaped as ''. Double quotes, backslashes and NULL's will remain untouched and unescaped.
See also ini_get() for retrieving its value.
Useful for beginners
Magic quotes are implemented in PHP to help code written by beginners from being dangerous. Although SQL Injection is still possible with magic quotes on, the risk is reduced.
Convenience
For inserting data into a database, magic quotes essentially runs addslashes() on all Get, Post, and Cookie data, and does so automagically.
Portability
Assuming it to be on, or off, affects portability. Use get_magic_quotes_gpc() to check for this, and code accordingly.
Performance
Because not every piece of escaped data is inserted into a database, there is a performance loss for escaping all this data. Simply calling on the escaping functions (like addslashes()) at runtime is more efficient.
Although php.ini-dist enables these directives by default, php.ini-recommended disables it. This recommendation is mainly due to performance reasons.
Inconvenience
Because not all data needs escaping, it's often annoying to see escaped data where it shouldn't be. For example, emailing from a form, and seeing a bunch of \' within the email. To fix, this may require excessive use of stripslashes().
The magic_quotes_gpc directive may only be disabled at the system level, and not at runtime. In otherwords, use of ini_set() is not an option.
Esempio 31-1. Disabling magic quotes server side An example that sets the value of these directives to Off in php.ini. For additional details, read the manual section titled How to change configuration settings.
If access to the server configuration is unavailable, use of .htaccess is also an option. For example:
|
In the interest of writing portable code (code that works in any environment), like if setting at the server level is not possible, here's an example to disable magic_quotes_gpc at runtime. This method is inefficient so it's preferred to instead set the appropriate directives elsewhere.
Esempio 31-2. Disabling magic quotes at runtime
|
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 security and repair any 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.
I meccanismi di Autenticazione HTTP sono disponibili in PHP solo quando questo viene usato come un modulo di Apache ed esso non è quindi disponibile nella versione CGI. In uno script PHP modulo di Apache, è possibile usare la funzione header() per inviare un messaggio di "Authentication Required" al browser dell'utente, provocando quindi l'apertura di una finestra contenente una richiesta di Nome utente/Password. Una volta che l'utente ha compilato i campi nome utente e password, l'URL contenente lo script PHP verrà richiamato nuovamente usando le variabili predefinite, PHP_AUTH_USER, PHP_AUTH_PW e AUTH_TYPE impostate con, rispettivamente: nome, password e tipo di autenticazione. Queste variabili predefinite possono essere trovate negli array $_SERVER e $HTTP_SERVER_VARS. Saranno supportati entrambi i metodi di autenticazione, "Basic" e "Digest" (a partire dal PHP 5.1.0). Fare riferimento alla funzione header() per ulteriori informazioni.
Nota sulla versione di PHP: Le variabili autoglobali, come $_SERVER, esistono a partire da PHP 4.1.0. $HTTP_SERVER_VARS è disponibile a partire da PHP 3.
Un frammento di script di esempio che richiede l'autenticazione da parte del browser su una pagina, potrebbe essere il seguente:
Esempio 34-1. Esempio di Autenticazione HTTP "Basic"
|
Esempio 34-2. Esempio di autenticazione HTTP "Digest" Questo esempio illustra come implementare una autenticazione Digest. Per maggiori dettagli vedere RFC 2617.
|
Note sulla compatibilità: Fare molta attenzione quando si scrive codice per le intestazioni HTTP. Per ottenere la massima compatibilità con tutti i client, la paorla-chiave "Basic" deve essere scritta con una "B" maiuscola, la stringa realm deve essere racchiusa in virgolette doppie (non singole), ed esattamente uno spazio deve precedere il codice 401 nella linea di intestazione HTTP/1.0 401.
Invece di stampare semplicemente PHP_AUTH_USER e PHP_AUTH_PW, probabilmente si vorrà controllare la validità dello username e della password. Probabilmente inviando una chiamata al database, o cercando un utente in un file dbm.
Si faccia attenzione ad alcune versioni di Internet Explorer. Sembra che siano molto schizzinosi riguardo all'ordine delle intestazioni. Inviare l'intestazione WWW-Authenticate prima dell'intestazione HTTP/1.0 401 sembra sistemare le cose per il momento.
A partire da PHP 4.3.0, al fine di prevenire che qualcuno scriva uno script che rivela la password di una pagina che era stata autenticata tramite un tradizionale meccanismo esterno, le variabili PHP_AUTH non verranno impostate se è abilitata l'autenticazione esterna per quella determinata pagina e modalità sicura è abilitato. Ciò nonostante, la variabile REMOTE_USER può essere usata per identificare un utente autenticato esternamente. Quindi, potete usare $_SERVER['REMOTE_USER'].
Nota sulla Configurazione: PHP usa la presenza di una direttiva AuthType per determinare se viene utilizzata l'autenticazione esterna.
Si fa notare, però, che quanto scritto sopra non impedisce a qualcuno che controlla un URL non autenticato di sottrarre password da URL autenticati presenti sullo stesso server.
Sia Netscape Navigator che Internet Explorer cancellano la cache locale della finestra del browser, per quanto riguarda il realm, al ricevimento di una risposta 401 da parte del server. Questo è effettivamente un meccanismo di "log out" per l'utente, che lo forza a reinserire lo username e la password. Alcune persone usano questo per fare il "time out" dei login, o per rendere disponibili bottoni di "log-out".
Esempio 34-3. Esempio di Autenticazione HTTP che impone l'inserimento di nuovo username/password
|
Questo comportamento non è richiesto dallo standard di autenticazione HTTP Basic, quindi non si dovrebbe mai fare affidamento su di esso. Test effettuati con Lynx mostrano che Lynx non cancella le credenziali di autenticazione al ricevimento del codice di risposta 401 da parte del server, quindi, premendo indietro e avanti nuovamente, darà nuovamente accesso alla risorsa, ammesso che le rispettive richieste di credenziali non siano cambiate. L'utente può però premere il tasto '_' al fine di cancellare le sue informazioni di autenticazione.
Si noti anche che questo non funziona con il server IIS di Microsoft e con la versione CGI di PHP a causa di una limitazione di IIS. Si noti anche che, prima di PHP 4.3.3, l'Autenticazione HTTP non funzionava usando il server IIS di Microsoft e con la versione CGI di PHP a causa di una limitazione di IIS. Al fine di farla funzionare in PHP 4.3.3+, si deve modificare la vostra configurazione di IIS "Directory Security". Cliccare su "Edit" e selezionare solo "Anonymous Access", tutti gli altri campi dovrebbero essere lasciati deselezionati.
Un'altra limitazione è che se si usa il modulo IIS (ISAPI) e PHP 4, non si possono usare le variabili PHP_AUTH_* ma, al contrario, la variabile HTTP_AUTHORIZATION è disponibile. Per esempio, si consideri il seguente codice: list($user, $pw) = explode(':', base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));
Nota su IIS:: Al fine di fare funzionare la Autenticazione HTTP con IIS, la direttiva PHP cgi.rfc2616_headers deve essere impostata al valore 0 (il valore predefinito).
Nota: Se è abilitato safe mode viene aggiunto lo uid dello script al realm dell'header WWW-Authenticate.
PHP supporta in modo trasparente i cookies HTTP. I cookies sono un meccanismo per memorizzare dati nel browser remoto e tenere traccia degli utenti o identificarli al loro ritorno. I cookies possono essere impostati tramite le funzioni setcookie() oppure setrawcookie(). I cookies sono parte dell'intestazione HTTP, quindi setcookie() deve essere chiamata prima che qualsiasi output sia inviato al browser. Si tratta della stessa limitazione della funzione header(). Si può utilizzare la funzione di buffer dell'output per posticipare l'output dello script finchè non avete stabilito se impostare o meno qualsiasi cookies o l''invio di header.
Ogni cookie inviato dal client sarà automaticamente trasformato in una variabile PHP, come avviene nel caso di dati GET o POST, in base alle variabili di configurazione register_globals e variables_order. Se si vogliono assegnare più valori ad un singolo cookie, basta aggiungere [] al nome del cookie.
Nel PHP 4.1.0 e successivi, il vettore auto-globale $_COOKIE sarà sempre impostato con qualsiasi cookies inviati dal client. $HTTP_COOKIE_VARS è anch'essa impostata nelle versioni precedenti del PHP se è impostata la variabile di configurazione track_vars. (Questo parametro è sempre a on a partire da PHP 4.0.3.)
Per maggiori dettagli si vedano le funzioni setcookie() e setrawcookie().
Session support in PHP consists of a way to preserve certain data across subsequent accesses. This enables you to build more customized applications and increase the appeal of your web site. All information is in the Session reference section.
XForms defines a variation on traditional webforms which allows them to be used on a wider variety of platforms and browsers or even non-traditional media such as PDF documents.
The first key difference in XForms is how the form is sent to the client. XForms for HTML Authors contains a detailed description of how to create XForms, for the purpose of this tutorial we'll only be looking at a simple example.
Esempio 37-1. A simple XForms search form
|
The above form displays a text input box (named q), and a submit button. When the submit button is clicked, the form will be sent to the page referred to by action.
Here's where it starts to look different from your web application's point of view. In a normal HTML form, the data would be sent as application/x-www-form-urlencoded, in the XForms world however, this information is sent as XML formatted data.
If you're choosing to work with XForms then you probably want that data as XML, in that case, look in $HTTP_RAW_POST_DATA where you'll find the XML document generated by the browser which you can pass into your favorite XSLT engine or document parser.
If you're not interested in formatting and just want your data to be loaded into the traditional $_POST variable, you can instruct the client browser to send it as application/x-www-form-urlencoded by changing the method attribute to urlencoded-post.
Esempio 37-2. Using an XForm to populate $_POST
|
Nota: As of this writing, many browsers do not support XForms. Check your browser version if the above examples fails.
Questa caratteristica permette di caricare sia file di testo che binari. Utilizzando le funzioni di PHP per l'autenticazione e manipolazione dei file, è possibile avere pieno controllo su chi ha i permessi per caricare un file e su ciò che deve essere fatto una volta che il file è stato caricato.
Il PHP è in grado di riceve upload di file da qualsiasi browser compatibile con la RFC-1867 (compresi Netscape Navigator 3 e successivi, Microsoft Internet Explorer 3 con le patch di Microsoft, oppure le versioni successive senza patch).
Note relative alla configurazione: Si vedano i parametri file_uploads, upload_max_filesize, upload_tmp_dir, post_max_size e max_input_time nel php.ini
Si noti che PHP permette l'upload di file con metodo PUT come utilizzato dai programmi Netscape Composer e W3C Amaya. Si veda Supporto per metodo PUT per maggiori dettagli.
Esempio 38-1. Form di caricamento file La schermata di caricamento di un file può essere costruita con una form particolare, di questo tipo:
L'__URL__ dell'esempio precedente deve essere sostituito con il puntamento ad un file PHP. Il campo nascosto MAX_FILE_SIZE (misurato in byte) deve precedere il campo di input del file, ed il suo valore indica la dimensione massima di file accettata. Questa è un'informazione per il browser, ma anche il PHP lo verifica. E' facile aggirare questa impostazione sul browser, quindi non fate affidamento sul fatto che il navigatore si comporti come desiderato! L'impostazione PHP lato server per la dimensione massima non può comunque essere aggirata. Tuttavia si può comunque inserire MAX_FILE_SIZE per evitare all'utente di attendere il trasferimento di un file prima di scoprire che è di dimensioni eccessive. |
Nota: Accertarsi che il form di upload abbia l'impostazione enctype="multipart/form-data" altrimentio non funzionerà.
A partire dal PHP 4.1.0 esiste la variabile globale $_FILES. (Utilizzare $HTTP_POST_FILES nelle versioni precedenti). Queste matrici contengono tutte le informazioni sui file inviati.
Di seguito verrà illustrato il contenuto di $_FILES nel caso dell'esempio precedente. Si noti che si assume come nome del file inviato userfile, come nell'esempio precedente. Nella realtà questo può assurmere nome.
Il nome originale del file sulla macchina dell'utente.
Il mime-type del file, se il browser fornisce questa informazione. Un esempio potrebbe essere "image/gif".
La dimensione, in bytes, del file caricato.
Il nome del file temporaneo in cui il file caricato è salvato sul server.
Il codice di errore associato all'upload di questo file. Questo elemento è stato aggiunto nella versione 4.2.0 di PHP.
I file sono, di default, salvati in una directory temporanea sul server, a meno che un diverso percorso sia specificato nella direttiva upload_tmp_dir nel file php.ini. La directory del server predefinita può essere cambiata impostando la variabile di ambiente TMPDIR in cui è in esecuzione PHP. Non è possibile impostare questa variabile utilizzando la funzione putenv() da uno script PHP. Questa variabile di ambiente può anche essere usata per assicurarsi che anche altre operazioni stiano lavorando sui file caricati.
Esempio 38-2. Verifica dell'upload di file Si vedano le definizioni delle funzioni is_uploaded_file() e move_uploaded_file() per maggiori dettagli. L'esempio seguente illustra il processamento di un file inviato tramite un form.
|
Lo script PHP che riceve il file caricato dovrebbe implementare la logica necessaria per determinare cosa deve essere fatto con il file caricato. E' possibile, per esempio, utilizzare la variabile $_FILES['userfile']['size'] per eliminare file che siano troppo grandi o troppo piccoli. E' possibile utillizzare la variabile $_FILES['userfile']['type'] per eliminare tutti i file che non soddisfano certi criteri. A partire da PHP 4.2.0, si può utilizzare $_FILES['userfile']['error'] ed organizzare la logica in base ai codici di errore. Quale che sia la logica, bisognerebbe comunque sempre cancellare il file dalla directory temporanea e spostarlo da qualche altra parte.
Se non si è selezinato alcun file per l'upload, il PHP restituità $_FILES['userfile']['size'] a 0, e $_FILES['userfile']['tmp_name'] vuoto.
Il file sarà eliminato dalla directory temporanea al termine della richiesta se non è stato mosso e rinominato.
Esempio 38-3. Upload di una serie di file Il PHP supporta le matrici HTML anche con i file.
|
Dalla versione 4.2.0, il PHP restituisce un codice di errore nella matrice del file. Il codice di errore si trova nell'indice error e viene valorizzato durante l'upload del file da parte del PHP. In altre parole l'errore può essere trovato in $_FILES['userfile']['error'].
Valore: 0; Non vi sono errori, l'upload è stato eseguito con successo.
Valore: 1; Il file inviato eccede le dimensioni specificate nel parametro upload_max_filesize di php.ini.
Valore: 2; Il file inviato eccede le dimensioni specificate nel parametro MAX_FILE_SIZE del form.
Valore: 3; Upload eseguito parzialmente.
Valore: 4; Nessun file è stato inviato.
Valore: 6; Mancanza della cartella temporanea. Inserito in PHP 4.3.10 e PHP 5.0.3.
Nota: Questi valori sono diventate costanti PHP a partire dal PHP 4.3.0.
La voce MAX_FILE_SIZE non può specificare una dimensione del file maggiore di quella impostata dal parametro upload_max_filesize del file php.ini. L'impostazione di default è 2 Megabytes.
Se si è impostato un limite di memoria memory_limit può essere necessario ampliarlo. Occorre essere certi di impostare memory_limit alle dimensioni appropriate.
Se max_execution_time è impostato ad un valore basso, l'esecuzione dello script può eccedere tale valore. Ampliare max_execution_time ad un tempo sufficiente per l'upload.
Nota: max_execution_time influisce solo sul tempo di esecuzione dello script. Il tempo utilizzato per attività esterno allo script, tipo le chiamate di sistema system(), o la funzione sleep(), le query nei database, il tempo inpiegato nell'upload del file non è considerato nel computo del tempo di esecuzione dello script.
Avvertimento |
max_input_time imposta il tempo massimo, in secondi, in cui lo script può ricevere dati; questo comprende l'upload di file. Per file di grandi dimensioni o molteplici file, o su connessioni lente, il valore di default 60 seconds può essere sforato. |
Se post_max_size è impostato ad un valore troppo piccolo, non si può inviare file di grosse dimensioni. Impostare post_max_size alle dimensioni appropriate.
Non controllare il file su cui si sta operando potrebbe dare agli utenti accesso a informazioni sensibili contenute in altre directory.
Si noti che che il server CERN httpd sembra eliminare qualsiasi cosa a partire dal primo spazio nell'header mime content-type che riceve dal client. Fino a che questo si verificherà, il server CERN httpd non supporterà la possibilità di caricare file.
A causa della varietà di formati di directory, non si è in grado di garantire che nomi di file strani (ad esempio contenenti spazi) siano gestiti correttamente.
Un sviluppatore non può mischiare normali campi di input con campi di upload di file con lo stesso nome di campo (utilizzando nomi tipo foo[]).
E' possibile inviare più file contemporanemante utilizzando in input nomi differenti.
E' possibile caricare più file contemporaneamente e avere le informazioni organizzate automaticamente in array. Per questo è necessario utilizzare la medesima sintassi di invio di array da form HTML che è utilizzata con select e checkbox multipli:
Nota: Il supporto per il caricamento di file multipliè stato aggiunto in PHP 3.0.10.
Quando la form è inviata, gli array $_FILES['userfile'], $_FILES['userfile']['name'], e $_FILES['userfile']['size'] saranno inizializzati (come sarà valorizzato $HTTP_POST_FILES per le versioni di PHP precedenti la 4.1.0). Quando il parametro register_globals è impostato a on saranno presenti anche le variabili globali. Ognuno di questi è un array indicizzato numericamente con i valori relativi ai diversi file caricati.
Per esempio, si supponga che i nomi di file /home/test/review.html e /home/test/xwp.out siano inviati. In questo caso, $_FILES['userfile']['name'][0] conterrebbe il valore review.html, e $_FILES['userfile']['name'][1] conterrebbe il valore xwp.out. Analogamente, $_FILES['userfile']['size'][0] conterrebbe la dimensione di review.html, e così via.
Anche $_FILES['userfile']['name'][0], $_FILES['userfile']['tmp_name'][0], $_FILES['userfile']['size'][0], e $_FILES['userfile']['type'][0] sono impostati.
Il supporto al metodo PUT è cambiato tra PHP 3 e PHP 4. In PHP 4 occorre utilizzare il flusso standard di input per leggere il contenuto di un PUT HTTP.
Esempio 38-5. Salvataggio di un file HTTP PUT con PHP 4
|
Nota: Tutta la documentazione che segue si applica solo a PHP 3.
PHP fornisce supporto per il metodo HTTP PUT utilizzato da programmi come Netscape Composer e W3C Amaya. Le richieste PUT sono molto più semplici rispetto al caricamento di un file, e assomigliano a
Questo significa che normalmente il programma remoto intende salvare il contenuto della richesta come : /path/filename.html nel filesystem sul server web. Non è ovviamente una buona idea per Apache o PHP lasciare a un qualsiasi utente la possibilità di sovrascrivere file sul server web. Quindi, per gestire questa richiesta si deve chiedere al server web che si vuole che sia un certo script PHP a gestire la richiesta stessa. In Apache si ottiene questo con la direttiva Script. Può essere posta quasi ovunque nel file di configurazione di Apache. Un posto frequente è all'interno di un blocco <Directory> oppurte all'interno del blocco <Virtualhost>. Un linea come la seguente è sufficiente:
Questo chiede ad Apache di inviare tutte le richieste PUT che soddisfano il contesto in cui si è inserito questo comando allo script put.php. Questo richiede, naturalmente, che sia abilitato PHP per l'estensione .php e che PHP sia attivo.
All'interno del file put.php si può inserire qualcosa del tipo:
Questo copia il file nella posizione chiesta dal programma remoto. E' probabile che si vogliano effettuare dei controlli o autenticazioni dell'utente prima di effettuare questa copia. L'unica magia qui presente è che quando PHP vede una richiesta con metodo PUT memorizza il file caricato in un file temporaneo così come per i file caricati con il metodo POST. Quando la richiesta termina, questo file temporaneo è eliminato. Quindi il gestore della richiesta PUT deve copiare il file da qualche parte. Il nome del file temporaneo è memorizzato nella variabile $PHP_PUT_FILENAME, ed è possibile vedere il nome del file di destinazione nella variabile $REQUEST_URI (potrebbe variare su web server diversi da Apache). Qusto nome di file di destinazione è quello specificato dal client remoto. Non è necessario seguire le indicazioni del client. E' possibile, per esempio, copiare tutti i file caricati in una apposita directory.
Se allow_url_fopen è abilitato in php.ini, si possono usare gli URL HTTP e FTP con la maggior parte delle funzioni che richiedono nomi di file come parametri, incluse le funzioni require(), require_once(), include() e include_once(). Vedere Appendice M per maggiori dettagli sui protocolli supportati dal PHP.
Nota: In PHP 4.0.3 e precedenti, al fine di poter utilizzare gli URL wrapper, occorreva specificare l'opzione di configurazione --enable-url-fopen-wrapper.
Nota: Al momento, le versioni Windows di PHP precedenti la 4.3, non supportano l'accesso remoto ai file con le seguenti funzioni: include(), include_once(), require() e require_once() e le funzioni imagecreatefromXXX del modulo Riferimento LVI, Funzioni per le immagini.
Per esempio, si può usare per aprire un file da un web server remoto, elaborare i dati presi da remoto, e usarli per effetuare delle query, o semplicemente visualizzarli con lo stile del proprio sito web.
Esempio 39-1. Leggere il titolo di una pagina web remota
|
Si può anche scrivere in un file remoto via FTP (se l'utente con cui ci si connette ha le autorizzazioni necessarie). Si possono solamente creare nuovi file usando questo metodo, se si prova a sovrascrivere un file che già esiste, fopen() non avrà successo.
Per connettersi con un utenti diversi da 'anonymous' si ha bisogno di specificare lo username (e la relativa password) assieme all'URL, in questo modo: 'ftp://user:password@ftp.example.com/directory/del/file'. (Si può usare lo stesso tipo di sintassi per accedere a file via HTTP quando richiedono autenticazione Basic).
Esempio 39-2. Salvataggio di dati su server remoto
|
Nota: Le seguenti note si applicano a partire dalla versione 3.0.7.
Internamente il PHP mantiene lo stato della connessione. Si hanno 3 possibili stati:
0 - NORMAL
1 - ABORTED
2 - TIMEOUT
Quendo uno script PHP viene eseguito normalmente si trova nello stato NORMAL. Se il client remoto si disconnette viene attivato il flag ABORTED. La disconnessione di un client remoro è generalmente causata dalla pressione del tasto STOP da parte dell'utente. Se invece si raggiunge il limite di tempo imposto dal PHP (vedere set_time_limit()) si attiva lo stato TIMEOUT.
Si può decidere se la disconnessione del client debba fare abortire lo script o meno. In certi casi è più pratico lasciare finire lo script anche se non c'è più il browser remoto a ricevere i dati. Tuttavia il comportamento di default è di fare abortire lo script quando il client remoto si disconnette. Questo comportamento può essere impostato tramite la direttiva di php.ini ignore_user_abort oppure tramite la corrispondente direttiva "php_value ignore_user_abort" del file .conf di Apache oppure con la funzione ignore_user_abort(). Se non si segnala al PHP di ignorare la disconssessione dell'utente lo script sarà interrotto. Unica eccezione si ha con la registrazione di una funzione di chiusura utilizzando register_shutdown_function(). Con una funzione di shutdown, quando l'utente remoto preme il bottone di STOP, alla prima occasione in cui lo script tenterà di produrre un output, il PHP intercetterà che la connessione è interrotta e richiamerà la funzione di shutdown. Questa funzione sarà richiamata anche al normale termine dello script, pertanto per eseguire passi differenti in caso di disconnessione del client occorre utilizzare la funzione connection_aborted(). Questa funzione restituisce TRUE se la connessione è stata interrotta.
Uno script può essere fermato dal timer incorporato nel PHP. Per default il timeout è impostato a 30 secondi. Tale limite può essere variato agendo sulla direttiva max_execution_time nel php.ini o nel corrispondente parametro php_value max_execution_time nella configurazione di Apache, oppure con la funzione set_time_limit(). Quando termina il tempo impostato lo script viene interrotto, se è stata prevista una funzione di shutdown, questa verrà eseguita. All'interno di questa funzione si può discriminare se è stata attivata per lo scadere del timeout utilizzando la funzione connection_timeout(). Questa restituisce 2 se la funzione di shutdown è stata chiamata per lo scadere del tempo a disposizione.
Un aspetto che occorre notare sui stati ABORTED e TIMEOUT è che possono essere attivi contemporaneamente. Questo può accadere se si è impostato il PHP affinchè ignori le interruzioni da parte dell'utente. Infatti il PHP continua a tenere traccia della disconnessione dell'utente, ma, semplicemente, non viene interrotto lo script. Quindi, quando termina il tempo, lo script sarà interrotto e verrà richiamata la funzione di shutdown, se presente. In questa situazione si avrà che connection_status() restituirà 3.
Connessioni persistenti sono collegamenti che non vengono chiusi quando l'esecusione di uno script viene terminata. Quando è richiesta una connessione persistente, PHP controlla se esiste già una identica connessione persistente (che è rimasta aperta da prima) - e se esiste, la usa. Se non esiste, crea il collegamento. Una connessione 'identica' è una connessione aperta verso lo stesso host, con lo stesso username e la stessa password (dove applicabile).
Chi non ha molta familiarità con il modo in cui lavorano i server web e di come essi distribuiscano il carico potrebbero confondere le connessioni permanenti per ciò che esse non sono. In particolare, non danno la possibilità di aprire 'sessioni utente' sullo stesso collegamento, non danno la possibilità di gestire una transazione in maniera efficiente e sopratutto non fanno molte altre cose. Infatti, per essere molto chiari su questo punto, le connessioni persistenti non hanno nessuna funzionalià che non era disponibile con le loro omonime non-persistenti.
Perché?
Questo ha a che fare con il modo in cui i server web operano. Ci sono tre modi in cui un server web può utilizzare PHP per generare le pagine web.
Il primo metodo ` quello di usare il PHP come un "wrapper" (involucro) CGI. Quando viene eseguito in questa modalità, per ogni pagina che viene richiesta al server web che contenga del codice PHP, viene creata e, alla fine dell'esecuzione, distrutta, una istanza dell'interprete PHP. Poiché viene distrutta alla fine di ogni richiesta, qualunque risorsa abbia acquisito (come ad esempio un collegamento ad un server di database SQL) verrà anch'essa distrutta. In questo caso, non vi è nessun guadagno nell'usare le connessioni persistenti -- semplicemente esse non persistono.
Il secondo, e più popolare, metodo è quello di eseguire il programma PHP come modulo in un server web multiprocesso, cosa che attualmente include solo Apache. Un server multiprocesso ha tipicamente un processo (il padre) che coordina un insieme di processi (i suoi figli) che sono quelli che generano le pagine web. Quando arriva una richiesta da parte di un client, questa è passata ad uno dei figli che in quel momento non è già occupato a servire un altro client. Questo significa che quando lo stesso client effettua una seconda richiesta al server, esso potrà essere servito da un diverso processo figlio rispetto a quello della prima volta. Quando si aprono delle connessioni persistenti, ciascuna pagina successiva che richiede dei servizi SQL, può riutilizzare la connessione al server SQL precedente.
L'ultimo metodo è quello di usare il PHP come una plug-in per un server web multithread. Attualmente PHP 4 supporta ISAPI, WSAPI e NSAPI (su piattaforma Windows), i quali permettono di usare PHP come una plug-in sui server web multithread come FastTrack (iPlanet) di Netscape, Internet Information Server (IIS) di Microsoft e WebSite Pro di O'Reilly. Il comportamento è essenzialmente lo stesso che si ha nel modello multiprocesso descritto prima. Si noti che il supporto SAPI non è disponibile in PHP 3.
Se le connessioni persistenti non hanno nessuna funzionalità aggiuntiva, perch´ usarle?
La risposta, in questo caso è estremamente semplice: efficienza. Le connessioni persistenti sono utili se il carico di lavoro necessario per aprire una connessione al server SQL è alto. Che il carico sia molto alto o meno dipende da molti fattori. Quali, il tipo di database che si utilizza, il fatto che esso si trovi sulla stessa macchina sulla quale si trova il server web, quanto carico di lavoro ha la macchina sulla quale si trova il server SQL, e molte altre ragioni. Il fatto importante è che se il carico di lavoro necessario per aprire le connessioni è alto, le connessioni persistenti possono aiutare in maniera considerevole. Fanno in modo che il processo figlio si colleghi semplicemente una volta durante la sua intera vita, invece di collegarsi ogni volta che processa una pagina che richiede una connessione al server SQL. Questo significa che per ogni figlio che ha aperto una connessione persistente, si avrà una nuova connessione persistente aperta verso il server. Per esempio, se si hanno 20 diversi processi figlio che eseguono uno script che crea una connessione persistente al server SQL server, si avranno 20 diverse connessioni al server SQL, una per ogni figlio.
Si fa notare, tuttavia, che questo può avere degli svantaggi se si fa uso di un database che ha un limite al numero di connessioni, minore rispetto al numero delle connessioni persistenti dei procesi figlio. Se per esempio di usa un database con 16 connessioni simultanee, e durante un periodo di intensa attività del web server, 17 processi figlio cercano di collegarsi, uno non sarà in grado di farlo. Se nei vostri script ci sono bug che non permettono alle connessioni di chiudersi in maniera regolare (come ad esempio un loop infinito), un database con sole 16 connessioni diventerà rapidamente saturo. Fare riferimento alla documentazione del database per informazioni su come gestire connessioni abbandonate o inattive.
Avvertimento |
Ci sono un paio di altri caveat da tenere in considerazione quando si usano le connessioni persistenti. Uno è che quando si usa il table locking su una connessione persistente, se lo script, per una qualunque ragione non è in grado di rimuovere il blocco, allora i successivi script che useranno la stessa connessione rimarranno bloccati in maniera indefinita e potrebbe essre necessario riavviare il server httpd o il server database. Un altro è che quando si usano le transazioni, un transaction block verrà trasferito anche allo script successivo che usa la medesima connessione, se lo script in esecuzione termina prima che sia terminato il transaction block. In entrambi i casi, si può usare register_shutdown_function() per registrare una semplice funzione di pulizia per sbloccare le tabelle o effettuare il roll back delle transaczioni. Sarebbe meglio non dover affrontare il problema, semplicemente non usando le connessioni persistenti negli script che usano i lock delle tabelle o le transaczioni (si possono comunque usare in altre situazioni). |
Sommario importante. Le connessioni persistenti sono state pensate per avere una mappatura uno-a-uno con le connessioni di tipo normale. Ciò significa che si dovrebbe sempre essere in grado di cambiare una connessione persistente con una connessione non-persistente, e che questo non dovrebbe cambiare il modo in cui lo script si comporta. Può (e probabilmente succederà) cambiare l'efficienza dello script, ma non il suo comportamento!
Vedere anche fbsql_pconnect(), ibase_pconnect(), ifx_pconnect(), ingres_pconnect(), msql_pconnect(), mssql_pconnect(), mysql_pconnect(), ocipLogon(), odbc_pconnect(), ora_pLogon(), pfsockopen(), pg_pconnect() e sybase_pconnect().
La modalità Safe Mode è un tentativo di risolvere il problema di sicurezza derivante dalla condivisione del server. Dal punto di vista architetturale non è corretto cercare di risolvere questo problema al livello del PHP, ma poiché le alternative al livello del web server e del SO (Sistema Operativo) non sono realistiche, in molti, specialmente ISP (Internet Service Provider), utilizzano la modalità sicura.
Tabella 42-1. Direttive di configurazione della Modalità sicura e Sdella icurezza
Nome | Default | Changeable | Changelog |
---|---|---|---|
safe_mode | "0" | PHP_INI_SYSTEM | |
safe_mode_gid | "0" | PHP_INI_SYSTEM | Disponibile dal PHP 4.1.0. |
safe_mode_include_dir | NULL | PHP_INI_SYSTEM | Disponibile dal PHP 4.1.0. |
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 only | Disponibile dal PHP 4.0.1. |
disable_classes | "" | php.ini only | Disponibile dal PHP 4.3.2. |
Breve descrizione dei parametri di configurazione.
Abilita o disabilita la modalità sicura di PHP's. Leggere il capitolo Sicurezza per ulteriori informazioni.
Di 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 colon (semi-colon on Windows) separated path in a fashion similar 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. You have to use / as directory separator on all environments including Windows.
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 working directory of the script will be used as the base-directory. This is, however, a little dangerous as the working directory of the script can easily be changed with chdir().
In httpd.conf, open_basedir can be turned off (e.g. for some virtual hosts) the same way as any other configuration directive with "php_admin_value open_basedir none".
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-delimited 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.
This directive allows you to disable certain classes for security reasons. It takes on a comma-delimited list of class names. disable_classes is not affected by Safe Mode.
This directive must be set in php.ini For example, you cannot set this in httpd.conf.
Availability note: This directive became available in PHP 4.3.2
See also: register_globals, display_errors, and log_errors
Le direttive di configurazione che controllano la modalità sicura sono:
safe_mode = Off open_basedir = safe_mode_exec_dir = safe_mode_allowed_env_vars = PHP_ safe_mode_protected_env_vars = LD_LIBRARY_PATH disable_functions = |
Quando safe_mode è attiva (on), il PHP verifica se il proprietario dello script in esecuzione e il proprietario del file su cui si sta operando con una funzione sui file, coincidono. Per esempio:
-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 |
Se, invece di safe_mode, viene definita una directory open_basedir allora tutte le operazioni sui file saranno limitate ai file sottostanti la directory specificata. Per esempio (nel file httpd.conf di Apache):
<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 |
È possibile inoltre disabilitare le singole funzioni. Se si aggiunge la seguente riga al file php.ini:
disable_functions readfile,system |
Warning: readfile() has been disabled for security reasons in /docroot/script.php on line 2 |
Questo è un elenco probabilmente ancora incompleto e forse non esatto delle funzioni limitate da Safe Mode.
Tabella 42-2. Funzioni limitate dalla modalità sicura
Funzioni | Limitazioni |
---|---|
dbmopen() | Controlla che i file o le directory su cui si sta lavorando, abbiano lo stesso UID dello script che è in esecuzione. |
dbase_open() | Controlla che i file o le directory su cui si sta lavorando, abbiano lo stesso UID dello script che è in esecuzione. |
filepro() | Controlla che i file o le directory su cui si sta lavorando, abbiano lo stesso UID dello script che è in esecuzione. |
filepro_rowcount() | Controlla che i file o le directory su cui si sta lavorando, abbiano lo stesso UID dello script che è in esecuzione. |
filepro_retrieve() | Controlla che i file o le directory su cui si sta lavorando, abbiano lo stesso UID dello script che è in esecuzione. |
ifx_*() | sql_safe_mode restrictions, (!= Safe Mode) |
ingres_*() | sql_safe_mode restrictions, (!= Safe Mode) |
mysql_*() | sql_safe_mode restrictions, (!= Safe Mode) |
pg_loimport() | Controlla che i file o le directory su cui si sta lavorando, abbiano lo stesso UID dello script che è in esecuzione. |
posix_mkfifo() | Controlla che la directory su cui si sta lavorando, abbia lo stesso UID dello script che è in esecuzione. |
putenv() | Obbedisce le direttive del file ini safe_mode_protected_env_vars e safe_mode_allowed_env_vars. Vedere la documentazione relativa on putenv() |
move_uploaded_file() | Controlla che i file o le directory su cui si sta lavorando, abbiano lo stesso UID dello script che è in esecuzione. |
chdir() | Controlla che la directory su cui si sta lavorando, abbia lo stesso UID dello script che è in esecuzione. |
dl() | Questa funzione è disabilitata nella modalitàsafe-mode |
backtick operator | Questa funzione è disabilitata nella modalitàsafe-mode |
shell_exec() (functional equivalent of backticks) | Questa funzione è disabilitata nella modalità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() | Controlla che la directory su cui si sta lavorando, abbia lo stesso UID dello script che è in esecuzione. |
rmdir() | Controlla che i file o le directory su cui si sta lavorando, abbiano lo stesso UID dello script che è in esecuzione. |
rename() | Controlla che i file o le directory su cui si sta lavorando, abbiano lo stesso UID dello script che è in esecuzione. Controlla che la directory su cui si sta lavorando, abbia lo stesso UID dello script che è in esecuzione. |
unlink() | Controlla che i file o le directory su cui si sta lavorando, abbiano lo stesso UID dello script che è in esecuzione. Controlla che la directory su cui si sta lavorando, abbia lo stesso UID dello script che è in esecuzione. |
copy() | Controlla che i file o le directory su cui si sta lavorando, abbiano lo stesso UID dello script che è in esecuzione. Controlla che la directory su cui si sta lavorando, abbia lo stesso UID dello script che è in esecuzione. (on source and target) |
chgrp() | Controlla che i file o le directory su cui si sta lavorando, abbiano lo stesso UID dello script che è in esecuzione. |
chown() | Controlla che i file o le directory su cui si sta lavorando, abbiano lo stesso UID dello script che è in esecuzione. |
chmod() | Controlla che i file o le directory su cui si sta lavorando, abbiano lo stesso UID dello script che è in esecuzione. In addition, you cannot set the SUID, SGID and sticky bits |
touch() | Controlla che i file o le directory su cui si sta lavorando, abbiano lo stesso UID dello script che è in esecuzione. Controlla che la directory su cui si sta lavorando, abbia lo stesso UID dello script che è in esecuzione. |
symlink() | Controlla che i file o le directory su cui si sta lavorando, abbiano lo stesso UID dello script che è in esecuzione. Controlla che la directory su cui si sta lavorando, abbia lo stesso UID dello script che è in esecuzione. (note: only the target is checked) |
link() | Controlla che i file o le directory su cui si sta lavorando, abbiano lo stesso UID dello script che è in esecuzione. Controlla che la directory su cui si sta lavorando, abbia lo stesso UID dello script che è in esecuzione. (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()! |
Qualsiasi funzione che utilizza php4/main/fopen_wrappers.c | ?? |
A partire dalla versione 4.3.0, il PHP supporta un nuovo tipo di SAPI (Server Application Programming Interface) chiamata CLI che significa Interfaccia per la Linea di Comando (Command Line Interface). Come il nome stesso suggerisce, questo tipo di SAPI è mirato allo sviluppo di applicazioni shell (o desktop) con PHP. Esistono alcune differenze tra la CLI SAPI e le altre SAPI; queste saranno illustrate nel corrente capitolo. Val la pena ricordare che CLI e CGI sono differenti SAPI sebbene condividano il medesimo comportamento in diverse situazioni.
La CLI SAPI è stata rilasciata per la prima volta con PHP 4.2.0, ma era ancora sperimentale e quindi doveva essere esplicitamente abilitata con --enable-cli nell'esecuzione di ./configure. A partire dal PHP 4.3.0 la CLI SAPI non viene più considerata sperimentale e quindi l'opzione --enable-cli è attivata per default. Vedere --disable-cli per disabilitare l'opzione.
Dal PHP 4.3.0, il nome, la posizione, e l'esistenza di eseguibili CLI/CGI differirà in base a come il PHP sarà installato sul sistema. Per default quando si esegue il make, si compila sia la versione CLI sia la versione CGI e saranno poste rispettivamente in sapi/cgi/php e sapi/cli/php a partire dalla directory dei sorgenti. Occorre notare che entrambi gli eseguibili sono chiamati php. Ciò che accade durante l'esecuzione di dipende dalla linea di configurazione. Se durante la configurazione si è scelto un modulo SAPI, tipo apxs, o si è attivato --disable-cgi, l'eseguibile CLI viene copiato in durante make install, altrimenti in questa cartella sarà posto l'eseguibile CGI. Così, per esempio, se si ha come parametro di configurazione --with--apxs allora l'eseguibile CLI sarà copiato in {PREFIX}/bin/php durante make install. Se si vuole evitare l'installazione dell'eseguibile CGI, utilizzare make install-cli dopo make install. In alternativa si può specificare --disable-cgi nella linea di configurazione.
Nota: Poichè sia --enable-cli sia --enable-cgi sono abilitati per default, avere semplicemente --enable-cli nella linea di configurazione non significa necessariamente che l'eseguibile CLI sia copiato come {PREFIX}/bin/php con l'esecuzione di make install.
Nel pacchetto per Windows, nelle versioni tra PHP 4.2.0 e PHP 4.2.3, l'eseguibile CLI era presente come php-cli.exe, nella medesima cartella della versione CGI php.exe. A partire dal PHP 4.3.0 nel pacchetto per Windows la versione CLI viene distribuita come php.exe in una cartella a parte chiamata cli, avendo perciò cli/php.exe. A partire dal PHP 5, la versione CLI viene inserita nella cartella principale, con il nome php.exe. La versione CGI sarà chiamata php-cgi.exe.
Sempre dal PHP 5, sarà introdotto un nuovo file chiamato php-win.exe. Questo è equivalente alla versione CLI, tranne che php-win non visualizzerà nulla e quindi non vi sarà la finestra di console (non compare la fienstra dos nello schermo). Questo comportamento è stato ripreso da php-gtk. Si dovrebbe configurare il PHP con --enable-cli-win32.
Quale SAPI ho?: Da shell, digitando php -v si avrà l'informazione di quale php si tratta, CGI o CLI. Vedere anche la funzione php_sapi_name()e la costante PHP_SAPI per dettagli.
Nota: Una pagina stile man di Unix è stata aggiunta in PHP 4.3.2. La si può visualizzare digitando man php da linea di comando.
Le principali differenze tra la CLI SAPI e le altre SAPI sono:
A differenza di CGI SAPI, non sono inviate in output delle intestazioni.
Mentre nella CGI SAPI esiste un modo per sopprimere le intestazioni, nella CLI SAPI non si ha una opzione per abilitare le intestazioni.
Per default CLI parte in modalità silenziosa, si è mantenuto, comunque, l'opzione -q e --no-header per motivi di compatibilità; in questo modo si possono utlizzare i vecchi script CGI.
Non cambia la directory di lavoro in quella dello script. (E' rimasta l'opzione -C e --no-chdir per compatibilità)
Messaggi di errore in formato testo (non formattati in HTML).
Esistono, inoltre, alcune direttive del php.ini che sono forzate nell'impostazione dalla CLI SAPI poichè non hanno senso nell'ambiente di shell:
Tabella 43-1. Direttive del php.ini forzate
Direttiva | CLI SAPI valore di default | Commento |
---|---|---|
html_errors | FALSE | E' difficile leggere i messaggi di errore nella shell quando sono affogati in tag HTML prive di significato; pertanto il default della direttiva è impostato a FALSE. |
implicit_flush | TRUE | E' desiderabile che ogni tipo di output proveniente da print(), echo() e simili sia scritto immediatamente e non venga bufferizzato. Tuttavia è ancora possibile utilizzare le funzioni di controllo dell'output se si desidera ritardare o manipolare lo standard output. |
max_execution_time | 0 (unlimited) | Considerate le svariate possibilità offerte da PHP nell'ambiente di shell, il tempo massimo di esecuzione è stato impostato a infinito. Mentre nelle applicazione scritte per il web i tempi di esecuzione sono rapidi, le applicazioni di shell tendono ad avere tempi di esecuzione molto più lunghi. |
register_argc_argv | TRUE |
Poichè è impostato a TRUE nella CLI SAPI si ha sempre la possibilità di accedere alla variabili argc (numero di argomenti passati all'applicazione) e argv (matrice degli argumenti). A partire da PHP 4.3.0, quando si utilizza la CLI SAPI le variabili PHP $argc e $argv sono sempre registrate e valorizzate in modo appropriato. Prima di questa versione la creazione di queste variabili era coerente con il comportamento delle versioni CGI e MODULO le quali richiedevano che la direttiva PHP register_globals fosse impostata a on. A prescindere dalla versione o dall'impostazione di register_globals si può sempre accedere alle variabili $_SERVER o $HTTP_SERVER_VARS. Esempio: $_SERVER['argv'] |
Nota: Queste direttive non possono essere inizializate con altri valori dal file di configurazione php.ini o da uno personalizzato (se specifictao). Questa è una limitazione perchè questi valori di default sono applicati dopo avere esaminato tutti i file di configurazione. Tuttavia i loro valori possono essere cambiati durante l'esecuzione (operazione che non ha senso per queste direttive, ad esempio register_argc_argv).
Per potere lavorare meglio con le shell, sono state definite le seguenti costanti:
Tabella 43-2. Costanti specifiche per CLI
Costante | Descrizione | ||
---|---|---|---|
STDIN |
Un flusso già aperto allo stdin. Questo evita di
aprirlo con
| ||
STDOUT |
Un flusso già aperto allo stdout. Questo evita di
aprirlo con
| ||
STDERR |
Un flusso già aperto allo stderr. Questo evita di
aprirlo con
|
Stante a quanto descritto non occorre più aprire in autonomia flussi per, ad esempio, lo stderr, ma semplicemente si può usare le costanti anzichè una nuova risorsa di flusso:
php -r 'fwrite(STDERR, "stderr\n");' |
La CLI SAPI non cambia la directory corrente in quella dello script eseguito!
Il seguente esempio illustra la diferenza rispetto alla CGI SAPI:
<?php // Semplice esempio di test chiamato test.php echo getcwd(), "\n"; ?> |
Quando si usa la versione CGI, si avrà il seguente output:
$ pwd /tmp $ php -q another_directory/test.php /tmp/another_directory |
Utilizzando la versione CLI SAPI abbiamo:
$ pwd /tmp $ php -f another_directory/test.php /tmp |
Nota: La CGI SAPI supporta il comportamento della CLI SAPI attivando l'opzione -C quando viene eseguito da linea di comando.
L'elenco completo delle opzioni del PHP disponibili da linea di comando può essere visualizzato in qualsiasi momento eseguendo il PHP con l'opzione -h:
Usage: php [options] [-f] <file> [--] [args...] php [options] -r <code> [--] [args...] php [options] [-B <begin_code>] -R <code> [-E <end_code>] [--] [args...] php [options] [-B <begin_code>] -F <file> [-E <end_code>] [--] [args...] php [options] -- [args...] -a Run interactively -c <path>|<file> Look for php.ini file in this directory -n No php.ini file will be used -d foo[=bar] Define INI entry foo with value 'bar' -e Generate extended information for debugger/profiler -f <file> Parse <file>. -h This help -i PHP information -l Syntax check only (lint) -m Show compiled in modules -r <code> Run PHP <code> without using script tags <?..?> -B <begin_code> Run PHP <begin_code> before processing input lines -R <code> Run PHP <code> for every input line -F <file> Parse and execute <file> for every input line -E <end_code> Run PHP <end_code> after processing all input lines -H Hide any passed arguments from external tools. -s Display colour syntax highlighted source. -v Version number -w Display source with stripped comments and whitespace. -z <file> Load Zend extension <file>. args... Arguments passed to script. Use -- args when first argument starts with - or script is read from stdin |
La vesione CLI SAPI ha tre differenti modi per eseguire il codice PHP:
Dire al PHP di eseguire certi file.
php my_script.php php -f my_script.php |
Passare il codice PHP da eseguire direttamente da linea di comando.
php -r 'print_r(get_defined_constants());' |
Nota: Osservando con attenzione l'esempio si nota l'assenza dei tag di inizio e fine! L'opzione -r non li richiede. L'uso dei tag genera un errore di parsing.
Si può passare il codice PHP da eseguire via standard input (stdin).
Questo da la possibilità di generare dinamicamente del codice PHP e passarlo all'eseguibile, come illustrato nel seguente esempio (fittizio):
$ some_application | some_filter | php | sort -u >final_output.txt |
Come qualsiasi applicazione di shell, anche l'eseguibile PHP accetta diversi argomenti, ma anche lo script PHP può ricevere argomenti. Il numero degli argomenti passabili allo script non è limitato dal PHP (si rammenta che la shell ha un limite nel numero di caratteri che possono essere passati; solitamente non si raggiunte questo limite). Gli argomenti passati allo script sono disponibili nell'array $argv. L'indice zero contiene sempre il nome dello script (che è - nel caso in cui il codice PHP provenda o dallo standard input o dalla linea di comando con l'opzione -r). La seconda variabile globale registrata è $argc la quale contiene il numero degli elementi nella matrice $argv (non è il numero degli argomenti passati allo script).
Fino a quando gli argomenti passati allo script non iniziano con il carattere - non si deve prestare alcuna cautela. Tuttavia se si passa allo script argomenti che iniziano con - si hanno dei problemi perchè lo stesso PHP ritiene di doverli gestire. Per evitare ciò occorre utilizzare il separatore di argomenti --. Dopo che il PHP ha incontrato questo separatore, ogni argomento verrà passato direttamente allo script.
# Questo non visualizzerà il codice passato, ma l'elenco delle opzioni $ php -r 'var_dump($argv);' -h Usage: php [options] [-f] <file> [args...] [...] # Questo passerà il '-h'allo script ed eviterà al PHP di visualizzare le opzioni $ php -r 'var_dump($argv);' -- -h array(2) { [0]=> string(1) "-" [1]=> string(2) "-h" } |
Tuttvia esiste un'altro modo per eseguire gli script PHP. Si può scrivere uno script la cui prima riga inizi con #!/usr/bin/php. Seguendo questa regola si può posizionare il normale codice PHP tra i tag di apertura e chiusura del PHP. Una volta impostati correttamente gli attributi del file (ad esempio chmod +x test) lo script può essere eseguito come una normale shell o script perl:
#!/usr/bin/php <?php var_dump($argv); ?> |
$ chmod +x test $ ./test -h -- foo array(4) { [0]=> string(6) "./test" [1]=> string(2) "-h" [2]=> string(2) "--" [3]=> string(3) "foo" } |
I parametro lunghi sono disponibili dal PHP 4.3.3.
Tabella 43-3. Opzioni della linea di comando,
Parametro | Parametro lungo | Descrizione | |||
---|---|---|---|---|---|
-a | --interactive |
Esegue il PHP in modo interattivo. | |||
-c | --php-ini |
Con questa opzione si può sia specificare la directory in cui cercare il php.ini o si può specificare un file INI personalizzato (che non deve necessariamente chiamarsi php.ini), ad esempio:
| |||
-n | --no-php-ini |
Ignora del tutto il php.ini. Opzione disponibile dal PHP 4.3.0. | |||
-d | --define |
Questa opzione permette di impostare valori personalizzati per qualsiasi delle direttive di configurazione previste in php.ini. La sintassi è:
Esempi (le linee vanno a capo per motivi di layout):
| |||
-e | --profile-info |
Genera informazioni estese per il debugger/profiler. | |||
-f | --file |
Analizza ed esegue il file passato con l'opzione -f. Questo parametro è opzionale e può essere omesso. Basta fornire il nome del file da eseguire. | |||
-h e -? | --help e --usage | Con questa opzione si ha l'elenco dei comandi di linea ed una breve descrizione di questi. | |||
-i | --info | Questa opzione della linea di comando richiama la funzione phpinfo(), e ne visualizza il risultato. Se il PHP non funziona correttamente, è opportuno utilizzare php -i per verificare se sono visualizzati messaggi di errore prima o al posto della tabella con le informazioni. Fare attenzione quando si usa la modalità CGI, l'output è in formato HTML e quindi abbastanza abbondante. | |||
-l | --syntax-check |
Questa opzione fornisce un metodo pratico per eseguire un controllo sintattico di un dato codice PHP. Se il controllo ha successo, verrà visualizzato il testo No syntax errors detected in <filename> e alla shell sarà restituito il codice 0. Se si rilevano errori si avrà il testo Errors parsing <filename>, inoltre si avranno anche i messaggi di errore del parser ed alla shell sarà restituito il codice 255. Questa opzione non rileva errori fatali (tipo funzioni non definite). Occorre utilizzare l'opzione -f se si desidera rilevare gli errori fatali.
| |||
-m | --modules |
Utilizzare questa opzione per visualizzare i moduli PHP e di Zend integrati (e quindi caricati):
| |||
-r | --run |
Questa opzione permette l'esecuzione di codice PHP direttamente da linea di comando. I tag PHP di apertura e di chiusura (<?php e ?>) non sono necessari anzi, se presenti, causano un errore del parser.
| |||
-B | --process-begin |
Codice PHP da eseguirsi prima di processare stdin. Aggiunto in PHP 5. | |||
-R | --process-code |
Esegue il codice PHP per ogni linea di input. Aggiunto in PHP 5. In questa modalità si hanno due variabili speciali: $argn ed $argi. $argn contiene la linea PHP in elaborazione al momento, mentre $argi contiene il numero di linea. | |||
-F | --process-file |
Esegue il file PHP per ogni linea di input. Aggiunto in PHP 5. | |||
-E | --process-end |
Codice PHP da eseguirsi dopo il processamento dell'input. Aggiunto in PHP 4. Esempio di utilizzo delle opzioni -B, -R e -E per contare il numero di linea di un progetto.
| |||
-s | --syntax-highlight e --syntax-highlighting |
Visualizza il sorgente con sintassi colorata. Questa opzione utilizza il meccanismo interno di parsing dei file e produce una versione HTML del sorgente e la dirige verso lo standard output. Occore notare che questa funzione genera dei blocchi di tag HTML <code> [...] </code> e non le intestazione HTML.
| |||
-v | --version |
Visualizza le versioni di PHP, PHP SAPI, e Zend nello standard output, ad esempio:
| |||
-w | --strip |
Visualizza il sorgente senza gli spazi e i commenti.
| |||
-z | --zend-extension |
Carica l'estensione Zend. Soltano se si fornisce un nome di file, il PHP tenta di caricare l'estensione dal corrente percorso di default delle librerie (solitamente, sui sistemi Linux, /etc/ld.so.conf). Se si fornisce un nome di file con percorso assoluto, ls libreria non sarà cercata nella directory di default. Un nome di file con percorso relativo indica al PHP di tentare di caricare l'estensione con percorso relativo alla directory corrente. |
L'eseguibile PHP può essere utilizzato per eseguire script PHP in modo indipendente dal server web. Se ci si trova su sistemi Unix, si può aggiungere una prima linea speciale allo script PHP e renderlo eseguibile, in questo modo il sistema sa quale programma deve interpretare lo script. Sui sistemi Windows si può associare php.exe all'estensione .php, o si può scrivere un batch per eseguire gli script tramite PHP. La prima riga inserita per i sistemi Unix non crea problemi in Windows, in questo modo si possono scrivere batch multi-piattaforma. Seguirà un semplice esempio di programma PHP da linea di comando.
Esempio 43-1. Script sviluppato per essere esguito da linea di comando (script.php)
|
Nello script precedente, abbiamo utilizzato la prima riga per indicare che questo file deve essere interpretato dal PHP. Poichè qui lavoriamo con la versione CLI non vengono prodotte intestazioni HTTP. Esistono due variabili che si possono utilizzare nelle applicazioni PHP da linea di comando: $argc e $argv. La prima è il numero di argomenti più uno (il nome dello script). La seconda è una matrice contenente gli argomenti, iniziando dal nome dello script all'indice zero ($argv[0]).
Nel programma precedente abbiamo verificato se i parametri passati erano di più o di meno di uno. Inoltre se l'argomento è --help, -help, -h oppure -?, si visualizza un messaggio di aiuto, visualizzando in modo dinamico il nome dello script. Se si riceve un argomento differente questo sarà visualizzato.
Se si desidera eseguire lo script precedente su Unix, occorre, per prima cosa, renderlo eseguibile, e quindi richiamarlo con script.php echothis oppure script.php -h. Su Windows occorre scrivere un batch per ottenere questo risultato:
Assumendo che programma precedente sia chiamato script.php, che la versione CLI di php.exe sia in c:\php\cli\php.exe questo batch eseguirà lo script con le opzioni passate: script.bat echothis oppure script.bat -h.
Vedere anche la documentazione del modulo Readline per informazioni su funzioni che possono essere utilizzate per migliorare le applicazioni da linea di comando.
Avvertimento |
Questo modulo è SPERIMENTALE. Ovvero, il comportamento di queste funzioni, i nomi di queste funzioni, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questo modulo è a vostro rischio. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Queste funzioni sono disponibili unicamente quando PHP è eseguito come modulo Apache.
Nota: A partire dal PHP 4.3.2, PATH_TRANSLATED non viene più impostata i mplicitamente sotto Apache 2 SAPI, diversamente da quanto accadeva in Apache 1, dove questa veniva impostata allo stesso valore di SCRIPT_FILENAME qualora non fosse già riempita. Questa modifica è stata fatta per adeguarsi allla specifica CGI che impone che PATH_TRANSLATED esista solo se PATH_INFO sia definita.
Gli utilizzatori di Apache 2 possono usare AcceptPathInfo = On in httpd.conf per definire PATH_INFO.
Il comportamento del modulo Apache per PHP è influenzato dalle impostazioni in php.ini. Le impostazioni di configurazione del php.ini possono essere scavalcate attraverso le impostazioni php_flag nel file di configurazione del server o nei file .htaccess locali.
Tabella 1. Opzioni di configurazione di Apache
Nome | Default | Modificabile | Funzione |
---|---|---|---|
engine | On | PHP_INI_ALL | accende o spegne l'interprete PHP |
child_terminate | Off | PHP_INI_ALL | decide se gli script PHP possono richiedere la terminazione dei processi figli alla fine della richiesta HTTP, vedere anche apache_child_terminate() |
last_modified | Off | PHP_INI_ALL | manda la data di modifica degli script nell'header Last-Modified: |
xbithack | Off | PHP_INI_ALL | interpreta i file con il bit di esecuzione impostato, a prescindere dalla loro estensione |
Breve descrizione dei parametri di configurazione.
Questa direttiva è utile solo nella versione di PHP compilata come modulo di Apache. Viene usata dai siti che vogliono spegnere e accendere il parsing PHP in base alla directory o al virtual server corrente. Inserendo engine off nel posto appropriato nel file httpd.conf, il PHP può essere abilitato o disabilitato.
(PHP 4 >= 4.0.5, PHP 5)
apache_child_terminate -- Interrompe il processo apache dopo la presente richiestaapache_child_terminate() informa il processo Apache che sta eseguendo la richiesta PHP corrente di terminare quando l'esecuzione del codice PHP è stata completata. Può essere usata per interrompere un processo dopo che sia stato eseguito uno script con alta occupazione di memoria dal momento che la memoria viene normalmente liberata internamente ma non restituita al sistema operativo.
Nota: La disponibilità di questa caratteristica è controllata dalal direttiva del php.ini child_terminate, che è impostata a off di default.
Questa caratteristica non è inoltre disponibile sulle versioni multithread di apache come, ad esempio, la versione win32.
Vedere anche exit().
Get an Apache environment variable as specified by variable.
This function requires Apache 2 otherwise it's undefined.
The Apache environment variable
Whether to get the top-level variable available to all Apache layers.
(PHP 3 >= 3.0.4, PHP 4, PHP 5)
apache_lookup_uri -- Esegue una richiesta parziale della URI specificata e restituisce tutte le informazioniQuesta funzione esegue una richiesta parziale per una URI. Esegue l'operazione finché ottiene tutte le informazioni importanti sulla risorsa e restituisce queste informazioni in una classe. Le proprietà della classe restituita sono:
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 |
Esempio 1. esempio di apache_lookup_uri()
Questo esempio produrrà un risultato simile al seguente:
|
Nota: apache_lookup_uri() funziona solo quando PHP è installato come modulo Apache.
(PHP 3 >= 3.0.2, PHP 4, PHP 5)
apache_note -- Ricava o imposta una variabile nella tabella notes di Apacheapache_note() è una funzione specifica di Apache che ricava o imposta un valore nella tabella notes di una richiesta HTTP. Se viene invocata con un solo argomento restituisce il valore della nota nome_nota. Se viene chiamata con due argomenti, imposta il valore della nota nome_nota a valore e restituisce il valore precedente della nota nome_nota.
apache_request_headers() restituisce un array associativo contenente tutti gli header HTTP nella richiesta corrente. Questa funzionalità è supportata solo quando PHP è un modulo di Apache.
Nota: Prima del PHP 4.3.0, apache_request_headers() si chiamava getallheaders(). Dopo il PHP 4.3.0, getallheaders() è un alias di apache_request_headers().
Nota: È possibile ottenere il valore delle variabili comuni CGI anche leggendole dalle variabili di ambiente; questo funziona indipendentemente dal fatto che si stia usando PHP come modulo Apache. Utilizzare phpinfo() per ottenere una lista di tutte le variabili d'ambiente disponibili.
Nota: Dal PHP 4.3.3 è possibile utilizzare questa funzione anche con il modulo server NSAPI dei server web Netscape/iPlanet/SunONE
Vedere anche apache_response_headers().
apache_reset_timeout() resets the Apache write timer, which defaults to 300 seconds. With set_time_limit(0); ignore_user_abort(true) and periodic apache_reset_timeout() calls, Apache can theoretically run forever.
This function requires Apache 1.
Restituisce un array contenente tutti gli header della risposta HTTP di Apache. Questa funzione è disponibile solo nel PHP 4.3.0 o successivi.
Nota: Dal PHP 4.3.3 è possibile utilizzare questa funzione anche con il modulo server NSAPI dei server web Netscape/iPlanet/SunONE
Vedere anche getallheaders() e headers_sent().
apache_setenv() imposta il valore della variabile di environment di Apache specificata da variabile.
Nota: Quando si imposta una variabile di environment di Apache, la corrispondente variabile $_SERVER non viene cambiata.
apache_setenv() può essere usata con apache_getenv() su pagine separate o impostare variabili da passare a Server Side Includes (.shtml) chr siano stati inclusi negli script PHP.
Vedere anche apache_getenv().
ascii2ebcdic() è una funzione Apache che è disponibile solo su sistemi operativi basati sull'EBCDIC (OS/390, BS2000). Traduce la stringa codificata in ASCII ascii_str nella sua rappresentazione equivalente EBCDIC (proteggendo i dati binari), e restituisce il risultato.
Vedere anche la funzione duale ebcdic2ascii()
ebcdic2ascii() è una funzione Apache che è disponibile solo su sistemi operativi basati su EBCDIC (OS/390, BS2000). Traduce la stringa codificata in EBCDIC ebcdic_str nella sua rappresentazione equivalente ASCII (proteggendo i dati binari), e restituisce il risultato.
Vedere anche la funzione duale ascii2ebcdic()
getallheaders() è un alias di apache_request_headers(). Restituisce un array associativo contenente tutti gli header HTTP nella richiesta corrente. Leggere la documentazione di apache_request_headers() per ulteriori informazioni sul funzionamento.
Nota: Nel PHP 4.3.0 getallheaders() è diventata un alias di apache_request_headers(). In breve, è stata rinominata. Ciò dipende dal fatto che questa funzione è disponibile soltanto quando PHP è compilato come modulo di Apache.
Nota: Dal PHP 4.3.3 è possibile utilizzare questa funzione anche con il modulo server NSAPI dei server web Netscape/iPlanet/SunONE
Vedere anche apache_request_headers().
virtual() è una funzione specifica Apache che è equivalente a <!--#include virtual...--> in mod_include. Esegue una sotto-richiesta Apache. È utile ad includere script CGI o file .shtml, o qualsiasi altra cosa si voglia fa analizzarea ad Apache. Si noti che per uno script CGI, questo deve generare degli header CGI validi. Quindi, Come minimo deve generare un header Content-type.
Al fine di eseguire la sotto-richiesta, tutti i buffer vengono chiusi e svuotati verso il browser, e anche gli header in attesa vengono inviati.
Dal PHP 4.0.6, è possibile utilizzare virtual() sui file PHP. Comunque è preferibile usare include() o require() se è necessarei includere un altro file PHP.
Nota: Dal PHP 4.3.3 è possibile utilizzare questa funzione anche con il modulo server NSAPI dei server web Netscape/iPlanet/SunONE
The Alternative PHP Cache (APC) is a free and open opcode cache for PHP. It was conceived of to provide a free, open, and robust framework for caching and optimizing PHP intermediate code.
This PECL extension is not bundled with PHP.
Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: http://pecl.php.net/package/apc.
You may download this PECL extension DLL from the PHP Downloads page or at http://snaps.php.net/.
Nota: On Windows, APC expects c:\tmp to exist, and be writable by the web server.
Nota: For more in-depth, highly technical documentation, see the developer-supplied TECHNOTES file .
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Although the default APC settings are fine for many installations, serious users should consider tuning the following parameters.
Tabella 1. APC configuration options
Name | Default | Changeable | Changelog |
---|---|---|---|
apc.enabled | 1 | PHP_INI_ALL | |
apc.shm_segments | 1 | PHP_INI_SYSTEM | |
apc.shm_size | 30 | PHP_INI_SYSTEM | |
apc.optimization | 0 | PHP_INI_ALL | |
apc.num_files_hint | 1000 | PHP_INI_SYSTEM | |
apc.ttl | 0 | PHP_INI_SYSTEM | |
apc.gc_ttl | 3600 | PHP_INI_SYSTEM | |
apc.cache_by_default | On | PHP_INI_SYSTEM | |
apc.filters | "" | PHP_INI_SYSTEM | |
apc.mmap_file_mask | "" | PHP_INI_SYSTEM | |
apc.slam_defense | 0 | PHP_INI_SYSTEM | |
apc.file_update_protection | 2 | PHP_INI_SYSTEM | |
apc.enable_cli | 0 | PHP_INI_SYSTEM | > APC 3.0.6 |
Breve descrizione dei parametri di configurazione.
apc.enabled can be set to 0 to disable APC. This is primarily useful when APC is statically compiled into PHP, since there is no other way to disable it (when compiled as a DSO, the extension line in php.ini can just be commented-out).
The number of shared memory segments to allocate for the compiler cache. If APC is running out of shared memory but you have already set apc.shm_size as high as your system allows, you can try raising this value.
The size of each shared memory segment in MB. By default, some systems (including most BSD variants) have very low limits on the size of a shared memory segment.
The optimization level. Zero disables the optimizer, and higher values use more aggressive optimizations. Expect very modest speed improvements. This is experimental.
A "hint" about the number of distinct source files that will be included or requested on your web server. Set to zero or omit if you're not sure; this setting is mainly useful for sites that have many thousands of source files.
The number of seconds a cache entry is allowed to idle in a slot in case this cache entry slot is needed by another entry. Leaving this at zero means that your cache could potentially fill up with stale entries while newer entries won't be cached.
The number of seconds that a cache entry may remain on the garbage-collection list. This value provides a failsafe in the event that a server process dies while executing a cached source file; if that source file is modified, the memory allocated for the old version will not be reclaimed until this TTL reached. Set to zero to disable this feature.
On by default, but can be set to off and used in conjunction with positive apc.filters so that files are only cached if matched by a positive filter.
A comma-separated list of POSIX extended regular expressions. If any pattern matches the source filename, the file will not be cached. Note that the filename used for matching is the one passed to include/require, not the absolute path. If the first character of the expression is a + then the expression will be additive in the sense that any files matched by the expression will be cached, and if the first character is a - then anything matched will not be cached. The - case is the default, so it can be left off.
If compiled with MMAP support by using --enable-mmap this is the mktemp-style file_mask to pass to the mmap module for determing whether your mmap'ed memory region is going to be file-backed or shared memory backed. For straight file-backed mmap, set it to something like /tmp/apc.XXXXXX (exactly 6 Xs). To use POSIX-style shm_open/mmap put a .shm somewhere in your mask. e.g. /apc.shm.XXXXXX You can also set it to /dev/zero to use your kernel's /dev/zero interface to anonymous mmap'ed memory. Leaving it undefined will force an anonymous mmap.
On very busy servers whenever you start the server or modify files you can create a race of many processes all trying to cache the same file at the same time. This option sets the percentage of processes that will skip trying to cache an uncached file. Or think of it as the probability of a single process to skip caching. For example, setting apc.slam_defense to 75 would mean that there is a 75% chance that the process will not cache an uncached file. So, the higher the setting the greater the defense against cache slams. Setting this to 0 disables this feature.
When you modify a file on a live web server you really should do so in an atomic manner. That is, write to a temporary file and rename (mv) the file into its permanent position when it is ready. Many text editors, cp, tar and other such programs don't do this. This means that there is a chance that a file is accessed (and cached) while it is still being written to. This apc.file_update_protection setting puts a delay on caching brand new files. The default is 2 seconds which means that if the modification timestamp (mtime) on a file shows that it is less than 2 seconds old when it is accessed, it will not be cached. The unfortunate person who accessed this half-written file will still see weirdness, but at least it won't persist. If you are certain you always atomically update your files by using something like rsync which does this correctly, you can turn this protection off by setting it to 0. If you have a system that is flooded with io causing some update procedure to take longer than 2 seconds, you may want to increase this a bit.
Mostly for testing and debugging. Setting this enables APC for the CLI version of PHP. Normally you wouldn't want to create, populate and tear down the APC cache on every CLI request, but for various test scenarios it is handy to be able to enable APC for the CLI version of APC easily.
Array of cached data (and meta-data), or FALSE on failure
Nota: apc_cache_info() will raise a warning if it is unable to retrieve APC cache data. This typically occurs when APC is not enabled.
Esempio 1. A apc_cache_info() example
Il precedente esempio visualizzerà qualcosa simile a:
|
define() is notoriously slow. Since the main benefit of APC is to increase the performance of scripts/applications, this mechanism is provided to streamline the process of mass constant definition.
Nota: To remove a set of stored constants (without clearing the entire cache), an empty array may be passed as the constants parameter, effectively clearing the stored value(s).
The key serves as the name of the constant set being stored. This key is used to retrieve the stored constants in apc_load_constants().
An associative array of constant_name => value pairs. The constant_name must follow the normal constant naming rules. value must evaluate to a scalar value.
The default behaviour for constants is to be declared case-sensitive; i.e. CONSTANT and Constant represent different values. If this parameter evaluates to FALSE the constants will be declared as case-insensitive symbols.
The name of the constant set (that was stored with apc_define_constants()) to be retrieved.
The default behaviour for constants is to be declared case-sensitive; i.e. CONSTANT and Constant represent different values. If this parameter evaluates to FALSE the constants will be declared as case-insensitive symbols.
Nota: Unlike many other mechanisms in PHP, variables stored using apc_store() will persist between requests (until the value is removed from the cache).
Store the variable using this name. keys are cache-unique, so storing a second value with the same key will overwrite the original value.
The variable to store
Time To Live; store var in the cache for ttl seconds. After the ttl has passed, the stored variable will be expunged from the cache (on the next request). If no ttl is supplied (or if the ttl is 0), the value will persist until it is removed from the cache manually, or otherwise fails to exist in the cache (clear, restart, etc.).
APD is the Advanced PHP Debugger. It was written to provide profiling and debugging capabilities for PHP code, as well as to provide the ability to print out a full stack backtrace. APD supports interactive debugging, but by default it writes data to trace files. It also offers event based logging so that varying levels of information (including function calls, arguments passed, timings, etc.) can be turned on or off for individual scripts.
Attenzione |
APD is a Zend Extension, modifying the way the internals of PHP handle function calls, and thus may or may not be compatible with other Zend Extensions (for example Zend Optimizer). |
APD is currently available as a PECL extension from http://pecl.php.net/package/apd. Make sure you have installed the CGI version of PHP and it is available in your current path along with the phpize script.
Run the following command to download, build, and install the latest stable version of APD:
pear install apd |
This automatically installs the APD Zend module into your PHP extensions directory. It is not mandatory to keep it there; you can store the module in any directory PHP can read as long as you set the zend_extension parameter accordingly.
Windows users can download the extension dll php_apd.dll from http://snaps.php.net/win32/PECL_STABLE/.
In your INI file, add the following lines:
zend_extension = /absolute/path/to/apd.so apd.dumpdir = /absolute/path/to/trace/directory apd.statement_tracing = 0 |
Depending on your PHP build, the zend_extension directive can be one of the following:
zend_extension (non ZTS, non debug build) zend_extension_ts ( ZTS, non debug build) zend_extension_debug (non ZTS, debug build) zend_extension_debug_ts ( ZTS, debug build) |
To build APD under Windows you need a working PHP compilation environment as described on http://php.net/ -- basically, it requires you to have Microsoft Visual C++, win32build.zip, bison/flex, and some know how to get it to work. Also ensure that adp.dsp has DOS line endings; if it has unix line endings, Microsoft Visual C++ will complain about it.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. APD Configuration Options
Name | Default | Changeable | Changelog |
---|---|---|---|
apd.dumpdir | NULL | PHP_INI_ALL | |
apd.statement_tracing | "0" | PHP_INI_ALL |
Breve descrizione dei parametri di configurazione.
Sets the directory in which APD writes profile dump files. You can specify an absolute path or a relative path.
You can specify a different directory as an argument to apd_set_pprof_trace().
Specfies whether or not to do per-line tracings. Turning this on (1) will impact the performance of your application.
As the first line of your PHP script, call the apd_set_pprof_trace() function to start the trace:
apd_set_pprof_trace(); |
You can insert the line anywhere in your script, but if you do not start tracing at the beginning of your script you discard profile data that might otherwise lead you to a performance bottleneck.
Now run your script. The dump output will be written to apd.dumpdir/pprof_pid.ext.
Suggerimento: If you're running the CGI version of PHP, you will need to add the '-e' flag to enable extended information for apd to work properly. For example: php -e -f script.php
To display formatted profile data, issue the pprofp command with the sort and display options of your choice. The formatted output will look something like:
bash-2.05b$ pprofp -R /tmp/pprof.22141.0 Trace for /home/dan/testapd.php Total Elapsed Time = 0.00 Total System Time = 0.00 Total User Time = 0.00 Real User System secs/ cumm %Time (excl/cumm) (excl/cumm) (excl/cumm) Calls call s/call Memory Usage Name -------------------------------------------------------------------------------------- 100.0 0.00 0.00 0.00 0.00 0.00 0.00 1 0.0000 0.0009 0 main 56.9 0.00 0.00 0.00 0.00 0.00 0.00 1 0.0005 0.0005 0 apd_set_pprof_trace 28.0 0.00 0.00 0.00 0.00 0.00 0.00 10 0.0000 0.0000 0 preg_replace 14.3 0.00 0.00 0.00 0.00 0.00 0.00 10 0.0000 0.0000 0 str_replace |
The -R option used in this example sorts the profile table by the amount of real time the script spent executing a given function. The "cumm call" column reveals how many times each function was called, and the "s/call" column reveals how many seconds each call to the function required, on average.
To generate a calltree file that you can import into the KCacheGrind profile analysis application, issue the pprof2calltree comand.
If you have comments, bugfixes, enhancements or want to help developing this beast, you can send an mail to apd@mail.communityconnect.com. Any help is very welcome.
This can be used to stop the running of your script, and await responses on the connected socket. To step the program, just send enter (a blank line), or enter a php command to be executed. A typical session using tcplisten would look like this.
bash#tcplisten localhost 7777 APD - Advanced PHP Debugger Trace File --------------------------------------------------------------------------- Process Pid (6118) Trace Begun at Sun Mar 10 23:13:12 2002 --------------------------------------------------------------------------- ( 0.000000): apd_set_session_trace called at /home/alan/Projects/project2/test. php:5 ( 0.074824): apd_set_session_trace_socket() at /home/alan/Projects/project2/tes t.php:5 returned. Elapsed (0.074824) ( 0.074918): apd_breakpoint() /home/alan/Projects/project2/test.php:7 ++ argv[0] $(??) = 9 apd_breakpoint() at /home/alan/Projects/project2/test.php:7 returned. Elapsed ( -2089521468.1073275368) >\n statement: /home/alan/Projects/project2/test.php:8 >\n statement: /home/alan/Projects/project2/test.php:8 >\n statement: /home/alan/Projects/project2/test.php:10 >apd_echo($i); EXEC: apd_echo($i); 0 >apd_echo(serialize(apd_get_active_symbols())); EXEC: apd_echo(serialize(apd_get_active_symbols())); a:47:{i:0;s:4:"PWD";i:1;s:10:"COLORFGBG";i:2;s:11:"XAUTHORITY";i:3;s:14:" COLORTERM_BCE";i:4;s:9:"WINDOWID";i:5;s:14:"ETERM_VERSION";i:6;s:16:"SE SSION_MANAGER";i:7;s:4:"PS1";i:8;s:11:"GDMSESSION";i:9;s:5:"USER";i:10;s:5:" MAIL";i:11;s:7:"OLDPWD";i:12;s:5:"LANG";i:13;s:10:"COLORTERM";i:14;s:8:"DISP LAY";i:15;s:8:"LOGNAME";i:16;s:6:" >apd_echo(system('ls /home/mydir')); ........ >apd_continue(0); |
(no version information, might be only in CVS)
apd_callstack -- Returns the current call stack as an arrayBehaves like perl's Carp::cluck. Throw a warning and a callstack. The default line delimiter is "<BR />\n".
Usually sent via the socket to restart the interpreter.
(no version information, might be only in CVS)
apd_croak -- Throw an error, a callstack and then exitBehaves like perl's Carp::croak. Throw an error, a callstack and then exit. The default line delimiter is "<BR />\n".
(no version information, might be only in CVS)
apd_dump_function_table -- Outputs the current function table(no version information, might be only in CVS)
apd_dump_persistent_resources -- Return all persistent resources as an arrayReturn all persistent resources as an array.
(no version information, might be only in CVS)
apd_dump_regular_resources -- Return all current regular resources as an arrayReturn all current regular resources as an array.
Usually sent via the socket to request information about the running script.
(no version information, might be only in CVS)
apd_get_active_symbols -- Get an array of the current variables names in the local scopeReturns the names of all the variables defined in the active scope, (not their values)
Starts debugging to {dump_directory}/pprof_{process_id}, if dump_directory is not set, then the apd.dumpdir setting from the php.ini file is used.
Starts debugging to {dump_directory}/apd_dump_{process_id}, if dump_directory is not set, then the apd.dumpdir setting from the php.ini file is used.
debug_level is an integer which is formed by adding together the following values:
FUNCTION_TRACE 1 ARGS_TRACE 2 ASSIGNMENT_TRACE 4 STATEMENT_TRACE 8 MEMORY_TRACE 16 TIMING_TRACE 32 SUMMARY_TRACE 64 |
I would seriously not recommend using MEMORY_TRACE. It is very slow and does not appear to be accurate (great, huh?) also ASSIGNMENT_TRACE is not implemented. So, to turn on all functional traces (TIMING, FUNCTIONS, ARGS SUMMARY (like strace -c)) use the value 99
(no version information, might be only in CVS)
apd_set_session -- Changes or sets the current debugging levelThis can be used to increase or decrease debugging in a different area of your application,.debug_level is an integer which is formed by adding together the following values:
FUNCTION_TRACE 1 ARGS_TRACE 2 ASSIGNMENT_TRACE 4 STATEMENT_TRACE 8 MEMORY_TRACE 16 TIMING_TRACE 32 SUMMARY_TRACE 64 |
(no version information, might be only in CVS)
apd_set_socket_session_trace -- Starts the remote session debuggingConnects to the tcp server (eg. tcplisten) specified IP or Unix Domain socket (like a file), and sends debugging data to the socket. You can use any port, but higher numbers are better as most of the lower numbers may be used by other system services.
the socket_type can be APD_AF_UNIX (for file based sockets) or APD_AF_INET (for standard tcp/ip)
debug_level is an integer which is formed by adding together the following values:
FUNCTION_TRACE 1 ARGS_TRACE 2 ASSIGNMENT_TRACE 4 STATEMENT_TRACE 8 MEMORY_TRACE 16 TIMING_TRACE 32 SUMMARY_TRACE 64 |
I would seriously not recommend setting the value to 'zero' to start with, and use the breakpoint methods to start debugging at a specific place in the file.
Syntax similar to create_function(). Overrides built-in functions (replaces them in the symbol table).
Queste funzioni permettono di manipolare e interagire con gli array in vari modi. Gli array sono indispensabili per immagazzinare, mantenere e operare su gruppi di variabili.
Sono supportati sia array semplici che multi-dimensionali, che possono essere sia creati dall'utente che da funzioni. Ci sono specifiche funzioni di database per riempire gli array a partire da interrogazioni sui dati, e parecchie funzioni restituiscono array.
Vedere la sezione Array del manuale per una spiegazione dettagliata di come gli array siano implementati ed usati in PHP. Vedere anche per altri modi di manipolazione degli array.
Non è necessaria nessuna installazione per usare queste funzioni, esse fanno parte del core di PHP.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Le costanti qui elencate sono sempre disponibili in quanto parte del core di PHP.
CASE_LOWER è usata con array_change_key_case() per convertire le chiavi degli array in minuscolo. Questo è il valore di default per array_change_key_case().
CASE_UPPER è usata con array_change_key_case() per convertire le chiavi degli array in maiuscolo.
flag per l'ordinamento:
SORT_ASC è usata con array_multisort() per ordinare in senso crescente.
SORT_DESC è usata con array_multisort() per ordinare in senso decrescente.
flag per il tipo di ordinamento: usati da varie funzioni di ordinamento
SORT_REGULAR è usata per comparare gli oggetti in modo normale.
SORT_NUMERIC è usata per comparare gli oggetti in modo numerico.
SORT_STRING è usata per comparare gli oggetti come se fossero stringhe.
SORT_LOCALE_STRING è utilizzata per confrontare gli oggetti come stringhe, basandosi sul locale corrente. Aggiunto nel PHP 4.3.12 e 5.0.2.
(PHP 4 >= 4.2.0, PHP 5)
array_change_key_case -- Restituisce un array con tutte le chiavi cambiate in maiuscolo o in minuscoloarray_change_key_case() cambia le chiavi nell'array input in modo che siano tutte minuscole o maiuscole. Il tipo di cambiamento dipende dal parametro opzionale case. Si possono usare due costanti, CASE_UPPER per le maiuscole e CASE_LOWER per le minuscole. Il default è CASE_LOWER. La funzione non modifica le chiavi numeriche.
Se un array ha degli indici che risulteranno identici dopo l'esecuzione di questa funzione (es. "keY" e "kEY") il valore dell'ultimo indice sovrascrivera' gli altri.
array_chunk() spezza l'array in più array di dimensione dimensione. L'ultimo array potrebbe ovviamente avere una dimensione inferiore. Gli array sono restituiti in un array multidimensionale indicizzato con chiavi che partono da zero.
Impostando il parametro opzionale preserve_keys a TRUE, si forza PHP a mantenere le chiavi originarie dell'array di input. Se si imposta a FALSE come chiavi verranno usati in ogni array dei numeri crescenti a partire da zero. Il default è FALSE.
Esempio 1. esempio di array_chunk()
Il precedente esempio visualizzerà:
|
(PHP 5)
array_combine -- Crea un'array utilizzando un'array per le chiavi e un'altro per i suoi valoriRestituisce un'array utilizzando i valori dell'array keys come chiavi e i valori dall' array values come valori corrispondenti.
Restituisce FALSE se il numero degli elementi in ogni array non è uguale o se gli array sono vuoti.
Vedere anche array_merge(), array_walk() e array_values().
array_count_values() restituisce un array che ha i valori dell'array input per chiavi e la loro frequenza in input come valori.
Vedere anche count(), array_unique(), array_values() e count_chars().
(PHP 4 >= 4.3.0, PHP 5)
array_diff_assoc -- Calcola la differenza tra due o più array con un ulteriore controllo sull'indicearray_diff_assoc() restituisce un array contenente tutti i valori di array1 che non sono presenti in alcuno degli altri array. Si noti che le chiavi sono utilizzate nel confronto, diversamente da array_diff().
Esempio 1. esempio di array_diff_assoc()
Il risultato è:
|
Nell'esempio si vede che la coppia "a" => "verde" è presente in entrambi gli array e quindi non è nel risultato della funzione. Invece, la coppia 0 => "rosso" è nel risultato perché nel secondo argomento "red" cha come chiave 1.
Due valori delle coppie chiave => valore sono considerati uguali solo se (string) $elem1 === (string) $elem2 . In altre parole c'è un controllo stringente che si accerta che le rappresentazioni sotto forma di stringa siano uguali.
Nota: Si noti che questa funzione controlla solo una dimensione di un array n-dimensionale. Ovviamente è possibile controllare le altre dimensioni usando array_diff_assoc($array1[0], $array2[0]);.
Vedere anche array_diff(), array_intersect(), and array_intersect_assoc().
array_diff_key() returns an array containing all the values of array1 that have keys that are not present in any of the other arguments. Note that the associativity is preserved. This function is like array_diff() except the comparison is done on the keys instead of the values.
Esempio 1. array_diff_key() example
Il precedente esempio visualizzerà:
|
The two keys from the key => value pairs are considered equal only if (string) $key1 === (string) $key2 . In other words a strict type check is executed so the string representation 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 array_diff_key($array1[0], $array2[0]);.
See also array_diff(), array_udiff() array_diff_assoc(), array_diff_uassoc(), array_udiff_assoc(), array_udiff_uassoc(), array_diff_ukey(), array_intersect(), array_intersect_assoc(), array_intersect_uassoc(), array_intersect_key() and array_intersect_ukey().
(PHP 5)
array_diff_uassoc -- Computes the difference of arrays with additional index check which is performed by a user supplied callback functionarray_diff_uassoc() 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().
This comparison is done by a user supplied callback function. It must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. This is unlike array_diff_assoc() where an internal function for comparing the indices is used.
Esempio 1. array_diff_uassoc() example
Il precedente esempio visualizzerà:
|
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.
The equality of 2 indices is checked by the user supplied callback function.
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_uassoc($array1[0], $array2[0], "key_compare_func");.
See also array_diff(), array_diff_assoc(), array_udiff(), array_udiff_assoc(), array_udiff_uassoc(), array_intersect(), array_intersect_assoc(), array_uintersect(), array_uintersect_assoc() and array_uintersect_uassoc().
(PHP 5 >= 5.1.0RC1)
array_diff_ukey -- Computes the difference of arrays using a callback function on the keys for comparisonarray_diff_ukey() returns an array containing all the values of array1 that have keys that are not present in any of the other arguments. Note that the associativity is preserved. This function is like array_diff() except the comparison is done on the keys instead of the values.
This comparison is done by a user supplied callback function. It must return an integer less than, equal to, or greater than zero if the first key is considered to be respectively less than, equal to, or greater than the second.
Esempio 1. array_diff_ukey() example
Il precedente esempio visualizzerà:
|
Nota: Please note that this function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using array_diff_ukey($array1[0], $array2[0], 'callback_func');.
See also array_diff(), array_udiff() array_diff_assoc(), array_diff_uassoc(), array_udiff_assoc(), array_udiff_uassoc(), array_diff_key(), array_intersect(), array_intersect_assoc(), array_intersect_uassoc(), array_intersect_key() and array_intersect_ukey().
array_diff() restituisce un array contenente tutti i valori di array1 che non sono presenti in alcuno degli altri array. Si noti che le associazioni con le chiavi vengono mantenute.
Esempio 1. Esempio di array_diff()
Occorrenze multiple in $array1 sono tutte trattate nello stesso modo. Questo codice mostrerà:
|
Nota: Due elementi sono considerati uguali se e solo se (string) $elem1 === (string) $elem2. Ovvero: quando la rappresentazione sotto forma di stringa è la stessa.
Nota: Si noti che questa funzione controlla solo una dimensione di un array n-dimensionale. Ovviamente è possibile controllare le altre dimensioni usando array_diff($array1[0], $array2[0]);.
Avvertimento |
Questa funzione era errata nel PHP 4.0.4! |
Vedere anche array_diff_assoc(), array_intersect() e array_intersect_assoc().
array_fill() riempie un array con num elementi inizializzati con il valore del parametro valore, e con le chiavi che partono dal valore del parametro start_index. Si noti che num deve essere un valore maggiore di zero, altrimenti PHP mostrerà un avvertimento.
Vedere anche str_repeat() e range().
array_filter() esegue un'iterazione su ogni valore nell' array input passandolo alla funzione. Se funzione restituisce TRUE, il valore corrente di input viene restituito nell'array risultato. Le chiavi sono mantenute.
Esempio 1. Esempio di array_filter()
Il precedente esempio visualizzerà:
|
Gli utenti non possono modificare l'array attraverso la funzione di callback, ad esempio aggiungere/togliere un elemento, o cancellare l'array su cui array_filter() è applicata. Se l'array viene cambiato, il comportamento di questa funzione non è definito.
Se la funzione callback non viene indicata, array_filter() rimuoverà tutti gli elementi di input che siano uguali a FALSE. Vedere conversione a boolean per ulteriori informazioni.
Vedere anche array_map() e array_reduce().
array_flip() restituisce un array scambiato, ovvero le chiavi di trans diventano valori e i valori di trans diventano chiavi.
Si noti che i valori di trans devono poter diventare chiavi valide, ovvero devo essere di tipo integer o string. Un errore verrà segnalato se un valore ha il tipo errato, e la coppia chiave/valore in questione non verrà scambiata.
Se un valore ha più di una occorrenza, L'ultima chiave verrà usata come valore, e tutte le altre verranno perse.
array_flip() restituisce FALSE se fallisce.
Vedere anche array_values(), array_keys() e array_reverse().
(PHP 4 >= 4.3.0, PHP 5)
array_intersect_assoc -- Calcola l'intersezione degli array con un ulteriore controllo sugli indiciarray_intersect_assoc() restituisce un array contenente tutti i valori di array1 che siano presenti in tutti gli array passati come argomento. Si noti che le chiavi sono utilizzate nel confronto, diversamente da array_intersect().
Nell'esempio si vede che solo la coppia "a" => "verde" è presente in entrambi gli array e quindi viene restituita. Il valore "rosso" non viene restituito perché in $array1 la sua chiave è 0 mentre la chiave di "rosso" in $array2 è 1.
I due valori delle coppie chiave => valore sono considerati uguali solo se (string) $elem1 === (string) $elem2 . In altre parole viene eseguito un controllo stringente che si accerta che le rappresentazioni sotto forma di stringa siano uguali.
Vedere anche array_intersect(), array_uintersect_assoc(), array_intersect_uassoc(), array_uintersect_uassoc(), array_diff() e array_diff_assoc().
(PHP 5 >= 5.1.0RC1)
array_intersect_key -- Computes the intersection of arrays using keys for comparisonarray_intersect_key() returns an array containing all the values of array1 which have matching keys that are present in all the arguments.
Esempio 1. array_intersect_key() example
Il precedente esempio visualizzerà:
|
In our example you see that only the keys 'blue' and 'green' are present in both arrays and thus returned. Also notice that the values for the keys 'blue' and 'green' differ between the two arrays. A match still occurs because only the keys are checked. The values returned are those of array1.
The two keys from the key => value pairs are considered equal only if (string) $key1 === (string) $key2 . In other words a strict type check is executed so the string representation must be the same.
See also array_diff(), array_udiff() array_diff_assoc(), array_diff_uassoc(), array_udiff_assoc(), array_udiff_uassoc(), array_diff_key(), array_diff_ukey(), array_intersect(), array_intersect_assoc(), array_intersect_uassoc() and array_intersect_ukey().
(PHP 5)
array_intersect_uassoc -- Computes the intersection of arrays with additional index check, compares indexes by a callback functionarray_intersect_uassoc() 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().
The index comparison is done by a user supplied callback function. It must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
Esempio 1. array_intersect_uassoc() example
Il precedente esempio visualizzerà:
|
See also array_intersect(), array_intersect_assoc(), array_uintersect_assoc(), array_uintersect_uassoc(), array_intersect_key() and array_intersect_ukey().
(PHP 5 >= 5.1.0RC1)
array_intersect_ukey -- Computes the intersection of arrays using a callback function on the keys for comparisonarray_intersect_ukey() returns an array containing all the values of array1 which have matching keys that are present in all the arguments.
This comparison is done by a user supplied callback function. It must return an integer less than, equal to, or greater than zero if the first key is considered to be respectively less than, equal to, or greater than the second.
Esempio 1. array_intersect_ukey() example
Il precedente esempio visualizzerà:
|
In our example you see that only the keys 'blue' and 'green' are present in both arrays and thus returned. Also notice that the values for the keys 'blue' and 'green' differ between the two arrays. A match still occurs because only the keys are checked. The values returned are those of array1.
See also array_diff(), array_udiff() array_diff_assoc(), array_diff_uassoc(), array_udiff_assoc(), array_udiff_uassoc(), array_diff_key(), array_diff_ukey(), array_intersect(), array_intersect_assoc(), array_intersect_uassoc() and array_intersect_key().
array_intersect() restituisce un array contenente tutti i valori di array1 che siano presenti in tutti gli array passati come argomento. Si noti che le associazioni con le chiavi sono mantenute.
Nota: Due elementi sono considerati uguali solo e solo se (string) $elem1 === (string) $elem2. Ovvero: quando la rappresentazione sotto forma di stringa è la stessa.
Vedere anche array_intersect_assoc(), array_diff() e array_diff_assoc().
(PHP 4 >= 4.1.0, PHP 5)
array_key_exists -- Controlla se l'indice (o chiave) specificato esiste nell'arrayarray_key_exists() restituisce TRUE se il parametro chiave esiste nell'array. chiave può essere qualsiasi valore accettabile per un indice di array.
Nota: Il nome di questa funzione è key_exists() nel PHP 4.0.6.
Vedere anche isset(), array_keys() e in_array().
array_keys() rstituisce le chiavi, numeriche e stringa, dell'array input.
Se il parametro opzionale valore_ricerca è specificato, solo le chiavi che corrispondono a quel valore vengono restituite. Altrimenti, vengono restituite tutte le chiavi dell'array input.
Esempio 1. Esempio di array_keys()
Il risultato di questo programma sarà:
|
Vedere anche array_values() e array_key_exists().
(PHP 4 >= 4.0.6, PHP 5)
array_map -- Applica la funzione callback a tutti gli elementi dell'array datoarray_map() restituisce un array contenente tutti gli elementi di arr1 dopo che è stata loro applicata la funzione callback. Il numero di parametri che la funzione callback accetta deve corrispondere al numero di array passati alla funzione array_map()
Esempio 2. array_map() - usare più array
Il precedente esempio visualizzerà:
|
Generalmente, quando si usano due o più array, questi devono avere eguale lunghezza in quanto la funzione callback viene applicata in parallelo agli elementi corrispondenti. Se gli array sono di lunghezza diversa, il più corto verrà esteso con elementi vuoti.
Un uso interessante di questa funzione è quello di costruire un array di array, cosa che può essere facilmente ottenuta usando NULL come nome della funzione callback
Esempio 3. Creare un array di array
Il precedente esempio visualizzerà:
|
Vedere anche array_filter(), array_reduce(), array_walk() e information about the callback type.
Array_merge_recursive() fonde gli elementi di due o più array in modo tale che i valori di un array siano accodati all'array precedente. Restituisce l'array risultante.
Se gli array in input hanno le stesse chiavi stringa, i valori di queste chiavi vengono fusi in un array, e questo è fatto in modo ricorsivo, cio` se uno dei valori è un array, la funzione lo fonder%agrave; con una voce corrispondente in un altro array Comunque, se gli array hanno la stessa chiave numerica, l'ultimo valore non sovrascriver` il valore originale, bensì verrà accodato.
Esempio 1. Esempio di array_merge_recursive()
La variabile $risultato sarà:
|
Vedere anche array_merge().
array_merge() fonde gli elementi di uno o più array in modo che i valori di un array siano accodati a quelli dell'array precedente. Restituisce l'array risultante.
Se gli array in input hanno le stesse chiavi stringa, l'ultimo valore di quella chiave sovrascriverà i precedenti. Comunque, se gli array hanno le stesse chiavi numeriche, l'ultimo valore non sovrascriverà quello originale, bensì sarà accodato.
Se viene fornito un solo array, e questo è indicizzato numericamente, le chiavi vengono reindicizzate in una sequenza continua. Nel caso di array associativi, delle chiavi duplicate rimane solo l'ultima. Vedere l'esempio tre per ulteriori dettagli.
Esempio 1. Esempio di array_merge()
La variabile $risultato sarà:
|
Esempio 2. Esempio di array_merge()
Non dimenticarsi che le chiavi numeriche saranno rinumerate!
Se si vogliono preservare gli array e li si vuole solo concatenare, usare l'operatore +:
La chiave numerica sarà preservata e così pure l'associazione.
|
Esempio 3. esempio di array_merge()
Il risultato sarà:
|
Nota: Le chiavi condivise verranno sovrascritte dalla prima chiave processata.
Vedere anche array_merge_recursive() e array_combine() e operatori sugli array.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Array_multisort() Può essere usata per ordinare parecchi array allo stesso tempo, oppure un array multidimensionale, rispetto a una o più dimensioni.
Mantiene le chiavi associative (tipo string), mentre le chiavi numeriche vengono reindicizzate.
Gli array in input sono trattati come campi di una tabella che vengano ordinati per righe - questo assomiglia alla funzionalità della clausola SQL ORDER BY Il primo array è quello primario, rispetto a cui ordinare. Le righe (valori) in questo array that siano uguali vengono ordinate secondo l'array successivo, e così via.
La struttura degli argomenti di questa funzione è un po' inusuale, ma flessibile. Il primo argomento deve essere un array. In seguito, ogni argomento può essere sia un array che un flag di ordinamento, selezionabile dalla seguente lista.
Flag di ordinamento:
SORT_ASC - ordinamento crescente
SORT_DESC - ordinamento decrescente
Flag di tipo:
SORT_REGULAR - confronta gli elementi in modo normale
SORT_NUMERIC - confronta gli elementi numericamente
SORT_STRING - confronta gli elementi come stringhe
Dopo ogni array, non si possono specificare due flag dello stesso tipo. I flag specificati dopo un array si applicano solo a quell'array - sono reimpostati ai default SORT_ASC e SORT_REGULAR prima di ogni nuovo array passato come argomento.
Esempio 1. Ordinamre più array
In questo esempio, dopo l'ordinamento, il primo array conterrà "10", "a", 100, 100. Il secondo array conterrà 1, 1, "2", 3. Gli elementi del secondo array corrispondenti a quelli, identici, del primo array (100 e 100), vengono pure ordinati.
|
Esempio 2. Ordinamento di array multidimensionali
In questo esempio, dopo l'ordinamento, il primo array conterrà "10", 100, 100, 11, "a" (ordinato come stringhe ordine crescente), e il secondo conterrà 1, 3, "2", 2, 1 (ordinati come numeri, in ordine decrescente).
|
Esempio 3. Ordinamento dei risultati di un database In questo esempio, ogni elemento nell'array data rappresenta un record della tabella. Questo genere di dato è tipico dei record di database. Esempio di dati:
I dati sono in un array, chiamato data. Di solito questo si ottiene ciclando, ad esempio, con mysql_fetch_assoc().
In questo esempio ordineremo volume in senso discendente, edition in senso ascendente. Abbiamo un array di record, ma array_multisort() richiede un array di colonne, quindi usiamo il codice qui sotto per ottenerlo, quindi eseguiremo l'ordinamento.
Il set di dati è ora ordinato, e apparirà così:
|
Esempio 4. Ordinamento senza distinzione tra maiuscole e minuscole Sia SORT_STRING che SORT_REGULAR tengono conto delle maiuscole, le stringhe che iniziano con una maiuscola vengono prima di quelle che iniziano con una minuscola. Per ottenere un ordinamento che ignori le maiuscole, forzarlo in modo che sia determnato da una copia dell'array originale formata da sole minuscole.
Il precedente esempio visualizzerà:
|
array_pad() restituisce una copia di input allungato alla dimensione sepcificata da pad_size con il valore pad_value. Se pad_size è positivo l'array è riempito sulla destra, se è negativo sulla sinistra. Se il valore assoluto di pad_size è minore o uguale alla lunghezza di input non viene effettuata alcuna modifica.
Esempio 1. esempio di array_pad()
|
Vedere anche array_fill() e range().
array_pop() estrae e restituisce l'ultimo valore di array, accorciando array di un elemento. Se array è vuoto (o non è un array), viene restituito NULL.
Avvertimento |
Questa funzione può restituire il Booleano FALSE, ma può anche restituire un valore non-Booleano valutato come FALSE, come ad esempio 0 o "". Per favore fare riferimento alla sezione Booleans per maggiori informazioni. Usare l'operatore === per controllare il valore restituito da questa funzione. |
Vedere anche array_push(), array_shift() e array_unshift().
array_product() returns the product of values in an array as an integer or float.
array_push() tratta array come una pila, e accoda le variabili date alla fine di array. La lunghezza di array aumenta del numero di variabili accodate. Ha lo stesso effetto di:
<?php $array[] = $var; ?> |
Restituisce il nuovo numero di elementi nell'array.
Nota: Se si utilizza array_push() per aggiungere un elemento all'array, è preferibile piuttosto utilizzare $array[] = poiché in questo modo non c'è il tempo d'attesa per la chiamata di funzione.
Vedere anche array_pop(), array_shift() e array_unshift().
array_rand() è piuttosto utile quando si vuole estrarre a caso uno o più elementi da un array. Prende un array (input) e un argomento ozpionale (num_req) che specifica quanti elementi estrarre - se non è specificato, è 1 per default.
Se si sta estraendo solo un elemento, array_rand() restituisce la chiave di un elemento. Altrimenti, restituisce un array di chiavi. Questo viene fatto in modo da permettere di estrarre dall'array sia le chiavi che i valori.
Nota: Come in PHP 4.2.0, non vi è necessità di inizializzare il generatore di numeri casuali con srand() oppure con mt_srand() poichè viene eseguito in modo automatico.
Vedere anche shuffle().
(PHP 4 >= 4.0.5, PHP 5)
array_reduce -- Riduce iterativamente l'array a un singolo valore utilizzando una funzione callbackarray_reduce() applica iterativamente la funzione callback agli elementi dell'array input, riducendo l'array a un singolo valore. Seil parametro opzionale intial è specificato, viene usato come valore iniziale all'inizio del processo, o come risultato finale nel caso l'array sia vuoto.
In questo modo $b conterrà 15, $c conterrà 1200 (= 1*2*3*4*5*10) e $d conterrà 1.
Vedere anche array_filter() e array_map(), array_unique() e array_count_values().
array_reverse() prende array e restituisce un nuovo array con l'ordine degli elementi invertito, mantenendo le chiavi sie mantieni_chiavi è TRUE.
Esempio 1. esempio di array_reverse()
Questo fa sì che sia $risultato che $risultato_chiavi abbiano gli stessi elementi, ma si noti la differenza tra le chiavi. La stampa di $risultato e $risultato_chiavi sarà:
|
Nota: Il secondo parametro è stato aggiunto in PHP 4.0.3.
Vedere anche array_flip().
(PHP 4 >= 4.0.5, PHP 5)
array_search -- Ricerca un dato valore in un array e ne restituisce la chiave corrispondente, se la ricerca ha successo.Cerca in pagliaio per trovare ago e restituisce la chiave se viene trovato nell'array, FALSE altrimenti.
Nota: Se ago è una stringa, il confronto è fatto tenendo conto delle maiuscole/minuscole.
Nota: Nelle versioni di PHP antecedenti la 4.2.0, array_search() restituisce NULL invece di FALSE in caso di fallimento.
Se il terzo parametro opzionale strict è impostato a TRUE la funzione array_search() controllerà anche il tipo di ago nell'array pagliaio.
Se ago viene ritrovato in pagliaio più di una nolta, viene restituita la prima chiave trovata. Per restituire le chiavi di tutti i valori, utilizzare array_keys() con il parametro opzionale valore_ricerca.
Avvertimento |
Questa funzione può restituire il Booleano FALSE, ma può anche restituire un valore non-Booleano valutato come FALSE, come ad esempio 0 o "". Per favore fare riferimento alla sezione Booleans per maggiori informazioni. Usare l'operatore === per controllare il valore restituito da questa funzione. |
Vedere anche array_keys(), array_values(), array_key_exists() e in_array().
array_shift() estrae il primo elemento di array e lo restituisce, accorciando array di un elemento e spostando tutti gli altri all'indietro. Tutte le chiavi numeriche verranno modificate al fine di iniziare il conteggio da zero, mentre gli indici alfabetici non verranno modificati. Se array è vuoto (o non è un array), viene restituito NULL.
Vedere anche array_unshift(), array_push() e array_pop().
array_slice() restituisce la sequenza di elementi dell'array array come specificato dai parametri offset e length .
Se offset è positivo, la sequenza comincerà da quell'offset in array. Se offset è negativo, la sequenza comincerà alla distanza offset dalla fine di array.
Se length è specificata ed è positiva, la sequenza conterrà quel numero di elementi. Se length è specificata ed è negativa la sequenza si fermerà a quel numero di elementi dalla fine dell'array. Se viene omessa, la sequenza conterrà tutto da offset fino alla fine di array.
Si noti che array_slice() ignorerà le chiavi dell'array, e calcolerè gli spiazzamenti e le lunghezze basandosi sulle posizioni correnti degli elementi nell'array.
Esempio 1. esempi di array_slice()
|
Vedere anche array_splice() e unset().
array_splice() rimuove gli elementi specificati da offset e length dall'array input, e li sostituisce con gli elementi dell'array replacement, se fornito. Restituisce un array contenente gli elementi estratti.
Se offset è positivo l'inizio della porzione rimossa è a quella distanza dall'inizio dell'array input. Se offset è negativo inizia a quella distanza dalla fine dell'array input.
Se length è omessa, rimuove tutti gli elementi da offset alla fine dell'array. Se length è specificata a positiva, quel numero di elementi vengono rimossi. Se length è specificata e negativa la porzione da rimuovere terminerà a length elementi dalla fine dell'array. Suggerimento: per rimuovere tutti gli elementi tra offset e la fine dell'array quando è specificato pure replacement, usare count($input) nel parametro length.
Se l'array replacement è specificato, gli elementi rimossi sono sostituiti dagli elementi di questo array. Se offset e length sono tali per cui niente viene rimosso, gli elementi dell'array replacement sono inseriti nella posizione specificata da offset. Si noti che le chiavi nell'array replacement non sono conservate. Se replacement è composto solo da un elemento non è necessario porlo nel costrutto array(), a meno che l'elemento stesso non sia un array.
Le seguenti espressione cambiano i valori di $input nello stesso modo:
Tabella 1. array_splice() equivalents
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 // negli array in cui la chiave è uguale alla posizione | array_splice($input, $x, 1, $y) |
Restituisce un array contenente gli elementi rimossi.
Esempio 1. esempi di array_splice()
|
Vedere anche array_slice()i, unset() e array_merge().
array_sum() restituisce la somma dei valori dell'array sotto forma di integer o float.
Nota: Le versioni di PHP antecedenti alla 4.2.1 modificavano l'array stesso e convertivano le stringhe in numeri (le quali erano convertite in zeri la maggior parte delle volte, a seconda dal valore).
(PHP 5)
array_udiff_assoc -- Computes the difference of arrays with additional index check, compares data by a callback functionarray_udiff_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() and array_udiff(). The comparison of arrays' data is performed by using an user-supplied callback. In this aspect the behaviour is opposite to the behaviour of array_diff_assoc() which uses internal function for comparison.
Esempio 1. array_udiff_assoc() example
Il precedente esempio visualizzerà:
|
In our example above you see the "1" => new cr(4) pair is present in both arrays and thus it is not in the ouput from the function.
For comparison is used the user supplied callback function. It must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
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_udiff_assoc($array1[0], $array2[0], "some_comparison_func");.
See also array_diff(), array_diff_assoc(), array_diff_uassoc(), array_udiff(), array_udiff_uassoc(), array_intersect(), array_intersect_assoc(), array_uintersect(), array_uintersect_assoc() and array_uintersect_uassoc().
(PHP 5)
array_udiff_uassoc -- Computes the difference of arrays with additional index check, compares data and indexes by a callback functionarray_udiff_uassoc() 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() and array_udiff(). The comparison of arrays' data is performed by using an user-supplied callback : data_compare_func. In this aspect the behaviour is opposite to the behaviour of array_diff_assoc() which uses internal function for comparison. The comparison of keys (indices) is done also by the callback function key_compare_func. This behaviour is unlike what array_udiff_assoc() does, since the latter compares the indices by using an internal function.
Esempio 1. array_udiff_uassoc() example
Il precedente esempio visualizzerà:
|
In our example above you see the "1" => new cr(4) pair is present in both arrays and thus it is not in the ouput from the function. Keep in mind that you have to supply 2 callback functions.
For comparison is used the user supplied callback function. It must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
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_udiff_uassoc($array1[0], $array2[0], "data_compare_func", "key_compare_func");.
See also array_diff(), array_diff_assoc(), array_diff_uassoc(), array_udiff(), array_udiff_assoc(), array_intersect(), array_intersect_assoc(), array_uintersect(), array_uintersect_assoc() and array_uintersect_uassoc().
(PHP 5)
array_udiff -- Computes the difference of arrays by using a callback function for data comparisonarray_udiff() returns an array containing all the values of array1 that are not present in any of the other arguments. Note that keys are preserved. For the comparison of the data data_compare_func is used. It must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. This is unlike array_diff() which uses an internal function for comparing the data.
Esempio 1. array_udiff() example
Il precedente esempio visualizzerà:
|
Nota: Please note that this function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using array_udiff($array1[0], $array2[0], "data_compare_func");.
See also array_diff(), array_diff_assoc(), array_diff_uassoc(), array_udiff_assoc(), array_udiff_uassoc(), array_intersect(), array_intersect_assoc(), array_uintersect(), array_uintersect_assoc() and array_uintersect_uassoc().
(PHP 5)
array_uintersect_assoc -- Computes the intersection of arrays with additional index check, compares data by a callback functionarray_uintersect_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_uintersect(). The data is compared by using a callback function.
Esempio 1. array_uintersect_assoc() example
Il precedente esempio visualizzerà:
|
For comparison is used the user supplied callback function. It must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
See also array_uintersect(), array_intersect_assoc(), array_intersect_uassoc() and array_uintersect_uassoc().
(PHP 5)
array_uintersect_uassoc -- Computes the intersection of arrays with additional index check, compares data and indexes by a callback functionsarray_uintersect_uassoc() 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_uintersect(). Both the data and the indexes are compared by using a callback functions.
Esempio 1. array_uintersect_uassoc() example
Il precedente esempio visualizzerà:
|
For comparison is used the user supplied callback function. It must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
See also array_uintersect(), array_intersect_assoc(), array_intersect_uassoc() and array_uintersect_assoc().
(PHP 5)
array_uintersect -- Computes the intersection of arrays, compares data by a callback functionarray_uintersect() returns an array containing all the values of array1 that are present in all the arguments. The data is compared by using a callback function.
Esempio 1. array_uintersect() example
Il precedente esempio visualizzerà:
|
For comparison is used the user supplied callback function. It must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
See also array_intersect(), array_uintersect_assoc(), array_intersect_uassoc() and array_uintersect_uassoc().
array_unique() prende array e restituisce un nuovo array senza i valori duplicati.
Si noti che le chiavi sono mantenute. array_unique() ordina i valori trattandoli come stringhe, quindi mantiene la prima chiave trovata per ogni valore, e ignorerà tutte le altre chiavi. Questo non significa che la chiave del primo valore dell'array non ancora ordinato verrà mantenuta.
Nota: Due elementi sono considerati uguali se e solo se (string) $elem1 === (string) $elem2. Ovvero: quando la rappresentazione sotto forma di stringa è la stessa.
Verrà usato il primo elemento.
array_unshift() aggiunge gli elementi specificati in testa ad array. Si noti che la lista di elementi è aggiunta in blocco, in modo tale che gli elementi rimangano nello stesso ordine. Tutte le chiavi numeriche vengono modificate per iniziare da zero mentre le chiavi alfabetiche non sono modificate.
Restituisce il nuovo numero di elementi in array.
Vedere anche array_shift(), array_push() e array_pop().
array_values() restituisce tutti i valori dell'array input e indicizza numericamente l'array.
Vedere anche array_keys().
Applies the user-defined function funcname to each element of the input array. This function will recur into deeper arrays. Typically, funcname takes on two parameters. The input parameter's value being the first, and the key/index second. If the optional userdata parameter is supplied, it will be passed as the third parameter to the callback funcname.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: If funcname needs to be working with the actual values of the array, specify the first parameter of funcname as a reference. Then, any changes made to those elements will be made in the original array itself.
Esempio 1. array_walk_recursive() example
Il precedente esempio visualizzerà:
You may notice that the key 'sweet' is never displayed. Any key that holds an array will not be passed to the function. |
See also array_walk(), and information about the callback type.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Esegue la funzione definita dall'utente identificata da funzione su ogni elemento di array. Normalmente funzione accetta due parametri. Il valore del parametro array viene passato per primo, la chiave/indice per secondo. Se il parametro datiutente è specificato, verrà passato come terzo parametro alla funzione callback.
Se funzione richiede più parametri di quanti gliene vengono passati, un errore di livello E_WARNING verrà generato ogni volta che array_walk() la chiama. Questi avvertimenti possono essere soppressi apponendo l'operatore d'errore @ alla chiamata di array_walk(), oppure usando error_reporting().
Nota: Se funzione deve lavorare con i reali valori dell'array, specificare che il primo parametro di funzione deve essere passato come riferimento. A qesto punto ogni modifica a questi elementi verrà effettuata sull'array stesso.
Nota: Il passaggio della chiave e di datiutente a func è stato aggiunto nella versione 4.0.
array_walk() non è influenzato dal puntatore interno dell'array array. array_walk() percorrerà l'intero array indipendentemente dalla posizione del puntatore. Per reinizializzare il puntatore, utilizzare reset(). In PHP 3, array_walk() reinizializza il puntatore.
Gli utenti non possono modificare l'array attraverso la funzione di callback, ad esempio aggiungere/togliere un elemento, o cancellare l'array su cui array_walk() è applicata. Se l'array viene cambiato, il comportamento di questa funzione non è definito ed è imprevedibile.
Esempio 1. esempio di array_walk()
Il risultato del programma sarà:
|
Vedere anche array_walk_recursive(), create_function(), list(), foreach, each(), call_user_func_array() e array_map()
Restituisce un array contenente i parametri. Ai parametri si può dare un indice con l'operatore =>. Leggere la sezione relativa ai tipi per ulteriori informazioni sugli array.
Nota: array() è un costrutto del linguaggio usato per rappresentare array letterali, e non una normale funzione.
La sintassi "indice => valori", separati da virgole, definisce indici e valori. indice può essere di tipo string o numerico. Quando l'indice è omesso, viene generato automaticamente un indice intero, a partire da 0. Se l'indice è un intero, il successivo indice generato sarà l'indice intero più grande + 1. Si noti che quando due indici identici vengono definiti, l'ultimo sovrascrive il primo.
L'esempio seguente dimostra come creare un array bidimensionale, come specificare le chiavi per gli array associativi, e come modificare la serie degli indici numerici negli array normali.
Si noti che l'indice '3' è definito due volte, e che mantiene il valore finale 13. L'indice 4 è definito dopo l'indice 8, e il successivo indice generato (valore 19) è 9, dal momento che l'indice più grande era 8.
Questo esempio crea un array che parte da 1 (1-based).
Vedere anche array_pad(), list(), foreach e range().
(PHP 3, PHP 4, PHP 5)
arsort -- Ordina un array in ordine decrescente e mantiene le associazioni degli indiciQuesta funzione ordina un array in modo tale che i suoi indici mantengano la loro correlazione con gli elementi ai quali sono associati. Viene usata principalmente nell'ordinamento degli array associativi, quando la disposizione originaria degli elementi è importante.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Esempio 1. esempio di arsort()
Questo esempio mostrerà:
|
I frutti sono ordinati in ordine alfabetico decrescente, e l'indice associato a ogni elemento è stato mantenuto.
È possibile modificare il comportamento dell'ordinamento usando il parametro opzionale sort_flags, per maggiori dettagli vedere sort().
Questa funzione ordina un array in modo tale che i suoi indici mantengano la loro correlazione con gli elementi ai quali sono associati. Viene usata principalmente nell'ordinamento degli array associativi, quando la disposizione originaria degli elementi è importante.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
I frutti sono ordinati in ordine alfabetico, e l'indice associato ad ogni elemento è stato mantenuto.
È possibile modificare il comportamento dell'ordinamento usando il parametro opzionale sort_flags, per maggiori dettagli vedere sort().
compact() accetta un numero variabile di parametri. Ogni parametro può essere una stringa contenente il nome della variabile, o un array di nomi di variabile. L'array può contenere altri array di nomi di variabile; compact() se ne occupa in modo ricorsivo.
Per ognuno di questi, compact() cerca la variabile con quel nome nella tabella dei simboli corrente, e la aggiunge all'array di output in modo tale che il nome della variabile diventi la chiave e i contenuti della variabile diventino il valore associato a quella chiave. In breve, compact() è l'opposto di extract(). Restituisce l'array di output con tutte le variabili aggiunte a quest'ultimo.
Qualsiasi stringa non valorizzata verrà semplicemente ignorata.
Gotcha: Dal momento che le variabili variabili non posso essere utilizzate con gli array Superglobal di PHP nelle funzioni, gli array Superglobal non possono essere passati alla funzione compact().
Vedere anche extract().
Restituisce il numero di elementi in var, la quale è di norma un array, dal momento che qualsiasi altro oggetto avrà un elemento.
Per gli oggetti, se SPL è installato, è possibile agganciarsi a count() implementando l'interfaccia Countable. L'interfaccia ha esattamente un metodo, count(), che ritorna il valore restituito dalla funzione count().
Se var non è un array o un oggetto con l'interfaccia Countable implementata, verrà restituito 1 C'è una eccezione, se var è NULL, verrà restituito 0.
Nota: Il parametro opzionale mode è disponibile da PHP 4.2.0.
Se il parametro opzionale mode è impostato a COUNT_RECURSIVE (o 1), count() conterà ricorsivamente l'array. Questo è utile in particolare per contare tutti gli elementi di un array multidimensionale. Il valore di default per mode è 0. count() non identifica le ricorsioni infinite.
Attenzione |
count() può restituire 0 per una variabile che non è impostata, ma può anche restituire 0 per una variabile che è stata inizializzata con un array vuoto. Usare isset() per verificare se una variabile è impostata. |
Vedere la sezione Array nel manuale per una spiegazione dettagliata di come gli array siano implementati ed usati in PHP.
Esempio 2. esempio di count() ricorsiva (PHP >= 4.2.0)
|
Vedere anche is_array(), isset() e strlen().
Ogni array ha un puntatore interno all'elemento "corrente", che è inizializzato al primo elemento inserito nell'array.
La funzione current() restituisce il valore dell'elemento che è attualmente puntato dal puntatore interno. In ogni caso non muove il puntatore. Se il puntatore interno punta oltre la fine della lista di elementi, current() restituisce FALSE.
Avvertimento |
Se l'array contiene elementi vuoti (0 o "", la stringa vuota) la funzione restituirà FALSE pure per questi elementi. Questo rende impossibile stabilire se si è veramente alla fine della lista in un array di questo tipo usando current(). Per attraversare in modo corretto un array che può contenere elementi vuoti, usare la funzione each(). |
Esempio 1. Esempio di current() e funzioni relative
|
(PHP 3, PHP 4, PHP 5)
each -- Restituisce la corrente coppia chiave/valore di un array e incrementa il puntatore dell'arrayRestituisce la corrente coppia chiave/valore corrente di array e incrementa il puntatore interno dell'array. Questa coppia è restituita in un array di quattro elementi, con le chiavi 0, 1, key, and value. Gli elementi 0 e key contengono il nome della chiave dell'elemento dell'array, mentre 1 e value contengono i dati.
Se il puntatore interno dell'array punta oltre la fine dei contenuti dell'array, each() restituisce FALSE.
<?php $foo = array("Robert" => "Bob", "Seppo" => "Sepi"); $bar = each($foo); print_r($bar); ?> |
$bar ora contiene la seguente coppia chiave/valore:
Array ( [1] => Bob [value] => Bob [0] => Robert [key] => Robert ) |
each() viene normalmente usata in congiunzione con list() nell'attraversamento di un array; ecco un esempio:
Dopo l'esecuzione di each(), il puntatore dell'array viene lasciato sull'elemento successivo, o sull'ultimo elemento se si è alla fine dell'array. Si deve utilizzare reset() se si vuole riattraversare l'array usando each().
Attenzione |
Poiché assegnare un array ad un'altra variabile reimposta il puntatore, il nostro esempio diventerebbe un loop infinito se assegnassimo $frutta ad un'altra variabile all'interno del ciclo. |
Vedere anche key(), list(), current(), reset(), next(), prev() e foreach.
end() fa avanzare il puntatore di array all'ultimo elemento, e restituisce il suo valore.
Questa funzione viene usata per importare delle variabili da un array nella tabella dei simbloi corrente. Riceve un array associativo var_array e interpreta le chiavi come nomi di variabile e i valori come valori di variabile. Per ogni coppia chiave/valore verrà creata una variabile nella tabella dei simboli corrente, coerentemente con i parametri extract_type e prefix.
Nota: Dalla versione 4.0.5 questa funzione restituisce il numero di variabili estratte.
Nota: EXTR_IF_EXISTS e EXTR_PREFIX_IF_EXISTS sono stati introdotti nella versione 4.2.0.
Nota: EXTR_REFS è stata introdotta nella versione 4.3.0.
extract() controlla ogni chiave per stabilire se costituisce un nome valido di variabile e se ci sono collisioni con variabili già esistenti nella tabella dei simboli. Il modo in cui vengono trattate le chiavi invalide/numeriche e le collisioni è determinato da extract_type. Può essere uno dei seguenti valori:
Se avviene una collisione, sovrascrive la variabile esistente.
Se avviene una collisione, non sovrascrive la variabile esistente.
Se avviene una collisione, mette come prefisso al nome della variabile il parametro prefix.
Mette come prefisso di tutte le variabili il parametro prefix. Dal PHP 4.0.5 questo avviene anche per i valori numerici.
Mette come prefisso, solo per i nomi di variabili invalidi/numerici, il parametro prefix. Questa opzione è stata aggiunta in PHP 4.0.5.
Sovrascrive la variabile solo se già esiste nella tabella dei simboli, altrimenti non fa nulla. Questo è utile per definire una lista di variabili valide e quindi estrarre solo quelle variabili definite in $_REQUEST, per esempio. Questa opzione è stata aggiunta in PHP 4.2.0.
Crea nomi di variabili con il prefisso solo se la versione senza prefisso della stessa variable esiste nella tabella dei simboli. Questa opzione è stata aggiunta in PHP 4.2.0.
Estrae le variabili come riferimenti. Questo in effetti significa che i valori delle variabili importate referenziano i valori del parametro var_array. Si può usare questo flag da solo o combinarlo con gli altri mediante un OR nel parametro extract_type. Questo flag è stato aggiunto nel PHP 4.3.0.
Se extract_type non è specificato, si assume che sia EXTR_OVERWRITE.
Si noti che prefix è richiesto solo se extract_type è EXTR_PREFIX_SAME, EXTR_PREFIX_ALL, EXTR_PREFIX_INVALID o EXTR_PREFIX_IF_EXISTS. Se il risultato non è un nome di variabile valido, non viene importato nella tabella dei simboli.
extract() restituisce il numero di variabili importate con successo nella tabella dei simboli.
Avvertimento |
Non utilizzare extract() su dati non convalidati, come gli input degli utenti ($_GET, ...). Se lo si deve fare, ad esempio per eseguire temporaneamente vecchio codice basato su register_globals, sincerarsi di utilizzare uno dei valori di extract_type come EXTR_SKIP e ricordarsi che occorre estrarre $_SERVER, $_SESSION, $_COOKIE, $_POST e $_GET in questo ordine. |
Un possibile uso di extract() è quello di importare nella tabella dei simboli variabili contenute in un array associativo restituito da wddx_deserialize().
Esempio 1. esempio diextract()
L'esempio mostrerà:
|
La variabile $dimensione non è stata sovrascritta, in quanto è specificato EXTR_PREFIX_SAME, che ha portato alla creazione di $wddx_dimensione. Se fosse stato specificato EXTR_SKIP, $wddx_dimensione non sarebbe stata creata. EXTR_OVERWRITE avrebbe portato $dimensione ad assumere il valore "medio", e EXTR_PREFIX_ALL avrebbe fatto creare nuove variabili chiamate $wddx_colore, $wddx_dimensione e $wddx_forma.
Si deve usare un array associativo, un array indicizzato numericamente non produce risultati a meno di non usare EXTR_PREFIX_ALL o EXTR_PREFIX_INVALID.
Vedere anche compact().
Cerca in pagliaio per trovare ago e restituisce TRUE se viene trovato nell'array, FALSE altrimenti.
Se il terzo parametro strict è TRUE la funzione in_array() controllerà anche il tipo di ago nell'array haystack.
Nota: Se ago è una stringa, il confronto è effettuato tenendo conto delle maiuscole/minuscole.
Nota: Nelle versioni di PHP precedenti la 4.2.0. ago non poteva essere un array.
Esempio 1. esempio di in_array()
La seconda condizione fallisce perché in_array() tiene conto di maiuscole e minuscole, quindi il programma mostrerà:
|
Esempio 3. in_array() con un array come ago
Questo ritornerà:
|
Vedere anche array_search(), array_key_exists() e isset().
key() restituisce la chiave corrispondente all'attuale posizione del puntatore interno all'array.
Esempio 1. esempio di key()
|
Ordina un array rispetto alle sue chiavi, in ordine inverso, mantenendo le associazioni. Questa funzione è utile con gli array associativi.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Si può modificare il comportamento dell'ordinamento usando il parametro opzionale sort_flags, per ulteriori dettagli vedere sort().
Vedere anche asort(), arsort(), ksort(), sort(), natsort() e rsort().
Ordina un array rispetto alle sue chiavi, mantenendo le associazioni. Questa funzione è utile con gli array associativi.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Si può modificare il comportamento dell'ordinamento usando il parametro opzionale sort_flags, per ulteriori dettagli vedere sort().
Vedere anche asort(), arsort(), krsort(), uksort(), sort(), natsort() e rsort().
Nota: Il secondo parametro è stato aggiunto in PHP 4.
Come array(), questa non è in realtà una funzione, bensì un costrutto del linguaggio. list() è usata per assegnare valori ad una lista di variabili in una sola operazione.
Nota: list() funziona solo su array numerici e si aspetta che gli indici numerici partano da 0.
Esempio 1. esempio di list()
|
Esempio 2. Esempio di uso di list()
|
Avvertimento |
list() assegna i valori cominciando dal parametro più a destra. Se si stanno usando variabili semplici, non ci si deve preoccupare di questo fatto. Ma se si stanno usando array con indici di solito ci si aspetta che l'ordine degli indici negli array sia quello scritto negli argomenti della funzione list(), da sinistra a destra; non è così. L'ordine è invertito. |
Esempio 3. Utilizzo di list() con gli indici
Restituisce il segente risultato (si noti l'ordine degli elementi rispetto all'ordine con cui sono stati scritti nella sintassi di list()).
|
(PHP 4, PHP 5)
natcasesort -- Ordina un array usando un algoritmo di "ordine naturale" non sensibile alle maiuscole/minuscoleQuesta funziona implementa un algoritmo di ordinamento che ordina le stringhe alfanumeriche come lo farebbe un essere umano, mantenendo le associazioni chiavi/valori. Questo è chiamato "ordine naturale".
natcasesort() è una versione, non sensibile alle maiuscole/minuscole, di natsort().
Esempio 1. esempio di natcasesort()
Questo codice genererà il seguente risultato:
Per maggiori informazioni vedere la pagina di Martin Pool Natural Order String Comparison . |
Vedere anche sort(), natsort(), strnatcmp() e strnatcasecmp().
Questa funzione implementa un algoritmo di ordinamento che ordina le stringhe alfanumeriche come lo farebbe un essere umano, mantenendo l'associazione chiavi/valori. Questo è chiamato "ordine naturale". Un esempio della differenza tra questo algoritmo e quello normalmente usato dai computer (usato in sort()) è dato qui sotto:
Esempio 1. esempio di natsort()
Questo codice genererà il seguente risultato:
Per ulteriori informazioni vedere la pagina di Martin Pool Natural Order String Comparison . |
Vedere anche natcasesort(), strnatcmp() e strnatcasecmp().
Restituisce l'elemento dell'array che sta nella posizione successiva a quella attuale indicata dal puntatore interno, oppure FALSE se non ci sono altri elementi.
next() si comporta come current(), con una differenza. Incrementa il puntatore interno dell'array di una posizione, prima di restituire il valore dell'elemento. Ciò significa che restituisce l'elemento successivo e incrementa il puntatore di una posizione. Se l'incremento fa sì che il puntatore vada oltre la fine della lista di elementi, next() restituisce FALSE.
Avvertimento |
Se l'array contiene elementi vuoti, o elementi che hanno il valore chiave uguale a 0 allora questa funzione restituisce FALSE anche per questi elementi. Per esplorare correttamente un array che può contenere elementi vuoti o con chiave uguale a 0 vedere la funzione each(). |
Esempio 1. Esempio di next() e funzioni relative
|
Restituisce l'elemento dell'array che sta nella posizione precedente a quella attuale indicata dal puntatore interno, oppure FALSE se non ci sono altri elementi.
Avvertimento |
Se l'array contiene degli elementi vuoti la funzione restituirà FALSE per questi valori. Per esplorare correttamente un array che può contenere elementi vuoti vedere la funzione each(). |
prev() si comporta come next(), tranne per il fatto di decrementare il puntatore interno di una posizione, invece che incrementarlo.
Esempio 1. Esempio di prev() e funzioni relative
|
range() restituisce una serie di elementi da min a max, inclusiva. Se min > max, la sequenza sarà decrescente.
Nuovo parametro: Il parametro opzionale step è stato aggiunto nel PHP 5.0.0.
Se il valore step è specificato, verrà utilizzato come incremento tra gli elementi della sequenza. step deve essere un numero positivo. Se non specificato, il valore predefinito per step è 1.
Esempio 1. esempi di range()
|
Nota: Prima della versione 4.1.0 la funzione range() generava solo array crescenti di interi. Il supporto per le sequenze di caratteri e array decrescenti è stata aggiunta nella 4.1.0. I valori delle sequenze di caratteri sono limitati alla lunghezza di 1 carattere. Se viene inserito un valore con una lunghezza maggiore, viene utilizzato solo il primo carattere.
Attenzione |
Nel PHP dalla versione 4.1.0 alla 4.3.2, range() vede le stringhe numeriche come stringhe e non come interi. Quindi, verranno utilizzate come sequenze di caratteri. Per esempio, "4242" viene trattato come "4". |
Vedere shuffle(), array_fill() e foreach.
reset() riporta il puntatore di array sul primo elemento e ne restituisce il valore.
Esempio 1. esempio di reset()
|
Questa funzione ordina un array in ordine decrescente.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
I frutti sono stati ordinati in ordine alfabetico decrescente.
Si può modificare il comportamento dell'ordinamento usando il parametro opzionale sort_flags, per maggiori dettagli vedere sort().
Questa funzione mescola un array (rende casuale l'ordine degli elementi).
Nota: Come in PHP 4.2.0, non vi è necessità di inizializzare il generatore di numeri casuali con srand() oppure con mt_srand() poichè viene eseguito in modo automatico.
Vedere anche arsort(), asort(), ksort(), rsort(), sort() e usort().
Questa funzione ordina un array. Gli elementi vengono disposti dal più piccolo al più grande.
Nota: Questa funzione assegna nuove chiavi agli elementi di array. Quindi non si limita a riordinare le chiavi, ma rimuove tutte le chiavi che siano state assegnate.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Esempio 1. esempio di sort()
Questo esempio mostrerà:
|
I frutti sono stati ordinati in ordine alfabetico.
Il secondo parametro opzionale sort_flags può essere usato per modificare il comportamento dell'ordinamento, usando i seguenti valori:
flag d'ordinamento:
SORT_REGULAR - compara gli elementi in modo normale
SORT_NUMERIC - compara gli elementi numericamente
SORT_STRING - compara gli elementi convertiti in stringa
Nota: Il secondo parametro è stato aggiunto in PHP 4.
Vedere anche arsort(), asort(), ksort(), natsort(), natcasesort(), rsort(), usort(), array_multisort() e uksort().
(PHP 3 >= 3.0.4, PHP 4, PHP 5)
uasort -- Ordina un array mediante una funzione definita dall'utente e mantiene le associazioniQuesta funzione ordina un array in modo tale che le chiavi mantengano la loro correlazione con gli elementi dell'array a cui sono associate. Questo è utile quando si ordinano array associativi in cui l'ordine degli elementi è importante. La funzione di comparazione deve essere fornita dall'utente.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere anche usort(), uksort(), sort(), asort(), arsort(), ksort() e rsort().
(PHP 3 >= 3.0.4, PHP 4, PHP 5)
uksort -- Ordina rispetto alle chiavi di un array mediante una funzione definita dall'utenteuksort() ordina rispetto alle chiavi di un array mediante una funzione di comparazione definita dall'utente. Se si vuole ordinare un array con dei criteri non usuali, si deve usare questa funzione.
La funzione cmp_function deve accettare due parametri che saranno valorizzati con coppie di chiavi di array. La funzione di confronto deve restituire un intero minore, uguale o maggiore di zero se il primo argomento è considerato minore, uguale o maggiore del secondo.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Esempio 1. esempio di uksort()
Questo esempio mostrerà:
|
Vedere anche usort(), uasort(), sort(), asort(), arsort(), ksort(), natsort() e rsort().
Ordina i valori di un array mediante una funzione di comparazione definita dall'utente. Se si vuole ordinare un array con dei criteri non usuali, si deve usare questa funzione.
La funzione di comparazione deve restituire un intero minore, uguale o superiore a zero se il primo elemento è da considerarsi rispettivamente minore, uguale o maggiore del secondo.
Nota: Se due parametri vengono valutati come uguali, il loro ordinamento nell'array ordinato è indefinito. Fino al PHP 4.0.6 le funzioni definite dall'utente mantenevano l'ordine originario per questi elementi, ma con il nuovo algoritmo di ordinamento introdotto con la versione 4.1.0 questo non succede più dal momento che non c'è un modo per ottenerlo in maniera efficiente.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: Ovviamente, in questo caso banale di ordinamento decrescente la funzione sort() sarebbe stata più appropriata.
Esempio 2. esempio di usort() con un array multidimensionale
Quando si ordina un array multidimensionale, $a e $b contengono riferimenti al primo indice dell'array. Questo esempio mostrerà:
|
Esempio 3. esempio di usort() usando una funzione membro di un oggetto
Questo esempio mostrerà:
|
Vedere anche uasort(), uksort(), sort(), asort(), arsort(),ksort(), natsort() e rsort().
Le funzioni aspell() permettono di controllare la correttezza di una parola e di offrire suggerimenti.
Nota: Questa estensione è stata rimossa da PHP e non è più disponibile dal PHP 4.3.0. Se si desidera utilizzare le funzioni di correzione ortografica in PHP, utilizzare pspell, che utilizza la libreria pspell e funziona anche con le nuove versioni di aspell.
aspell funziona solo con versioni molto vecchie (più o meno fino alla .27.*) della libreria aspell. Né il presente modulo, né quelle versioni della libreria sono più supportate. Necessita della libreria aspell, disponibile da: http://aspell.sourceforge.net/.
In PHP 4, these functions are only available if PHP was configured with --with-aspell=[DIR].
(PHP 3 >= 3.0.7, PHP 4 <= 4.2.3)
aspell_check_raw -- Controlla una parola senza togliere le maiuscole o cercare di eliminare gli spazi inutili [deprecated]aspell_check_raw() controlla la correttezza di una parola, senza modificare le maiuscole/minusciole o cercare di eliminare gli spazi inutili e restituisce TRUE se è corretta, FALSE altrimenti.
aspell_check() controlla la compitazione di una parola e restituisce TRUE se è corretta, FALSE altrimenti.
aspell_new() apre un nuovo dizionario e restituisce un puntatore (link) identificatore del dizionario, da utilizzare in altre funzioni aspell. Restituisce FALSE in caso di errore.
Per la matematica a precisione arbitraria PHP offre il Binary Calculator che supporta numeri di qualsiasi dimensione e precisione, rappresentati da stringhe;
Dalla versione 4.0.4 del PHP, libbcmath è inclusa nella distribuzione. Non c'è bisogno di altre librerie esterne per questa estensione.
Queste funzioni sono disponibili solo se PHP è stato configurato con --enable-bcmath. Nel PHP 3, queste funzioni sono disponibili solo se PHP NON è stato configurato con --disable-bcmath.
La versione per Windows di PHP ha già compilato il supporto per questo modulo. Non occorre caricare alcun modulo addizionale per potere utilizzare queste funzioni.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Per ulteriori dettagli e definizioni delle costanti PHP_INI_* vedere ini_set().
Breve descrizione dei parametri di configurazione.
Somma il primo operando con il secondo operando e restituisce la somma sotto forma di stringa. Il parametro opzionale precisione è utilizzato per impostare il numero di cifre dopo il punto decimale nel risultato.
Confronta il primo_operando e il secondo_operando e restituisce il risultato sotto forma di intero. Il parametro opzionale precisione è utilizzato per impostare il numero di cifre dopo il punto decimale che verranno usate nel confronto. Il valore restituito è 0 se i due operandi sono uguali. Se il primo_operando è più grande del secondo_operando il valore restituito è +1 e se il primo_operando è minore del secondo_operando il valore restituito è -1.
Divide il primo operando per il secondo operando e restituisce il risultato. Il parametro opzionale precisione imposta il numero di cifre dopo il punto decimale nel risultato.
Ricava il modulo di operando usando modulo.
Moltiplica il primo operando per il secondo operando e restituisce il risultato. Il parametro opzionale precisione imposta il numero di cifre dopo il punto decimale nel risultato.
Eleva x alla potenza y. Il parametro opzionale precisione può essere usato per impostare il numero di cifre dopo il punto decimale nel risultato.
Utilizza il metodo di esponenziazione veloce per elevare x alla potenza y rispetto al modulo modulo. Il parametro opzionale precisione può essere utilizzato per impostare il numero di cifre dopo il punto decimale.
Nota: Dal momento che questo metodo utilizza l'operatore modulo, numeri non naturali possono dare risultati inattesi. Un numero naturale è un qualsiasi numero positivo intero diverso da zero.
Le seguenti istruzioni sono funzionalmente identiche. La versione bcpowmod(), comunque, esegue in meno tempo e può accettare parametri più grandi.
(PHP 3, PHP 4, PHP 5)
bcscale -- Imposta il valore di precisione di default per tutte le funzioni matematich BCMathQuesta funzione imposta il valore di default del parametro precisione per tutte le funzioni BCMath susseguenti, che non specifichino esplicitamente un parametro di precisione numerica. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Restituisce la radice quadrata di operando. Il parametro opzionale precisione imposta il numero di cifre dopo il punto decimale nel risultato.
Sottrae il primo operando dal secondo operando e retituisce il risultato in una stringa. Il parametro opzionale scale è usato per impostare il numero di cifre dopo il punto decimale nel risultato.
Avvertimento |
Questo modulo è SPERIMENTALE. Ovvero, il comportamento di queste funzioni, i nomi di queste funzioni, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questo modulo è a vostro rischio. |
Bcompiler was written for two reasons:
To encode entire script in a proprietary PHP application |
To encode some classes and/or functions in a proprietary PHP application |
To enable the production of php-gtk applications that could be used on client desktops, without the need for a php.exe. |
To do the feasibility study for a PHP to C converter |
The second of these goals is achieved using the bcompiler_write_header(), bcompiler_write_class(), bcompiler_write_footer(), bcompiler_read(), and bcompiler_load() functions. The bytecode files can be written as either uncompressed or plain. The bcompiler_load() reads a bzip compressed bytecode file, which tends to be 1/3 of the size of the original file.
To create EXE type files, bcompiler has to be used with a modified sapi file or a version of PHP which has been compiled as a shared library. In this scenario, bcompiler reads the compressed bytecode from the end of the exe file.
bcompiler can improve performance by about 30% when used with uncompressed bytecodes only. But keep in mind that uncompressed bytecode can be up to 5 times larger than the original source code. Using bytecode compression can save your space, but decompression requires much more time than parsing a source. bcompiler also does not do any bytecode optimization, this could be added in the future...
In terms of code protection, it is safe to say that it would be impossible to recreate the exact source code that it was built from, and without the accompanying source code comments. It would effectively be useless to use the bcompiler bytecodes to recreate and modify a class. However it is possible to retrieve data from a bcompiled bytecode file - so don't put your private passwords or anything in it.
short installation note:
You need at least PHP 4.3. for the compression to work
To install on PHP 4.3 and later at the unix command prompt type pear install bcompiler
To install on Windows, until the binary package distribution mechanism is finished please search the archives of the pear-general mailing list for pre-built packages. (or send an email to it if you could not find a reference)
To install on older versions you need to make some slight changes to the build.
untar the bcompiler.tgz archive into php4/ext.(Get it directly from PECL http://pecl.php.net/get/bcompiler)
If the new directory is now called something like bcompiler-0.x, then you should rename it to bcompiler (except you only want to build it as self-contained php-module).
If you are using versions before PHP 4.3, the you will need to copy the Makefile.in.old to Makefile.in and config.m4.old to config.m4.
run phpize in ext/bcompiler
run ./buildconf in php4
run configure with --enable-bcompiler (and your other options)
make; make install
that's it.
If you have comments, bugfixes, enhancements or want to help developing this beast, you can drop me a mail at alan_k@php.net. Any help is very welcome.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Reads data from a bcompiler exe file and creates classes from the bytecodes.
Esempio 1. bcompiler_load() example
|
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Nota: Please use include or require statements to parse bytecodes, it's more portable and convenient way than using this function.
Reads data from a bzcompressed file and creates classes from the bytecodes. Please note that this function won't execute script body code contained in the bytecode file.
Nota: This function has been removed from bcompiler and is no longer available as of bcompiler 0.5.
Reads the bytecodes of a class and calls back to a user function.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Nota: Please use include or require statements to parse bytecodes, it's more portable and convenient way than using this function.
Reads data from a open file handle and creates classes from the bytecodes. Please note that this function won't execute script body code contained in the bytecode file.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
This reads the bytecodes from PHP for an existing class, and writes them to the open file handle, It does not perform dependency checking, so make sure you write the classes in an order that will not result in an 'undefined class' occurring when you load it.
Esempio 1. bcompiler_write_class() example
|
See also bcompiler_write_header(), and bcompiler_write_footer().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
This function reads the bytecodes from PHP for an existing constant, and writes them to the open file handle.
See also bcompiler_write_header(), and bcompiler_write_footer().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
An EXE (or self executable) file consists of 3 parts,
The stub (executable code, e.g. a compiled C program) that loads PHP interpreter, bcompiler extension, stored Bytecodes and initiates a call for the specified function (e.g. main) or class method (e.g. main::main) |
The Bytecodes (uncompressed only for the moment) |
The bcompiler EXE footer |
To obtain a suitable stub you can compile php_embed-based stub phpe.c located in the examples/embed directory on bcompiler's CVS.
Esempio 1. bcompiler_write_footer() example
|
See also bcompiler_write_header(), bcompiler_write_class(), and bcompiler_write_footer().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
This function complies specified source file into bytecodes, and writes them to the open file handle.
See also bcompiler_write_header(), and bcompiler_write_footer().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Writes the single character \x00 to indicate End of compiled data.
See also bcompiler_write_header(), and bcompiler_write_header().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
This reads the bytecodes from PHP for an existing function, and writes them to the open file handle. Order is not important, (eg. if function b uses function a, and you compile it like the example below, it will work perfectly OK).
See also bcompiler_write_header(), and bcompiler_write_footer().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
This function searches for all functions declared in the given file, and writes their correspondent bytecodes to the open file handle. Always remember to include/require the file you intend to compile.
See also bcompiler_write_header(), and bcompiler_write_footer().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Writes the header part of a bcompiler file. Optional second parameter can be used to write bytecode in a previously used format, so that you can use it with older versions of bcompiler.
See also bcompiler_write_file(), bcompiler_write_class(), bcompiler_write_function(), and bcompiler_write_footer().
Le funzioni bzip2 sono utilizzate per leggere e scrivere in modo trasparente i file compressi con bzip2 (.bz2).
Questo modulo tuilizza le funzioni della libreria bzip2 di Julian Seward. Questo modulo richiede che la versione di bzip2/libbzip2 sia >= 1.0.x.
Il supporto di bzip2 in PHP non è abilitato di default. Si deve utilizzare l'opzione --with-bz2[=DIR] quando si compila PHP, per abilitare il supporto bzip2.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Questa estensione definisce un tipo di risorsa: un puntatore a file che identifica il file bz2 su cui lavorare.
Questo esempio apre un file temporaneo e scrive una stringa di prova su di esso, quindi stampa il contenuto del file.
Esempio 1. breve esempio di bzip2
|
Chiude il file bzip2 referenziato dal puntatore bz.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Il puntatore al file deve essere valido, e deve puntare a un file gi$agrave; aperto con bzopen().
Vedere anche bzopen().
bzcompress() comprime la stringa sorgente e la restituisce come dati codificati in bzip2.
Il parametro opzionale dimblocco specifica la dimensione del blocco usato durante la compressione e dovrebbe essere un numero tra 1 e 9 dove 9 dà la compressione migliore, ma usando più risorse. dimblocco ha come valore predefinito 4.
Il parametro opzionale workfactor controlla il comportamento della fase di compressione quando deve trattare col caso peggiore, ovvero dati in ingresso molto ripetitivi. Il valore può variare tra 0 e 250, dove 0 è un caso speciale e 30 è il valore di default. Indipendentemente dal parametro workfactor, i dat generati sono gli stessi.
See also bzdecompress().
bzdecompress() decomprime la stringa sorgente contenente dati codificati in bzip2 e li restituisce. Se il parametro opzionale small è TRUE, verrà usato un algoritmo di decompressione alternativo che richiede meno memoria (la maximum quantità massima di memoria richiesta scende a 2300K) ma funziona a circa la metà della velocità. Vedere la documentazione di bzip2 per maggiori informazioni su questa funzionalità.
See also bzcompress().
Restituisce il codice di un qualsiasi errore bzip2 restituito dal puntatore al file bz.
Vedere anche bzerror() e bzerrstr().
(PHP 4 >= 4.3.3, PHP 5)
bzerror -- Restituisce il codice d'errore bzip2 e la stringa corrispondente in un arrayRestituisce il codice e la stringa di errore, sotto forma di array associativo, di un errore bzip2 restituito dal puntatore bz.
Vedere anche bzerrno() e bzerrstr().
Resituisce la stringa di errore bzip2 restituito dal puntatore bz.
Forza la scrittura di tutti i dati che sono nel buffer del puntatore bz.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Apre un file bzip2 (.bz2) in lettura o scrittura. nomefile è il nome del file da aprire. Il parametro modo è simile a quello della funzione fopen() (`r' per lettura, `w' per scrittura, ecc.).
Se l'operazione fallisce, la funzione restituisce FALSE, altrimenti restituisce un puntatore al file appena aperto.
Vedere anche bzclose().
bzread() legge fino a lunghezza byte dal puntatore bzip2 specificato da bz. La pettura termina quando lunghezza byte (decompressi) sono stati letti o quando viene raggiunto l'EOF. Se il parametro opzionale lunghezza è omesso, bzread() leggerà 1024 byte (decompressi) ogni volta.
bzwrite() scrie il contenuto della stringa dati nel file bzip2 puntato da bz. Se il parametro opzionale lunghezza è specificato, la scrittura si fermerà dopo che siano stati scritti lunghezza byte (decompressi) o al raggiungimento della fine della stringa.
L'estensione calendar presenta una serie di funzioni che semplificano la conversione tra differenti formati di calendario. Il formato intermedio o standard è basato sul Conteggio del Giorno Giuliano. Il Conteggio Giuliano è un conteggio di giorni che parte molto prima di qualsiasi data la maggior parte della gente potrebbe usare (circa il 4000 a.C.). Per convertire tra i sistemi di calendario, si deve prima convertire nel sistema del Giorno Giuliano, poi nel sistema di calendario scelto. Il Conteggio del Giorno Giuliano è molto diverso dal Calendario Giulano! Per maggiori informazioni sui sistemi di calendario vedere http://www.boogle.com/info/cal-overview.html. Parti di questa pagina sono inclusi in queste istruzioni, citate tra virgolette.
Affinché queste funzioni siano disponibili, occorre compilare PHP con l'opzione --enable-calendar.
La versione per Windows di PHP ha già compilato il supporto per questo modulo. Non occorre caricare alcun modulo addizionale per potere utilizzare queste funzioni.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Le seguenti costanti sono disponibili dal PHP 4.3.0 :
Le seguenti costanti sono disponibili dal PHP 5.0.0 :
(PHP 4 >= 4.1.0, PHP 5)
cal_days_in_month -- Restituisce il numero di giorni di un mese per un dato anno e calendarioQuesta funzione restituisce il numero di giorni che compongono il mese dell'anno nel calendar specificato.
Vedere anche jdtounix().
cal_from_jd() converte il Giorno Giuliano specificato in giornogiuliano in una data del calendario specificato. I valori ammessi di calendario sono CAL_GREGORIAN, CAL_JULIAN, CAL_JEWISH e CAL_FRENCH.
Esempio 1. esempio di cal_from_jd()
Questo mostrerà:
|
Vedere anche cal_to_jd().
cal_info() restituisce informazioni sullo specifico calendario o su tutti i calendari supportati se il parametro calendario non è specificato.
Lei informazioni sul calendario sono restituite in un array contenente gli elementi calname, calsymbol, month, abbrevmonth e maxdaysinmonth.
Se calendario non è specificato, le informazioni su tutti i calendari supportati sono restituite nell'array. Questa funzionalità sarà disponibile dal PHP 5.
cal_to_jd() calcola il Giorno Giuliano per una data del calendario specificato. I valori supportati per calendario sono CAL_GREGORIAN, CAL_JULIAN, CAL_JEWISH e CAL_FRENCH.
Vedere anche cal_to_jd().
(PHP 3 >= 3.0.9, PHP 4, PHP 5)
easter_date -- Restituisce un timestamp Unix della mezzanotte del giorno di Pasqua di un dato annoRestituisce il timestamp Unix corrispondente alla mezzanotte del giorno di Pasqua dell'anno specificato.
Dal PHP 4.3.0, il parametro anno è opzionale e ha come default l'anno corrente, se omesso.
Avvertimento |
Questa funzione gerererà un allarme (warning) se l'anno è fuori dall'escursione di validità dei timestamp UNIX (cioè prima del 1970 o dopo il 2037). |
La data della Pasqua fu definita dal Concilio di Nicea nel 325 d.C. come la Domenica successiva alla prima luna piena dopo l'Equinozio di Primavera. Si assume che l'Equinozio cada sempre il 21 Marzo, quindi il calcolo si riduce alla determinazione della data della luna piena e la data della Domenica seguente. L'algoritmo qui usato fu proposto attorno all'anno 532 d.C. da Dionysius Exiguus (Dionigi il Piccolo). Nel Calendario Giuliano (for years before 1753) un semplice ciclo di 19 anni è usato per tracciare le fasi della Luna. Nel Calendario Gregoriano (per gli anni dopo il 1753 - ideato da Clavius e Lilius, e introdotto da Papa Gregorio XIII nell'Ottobre 1582, e in Gran Bretagna e nelle sue colonie nel Settembre 1752) due fattori correttivi sono aggiunti per rendere più accurato il ciclo.
(Il codice è basato su un programma in C di Simon Kershaw, <webmaster at ely.anglican dot org>)
Vedere easter_days() per il calcolo della Pasqua prima del 1970 o dopo il 2037.
(PHP 3 >= 3.0.9, PHP 4, PHP 5)
easter_days -- Restituisce il numero di giorni tra il 21 Marzo e Pasqua, dato un annoRestituisce il numero di giorni tra il 21 Marzo e Pasqua per un dato anno. Se l'anno non è specificato, si assume l'anno corrente.
Dal PHP 4.3.0, il parametro anno è opzionale e ha come default l'anno corrente, se omesso.
Anche il parametro metodo è stato introdotto nel PHP 4.3.0 e permette di calcolare la data della Pasqua basata sul calendario Gregoriano durante gli anni 1582 - 1752 quando è impostato a CAL_EASTER_ROMAN, vedere le costanti di calendario per altre costanti valide.
Questa funzione può essere usata al posto di easter_date() per calcolare la Pasqua per gli anni che cadono fuori dalla gamma di validità dei timestamp Unix (cioè prima del 1970 o dopo il 2037).
La data della Pasqua fu definita dal Concilio di Nicea nel 325 d.C. come la Domenica successiva alla prima luna piena dopo l'Equinozio di Primavera. Si assume che l'Equinozio cada sempre il 21 Marzo, quindi il calcolo si riduce alla determinazione della data della luna piena e la data della Domenica seguente. L'algoritmo qui usato fu proposto attorno all'anno 532 d.C. da Dionysius Exiguus (Dionigi il Piccolo). Nel Calendario Giuliano (for years before 1753) un semplice ciclo di 19 anni è usato per traciare le fasi della Luna. Nel Calendario Gregoriano (per gli anni dopo il 1753 - ideato da Clavius e Lilius, e introdotto da Papa Gregorio XIII nell'Ottobre 1582, e in Gran Bretagna e nelle sue colonie nel Settembre 1752) due fattori correttivi sono aggiunti per rendere più accurato il ciclo.
(Il codice è basato su un programma in C di Simon Kershaw, <webmaster at ely.anglican dot org>)
Vedere anche easter_date().
(PHP 3, PHP 4, PHP 5)
FrenchToJD -- Converte una data del Calendario Repubblicano Francese in un Giorno GiulianoConverte una data del Calendario Repubblicano Francese in un Giorno Giuliano.
Queste funzioni convertono solo le date con gli anni dal 1 al 14 (date Gregoriane dal 22 Settmbre 1792 al 22 Settembre 1806). Questo copre più del periodo in cui fu in uso il calendario.
L'intervallo valido per il Calendario Gregoriano è dal 4714 a.C. al 9999 d.C.
Anche se questa funzione può gestire date fino al 4714 a.C., qusto utilizzo potrebbe non avere senso. Il calendario Gregoriano fu istituito il 15 Ottobre 1582 (o 5 Ottobre 1582 nel calendario Giuliano). Alcune nazioni non lo accettarono per un lungo periodo. Per esempio, il Regno Unito si convertì nel 1752, L'Unione Sovietica nel in 1918 e la Grecia nel 1923. La maggior parte delle nazioni Europee usavano il calendario Giuliano prima del Gregoriano.
Restituisce il giorno della settimana. Può restituire una stringa o un intero a seconda del modo.
Restituisce una stringa contenente il nome di un mese. modo dice alla funzione verso quale calendario convertire il giorno Giuliano, e che tipo di nome di mese restituire.
Tabella 1. Modi del Calendario
Modo | Significato | Valori |
---|---|---|
0 | Gregoriano abbreviato | Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec |
1 | Gregoriano | January, February, March, April, May, June, July, August, September, October, November, December |
2 | Giuliano abbreviato | Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec |
3 | Giuliano | January, February, March, April, May, June, July, August, September, October, November, December |
4 | Giudeo | Tishri, Heshvan, Kislev, Tevet, Shevat, AdarI, AdarII, Nisan, Iyyar, Sivan, Tammuz, Av, Elul |
5 | Repubblicano Francese | Vendemiaire, Brumaire, Frimaire, Nivose, Pluviose, Ventose, Germinal, Floreal, Prairial, Messidor, Thermidor, Fructidor, Extra |
(PHP 3, PHP 4, PHP 5)
JDToFrench -- Converte un Giorno Giuliano in una data del Calendario Repubblicano FranceseConverte un Giorno Giuliano in una data del calendario Repubblicano Francese.
Converte il Giorno Giuliano in una stringa contenente la data Gregoriana nel formato "mese/giorno/anno".
Converte un Giorno Giuliano nel Calendario Giudeo.
I parametri opzionali ebraico e fl sono disponibili dal PHP 5.0.0
Se il parametro ebraico è TRUE, il parametro fl è usato per il formato di output Ebraico. I formati disponibili sono: CAL_JEWISH_ADD_ALAFIM_GERESH, CAL_JEWISH_ADD_ALAFIM, CAL_JEWISH_ADD_GERESHAYIM.
Converte un Giorno Giuliano in una stringa contenente la data del calendario Giuliano nel formato "mese/giorno/anno".
Questa funzione restituisce un timestamp Unix corrispondente al Giorno Giuliano giornogiuliano o FALSE se giornogiuliano non è all'interno della gamma Unix (anni Gregoriani tra il 1970 e il 2037 o 2440588 <= giornogiuliano <= 2465342 ). L'ora restituita è locale (e non GMT).
See also unixtojd().
Anche se questa funzione può gestire date fino all'anno 1 (3761 B.C.), questo utilizzo potrebbe non avere senso. Il calendario Giudeo è usato da parecchie migliaia di anni, ma nei primi tempi non c'era una formula per stabilire l'inizio del mese. Il nuovo mese iniziava quando si vedeva la prima volta la luna.
L'intervallo valido per il Calendario Giuliano è dal 4713 a.C. al 9999 d.C.
Anche se questa funzione può gestire date fino al 4713 a.C., questo utilizzo potrebbe non avere senso. Il calendario fu creato nel 46 a.C., ma i dettagli non furono perfezionati fino almeno al 8 d.C., e forse anche fino al quarto secolo. Inoltre, l'inizio dell'anno variava da una cultura all'altra - non tutti accettavano Gennaio come primo mese.
Attenzione |
Il calendario attuale, utilizzato in tutto il mondo, è il calendario Gregoriano. gregoriantojd() può essere utilizzata per convertire queste date nel corrispondente Giorno Giuliano. |
Restituisce il Giorno Giuliano di un timestamp Unix (secondi dal 1/1/1970), o del giorno corrente se timestamp non è specificato.
Vedere anche jdtounix().
Queste funzioni si interfacciano con le API CCVS, permettendo di lavorare direttamente con CCVS dagli script PHP. CCVS è la soluzione di RedHat per il "mediatore" nella gestione dei pagamenti con carta di credito. Permette di comunicare direttamente con le società di autorizzazione di transazione attraverso una *nix box e un modem. Usando il modulo CCVS per PHP, è possibile procesare direttamente le carte di credito attraverso gli script PHP. Le seguenti informazioni esemplificheranno il processo.
Nota: CCVS è stato abbandonato da Red Hat e non c'è l'intenzione di fornire altre chiavi o contratti di assistenza. Chi cerca un sostituto può considerare MCVE della Main Street Softworks come una possibile alternativa. Il prodotto è simile nella struttura ed ha un supporto documentato per PHP!
Questa estensione è stata rimossa dal PHP e non è più disponibile dal PHP 4.3.0. Se si vogliono utilizzare delle funzioni di processamento delle carte di credito, utilizzare piuttosto MCVE.
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=[DIR], where DIR is the path to your CCVS installation. Please note that CCVS support requires that DIR/lib and DIR/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.)
RedHat non supporta più CCVS; comunque una documentazione leggermente datata è ancora disponibile presso http://www.redhat.com/docs/manuals/ccvs/.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(4.0.2 - 4.2.3 only)
ccvs_command -- Esegue un comando caratteristico di un particolare protocollo, quindi non disponibile nelle API di CCVS
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(4.0.2 - 4.2.3 only)
ccvs_count -- Conta quante transazioni di un dato tipo sono archiviate nel sistema
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(4.0.2 - 4.2.3 only)
ccvs_return -- Trasferisce fondi dal merchant al titolare della carta di credito
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(4.0.2 - 4.2.3 only)
ccvs_textvalue -- Restuisce il valore testuale reso dalla precedente chiamata di funzione
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Queste funzioni permettono di ottenere informazioni sulle classi e sulle istanze degli oggetti. Si può ricavare il nome della classe da cui deriva un dato oggetto, come le sue proprietà e i suoi metodi. Utilizzando queste funzioni si ottiene, non solo a quale classe appartiene un dato oggetto, ma anche i suoi "padri" (ad esempio da quale classe è derivata la classe dell'oggetto).
Non è necessaria nessuna installazione per usare queste funzioni, esse fanno parte del core di PHP.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
In questo esempio, prima si definisce una classe base, quindi una seconda che deriva dalla prima. La classe base descrive gli aspetti generali degli ortaggi, se è commestibile e quale sia il colore. La classe derivata Spinaci aggiunge i metodi di cottura e di verifica della completa cottura.
Esempio 1. classi.inc
|
A questo punto si istanziano 2 oggetti a partire da queste classi e si visualizzeranno le informazioni relative a questi oggetti, compresi i loro padri. Verranno anche inserite funzioni di utilità principalmente con lo scopo di rendere chiara la visualizzazione delle variabili.
Esempio 2. test_script.php
Un aspetto da notare nell'esempio precedente è che l'oggetto $frondoso è un'istanza della classe Spinaci che a sua volta è una sottoclasse di Ortaggio, quindi l'ultima parte dell'esempio visualizzerà:
|
(PHP 4 >= 4.0.5, PHP 5)
call_user_method_array -- Richiama il metodo dato con un array di parametri [deprecated]Avvertimento |
A partire dalla versione 4.1.0 è sconsigliato l'uso di call_user_method_array(); in sostituzione utilizzare la serie di funzioni call_user_func_array() con sintassi array(&$obj, "method_name"). |
Richiama il metodo indicato da nome_metodo dell'oggetto oggetto, utilizzando i parametri forniti in array_parametri.
Vedere anche: call_user_func_array() e call_user_func().
(PHP 3 >= 3.0.3, PHP 4, PHP 5)
call_user_method -- Chiama un metodo dell'oggetto indicato [deprecated]Avvertimento |
A partire dalla versione 4.1.0 l'uso della funzione call_user_method() è sconsigliato; in sostituzione utilizzare la serie call_user_func() con la sintassi array(&$obj, "method_name"). |
Richiama il metodo indicato da nome_metodo dell'oggetto oggetto. Di seguito si fornisce un esempio di utilizzo. Qui si definisce una classe, si istanzia un oggetto, e si utilizza call_user_method() per richiamare il metodo stampa_info
<?php class Stato { var $NOME; var $TLD; function Stato($nome, $tld) { $this->NOME = $nome; $this->TLD = $tld; } function stampa_info($prestr = "") { echo $prestr . "Stato: " . $this->NOME . "\n"; echo $prestr . "Dominio di primo livello: " . $this->TLD . "\n"; } } $paese = new Stato("Peru", "pe"); echo "* Richiamo il metodo direttamente\n"; $paese->stampa_info(); echo "\n* utilizzo dello stesso metodo in modo indiretto\n"; call_user_method("stampa_info", $paese, "\t"); ?> |
Vedere anche call_user_func_array() e call_user_func().
Questa funzione restituisce TRUE se la classe indicata dal parametro nome_classe è stata definita, altrimenti restituisce FALSE .
class_exists(), per default, tenta di eseguire __autoload, se non si desidera che class_exists() esegua __autoload(), impostare il parametro autoload a FALSE.
Esempio 2. Esempio di uso di autoload
|
Nota: Il parametro autoload è stato aggiunto in PHP 5
Vedere anche interface_exists() e get_declared_classes().
Questa funzione restituisce un array contenente i nomi dei metodi definiti per la classe specificata da nome_classe.
Nota: Dalla versione 4.0.6 di PHP, si può specificare direttamente l'oggetto anziché la classe nel parametro nome_classe. Ad esempio:
Esempio 1. Esempio di get_class_methods()
Il precedente esempio visualizzerà:
|
Avvertimento |
Dal PHP 5, questa funzione restituisce il nome dei metodi così come sono dichiarati (sensibile alle maiuscole). In PHP 4 erano restituiti in minuscolo. |
Vedere anche get_class_vars() e get_object_vars()
Questa funzione restituisce un array associativo contenente le proprietà di default pubbliche della classe. Gli elementi dell'array prodotto sono nel formato nomevariabile => valore.
Nota: Nelle verioni di PHP precedenti alla 4.2.0, le variabili della classe non inizializzate non sono elencate da get_class_vars().
Esempio 1. get_class_vars() esempio
Il precedente esempio visualizzerà:
|
Vedere anche get_class_methods() e get_object_vars()
Questa funzione restituisce il nome della classe di cui l'oggetto oggetto è un'istanza. Restituisce FALSE se oggetto non è un oggetto.
Nota: Le classi definite nei moduli di PHP sono restituite nella notazione originale. In PHP 4, get_class() restituisce il nome delle classi definite dagli utenti in minuscolo, mentre in PHP 5 i nomi delle classi saranno restituiti nella notazione originale, come i nomi delle classi nei moduli.
Esempio 1. Utilizzo di get_class()
Il precedente esempio visualizzerà:
|
Vedere anche get_parent_class(), gettype() e is_subclass_of()
Questa funzione restituisce un array con i nomi delle classi definite all'interno dello script corrente.
Nota: Nella versione 4.0.1pl2 di PHP, in testa all'array erano indicate tre ulteriori classi: stdClass (definita in Zend/zend.c), OverloadedTestClass (definita in ext/standard/basic_functions.c) e Directory (definita in ext/standard/dir.c).
Occorre notare che, in base a quali librerie sono state compilate in PHP, possono essere rilevate ulteriori classi. Questo significa, anche, che non si potranno definire delle classi con questi nomi. Un'elenco delle classi predefinite è nella sezione Predefined Classes dell'appendice.
Vedere anche class_exists() e get_declared_interfaces().
This function returns an array of the names of the declared interfaces in the current script.
See also get_declared_classes().
Questa funzione restituisce un array associativo con le proprietà definite nell'oggetto passato nel parametro oggetto .
Nota: Nelle versioni di PHP precedenti la 4.2.0, le eventuali variabili dichiarate in nella classe oggetto ma non ancora valorizzate non saranno restituite nell'array. Nelle versioni successive alla 4.2.0, saranno restituite nell'array con valore NULL.
Esempio 1. Utilizzo di get_object_vars()
Il precedente esempio visualizzerà:
|
Vedere anche get_class_methods() e get_class_vars().
(PHP 4, PHP 5)
get_parent_class -- Restituisce il nome della classe genitrice di un oggetto o di una classeSe oggetto è un oggetto, la funzione restituisce il nome del genitore della classe di cui oggetto è un'istanza.
Se oggetto è una stringa, la funzione restituisce il nome della classe genitrice della classe di cui oggetto indica il nome. Questa funzionalità è stata aggiunta nella versione 4.0.5 di PHP.
Esempio 1. Utilizzo di get_parent_class()
Il precedente esempio visualizzerà:
|
Vedere anche get_class(), is_subclass_of()
This function returns TRUE if the interface given by interface_name has been defined, FALSE otherwise.
interface_exists() will attempt to call __autoload by default, if you don't want interface_exists() to call __autoload, you can set the parameter autoload to FALSE.
See also class_exists().
(PHP 4 >= 4.2.0, PHP 5)
is_a -- Restituisce TRUE se l'oggetto appartiene a questa classe o se ha questa classe tra i suoi genitoriQuesta funzione restituisce TRUE appartiene a questa classe oppure ha questa classe tra i suoi genitori, FALSE in caso diverso.
In PHP 5 la funzione is_a() è sconsigliata in favore di instanceof. L'esempio precedente, in PHP 5, può essere riscritto come:
Vedere anche get_class(), get_parent_class() e is_subclass_of().
(PHP 4, PHP 5)
is_subclass_of -- Restituisce TRUE se l'oggetto ha questa classe come uno dei suoi genitoriQuesta funzione restituisce TRUE se obj, appartiene ad una sottoclasse di nome_classe, altrimenti FALSE.
Nota: Dal PHP 5.0.3 si può specificare il parametro oggetto come stringa (il nome della classe).
Esempio 1. Esempio di uso di is_subclass_of()
Il precedente esempio visualizzerà:
|
Vedere anche get_class(), get_parent_class() e is_a().
Questa funzione restituisce TRUE se il metodo indicato dal parametro nome_metodo è stato nell'oggetto indicato da oggetto, altrimenti FALSE.
This function checks if the given property exists in the specified class (and if it was declared as public).
Nota: As opposed with isset(), property_exists() returns TRUE even if the property has the value NULL.
A string with the class name or an object of the class to test for
The name of the property
These functions allow the dynamic manipulation of PHP classes, at runtime.
Nota: This extension has been replaced by runkit, which is not limited to class manipulation but has function manipulation, as well.
This PECL extension is not bundled with PHP.
Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: http://pecl.php.net/package/classkit.
You may download this PECL extension DLL from the PHP Downloads page or at http://snaps.php.net/.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Nota: This function cannot be used to manipulate the currently running (or chained) method.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Esempio 1. classkit_import() example
Il precedente esempio visualizzerà:
|
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
The class to which this method will be added
The name of the method to add
Comma-delimited list of arguments for the newly-created method
The code to be evaluated when methodname is called
The type of method to create, can be CLASSKIT_ACC_PUBLIC, CLASSKIT_ACC_PROTECTED or CLASSKIT_ACC_PRIVATE
Nota: This parameter is only used as of PHP 5, because, prior to this, all methods were public.
Esempio 1. classkit_method_add() example
Il precedente esempio visualizzerà:
|
classkit_method_copy() |
classkit_method_redefine() |
classkit_method_remove() |
classkit_method_rename() |
create_function() |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Destination class for copied method
Destination method name
Source class of the method to copy
Name of the method to copy from the source class. If this parameter is omitted, the value of dMethod is assumed.
Esempio 1. classkit_method_copy() example
Il precedente esempio visualizzerà:
|
classkit_method_add() |
classkit_method_redefine() |
classkit_method_remove() |
classkit_method_rename() |
Nota: This function cannot be used to manipulate the currently running (or chained) method.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
The class in which to redefine the method
The name of the method to redefine
Comma-delimited list of arguments for the redefined method
The new code to be evaluated when methodname is called
The redefined method can be CLASSKIT_ACC_PUBLIC, CLASSKIT_ACC_PROTECTED or CLASSKIT_ACC_PRIVATE
Nota: This parameter is only used as of PHP 5, because, prior to this, all methods were public.
Esempio 1. classkit_method_redefine() example
Il precedente esempio visualizzerà:
|
classkit_method_add() |
classkit_method_copy() |
classkit_method_remove() |
classkit_method_rename() |
Nota: This function cannot be used to manipulate the currently running (or chained) method.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
The class in which to remove the method
The name of the method to remove
classkit_method_add() |
classkit_method_copy() |
classkit_method_redefine() |
classkit_method_rename() |
Nota: This function cannot be used to manipulate the currently running (or chained) method.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
The class in which to rename the method
The name of the method to rename
The new name to give to the renamed method
ClibPDF permette di creare documenti PDF utilizzando PHP. La funzionalità e l' API di ClibPDF sono simili a quelle di PDFlib. Questa documentazione dovrebbe essere letta insieme al manuale di ClibPDF poichè entra maggiormente nel dettaglio della libreria.
Molte funzioni nella ClibPDF nativa e nel modulo PHP , così come nella PDFlib hanno lo stesso nome. Tutte le funzioni ad eccezione di cpdf_open() hanno l'identificatore del documento come loro primo parametro.
Attualmente questo identificatore non è usato internamente dato che ClibPDF non supporta la creazione di svariati documenti PDF contemporaneamente. Attualmente non bisognerebbe provare a farlo, dato che i risultati sono imprevedibili. Non è possibile controllare quali siano le conseguenze in un ambiente multi processo. Secondo l'autore di ClibPDF questo cambierà in una delle prossime release (la versione corrente quando questo è stato scritto è la 1.10). Se si ha bisogno di questa funzionalità utilizzare il modulo pdflib.
Un'interessante caratteristica di ClibPDF (e PDFlib) è l'abilità di creare il documento PDF completamente in memoria senza utilizzare file temporanei. Inoltre fornisce l'abilità di passare le coordinare in un'unità di lunghezza predefinita. (Questa caratteristica puo'essere simulata da pdf_translate() quando si utilizzano le funzioni PDFlib.)
Un'altra interessante caratteristica di ClibPDF è il fatto che ogni pagina può essere modificata in qualsiasi momento anche se è già stata aperta una nuova pagina. La funzione cpdf_set_current_page() permette di lasciare la pagina corrente e modificare un'altra pagina.
La maggioranza delle funzioni sono abbastanza facili da usare. La parte più difficile è probabilmente creare un simplice documento PDF. L'esempio seguente dovrebbe essere utile per cominciare. Crea un documento con una pagina. La pagina contiene il testo "Times-Roman" con un font di 30pt. Il testo è sottolineato.
Nota: Se si è interessati ad alternativi generatori PDF free non utilizzare le librerie PDF esterne, vedere questa FAQ per dettagli.
Per potere utilizzare le funzioni ClibPDF occorre installare il modulo ClibPDF. Questo è disponibile in FastIO, ma richiede l'acquisto di una licenza per uso commerciale. Il PHP richiede la libreria cpdflib >= 2.
Per avere disponibili queste funzionalità occorre compilare il PHP con --with-cpdflib[=DIR]. Dove DIR indica la directory in cui è installato cpdflib, per default /usr. In aggiunta si può specificare le librerie jpeg e tiff da utilizzare. Per fare ciò aggiungere alla linea di configurazione le opzioni --with-jpeg-dir[=DIR] e --with-tiff-dir[=DIR].
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Esempio 1. Semplice esempio ClibPDF
|
La distribuzione pdflib contiene un esempio più complicato che crea una serie di pagine con un orologio analogico. Di seguito si trova questo esempio convertito in PHP utilizzando l'estensione ClibPDF:
Esempio 2. esempio pdfclock dalla distribuzione pdflib 2.0
|
La cpdf_add_annotation() aggiunge una nota con l'angolo in basso a sinistra in (llx, lly) e l'angolo in alto a destra in (urx, ury). Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Il parametro opzionale mode determina l'unità di misura. Se viene impostato a 0, oppure omesso, si utilizza come default l'unità specificata nella pagina. Altrimenti le coordinate sono misurate in punti postscript ignorando l'unità corrente.
(PHP 3 >= 3.0.9, PHP 4, PHP 5 <= 5.0.4)
cpdf_add_outline -- Aggiunge un segnalibro per la pagina correnteLa funzione cpdf_add_outline() aggiunge un segnalibro con il testo testo che punta alla pagina corrente.
Esempio 1. Aggiungere il contorno alla pagina
|
La funzione cpdf_arc() disegna un arco con centro nel punto (x-coor, y-coor) e raggio radius, che comincia all'angolo inizio e che termina all'angolo fine. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Il parametro opzionale mode determina l'unità di misura. Se viene impostato a 0, oppure omesso, si utilizza come default l'unità specificata nella pagina. Altrimenti le coordinate sono misurate in punti postscript ignorando l'unità corrente.
Vedere anche cpdf_circle().
La funzione cpdf_begin_text() avvia una sezione di testo. Restituisce TRUE in caso di successo, FALSE in caso di fallimento. La sezione creata deve essere terminata con cpdf_end_text().
Vedere anche cpdf_end_text().
La funzione cpdf_circle() disegna un cerchio con centro nel punto (x-coor, y-coor) e raggio raggio. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Il parametro opzionale mode determina l'unità di misura. Se viene impostato a 0, oppure omesso, si utilizza come default l'unità specificata nella pagina. Altrimenti le coordinate sono misurate in punti postscript ignorando l'unità corrente.
Vedere anche cpdf_arc().
La funzione cpdf_clip() taglia tutti i disegni dal path corrente. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
La funzione cpdf_close() chiude il documento pdf. Restituisce TRUE in caso di successo, FALSE in caso di fallimento. Questa dovrebbe essere l'ultima funzione dopo persino cpdf_finalize(), cpdf_output_buffer() e cpdf_save_to_file().
Vedere anche cpdf_open().
(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)
cpdf_closepath_fill_stroke -- Close, fill and stroke current pathThe cpdf_closepath_fill_stroke() function closes, fills the interior of the current path with the current fill color and draws current path. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also cpdf_closepath(), cpdf_stroke(), cpdf_fill(), cpdf_setgray_fill(), cpdf_setgray(), cpdf_setrgbcolor_fill(), cpdf_setrgbcolor().
(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)
cpdf_closepath_stroke -- Chiude il path e disegna una linea lungo il pathLa funzione cpdf_closepath_stroke() è una combinazione di cpdf_closepath() e cpdf_stroke(). Dopo libera il path. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere anche cpdf_closepath() e cpdf_stroke().
La funzione cpdf_closepath() chiude la path corrente. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
La funzione cpdf_continue_text() scrive la stringa testo nella riga seguente. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere anche cpdf_show_xy(), cpdf_text(), cpdf_set_leading() e cpdf_set_text_pos().
La funzione cpdf_curveto() disegna una curva di Bezier dal punto corrente al punto (x3, y3) utilizzando (x1, y1) e (x2, y2) come punti di controllo. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Il parametro opzionale mode determina l'unità di misura. Se viene impostato a 0, oppure omesso, si utilizza come default l'unità specificata nella pagina. Altrimenti le coordinate sono misurate in punti postscript ignorando l'unità corrente.
Vedere anche cpdf_moveto(), cpdf_rmoveto(), cpdf_rlineto() e cpdf_lineto().
La funzione cpdf_end_text() termina una sezione di testo cominciata con cpdf_begin_text(). Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere anche cpdf_begin_text().
The cpdf_fill_stroke() function fills the interior of the current path with the current fill color and draws current path. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also cpdf_closepath(), cpdf_stroke(), cpdf_fill(), cpdf_setgray_fill(), cpdf_setgray(), cpdf_setrgbcolor_fill(), cpdf_setrgbcolor().
La funzione cpdf_fill() riempie l'interno del path corrente con il colore di riempimento corrente. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere anche cpdf_closepath(), cpdf_stroke(), cpdf_setgray_fill(), cpdf_setgray(), cpdf_setrgbcolor_fill() e cpdf_setrgbcolor().
La funzione cpdf_finalize_page() chiude la pagina numero numero della pagina. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Questa funzione serve solo a preservare la memoria. Una pagina chiusa occupa meno memoria ma non può più essere modificata.
Vedere anche cpdf_page_init().
La funzione cpdf_finalize() chiude il documento. Bisogna comunque richiamare cpdf_close(). Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere anche 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. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also cpdf_open().
La funzione cpdf_import_jpeg() apre un'immagine contenuta nel file con nome nome del file. Il formato dell'immagine deve essere jpeg. L' immagine viene inserita nella pagina corrente alla posizione (x-coor, y-coor). L'immagine è ruotata di angolo gradi. Il parametro gsave dovrebbe essere diverso da zero affinchè questa funzione operi correttamente.
Il parametro opzionale mode determina l'unità di misura. Se viene impostato a 0, oppure omesso, si utilizza come default l'unità specificata nella pagina. Altrimenti le coordinate sono misurate in punti postscript ignorando l'unità corrente.
Vedere anche cpdf_place_inline_image().
La funzione cpdf_lineto() disegna una linea dal punto corrente al punto con coordinate (x-coor, y-coor). Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Il parametro opzionale mode determina l'unità di misura. Se viene impostato a 0, oppure omesso, si utilizza come default l'unità specificata nella pagina. Altrimenti le coordinate sono misurate in punti postscript ignorando l'unità corrente.
Vedere anche cpdf_moveto(), cpdf_rmoveto() e cpdf_curveto().
La funzione cpdf_moveto() setta il punto corrente alle coordinate x-coor e y-coor. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Il parametro opzionale mode determina l'unità di misura. Se viene impostato a 0, oppure omesso, si utilizza come default l'unità specificata nella pagina. Altrimenti le coordinate sono misurate in punti postscript ignorando l'unità corrente.
La funzione cpdf_newpath() inizia un nuovo path sul documento indicato dal parametro documento pdf. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
La funzione cpdf_open() apre un nuovo documento pdf. Il primo parametro setta il fattore di compressione del documento se è diverso da 0. Il secondo parametro, opzionale, setta il file in cui il documento viene scritto. Se è omesso il documento è creato in memoria e può essere scritto su un file con cpdf_save_to_file() oppure scritto sullo standard output con cpdf_output_buffer().
Nota: Il valore di ritorno sarà necessario nelle future versione di ClibPDF come primo parametro di tutte le altre funzioni che scrivono sul documento PDF.
La libreria ClibPDF considera il nome del file "-" come sinonimo di stdout. Se il PHP è compilato come modulo di apache questo però non funziona perchè il modo in cui ClibPDF scrive sullo stdout non funziona con apache. Si può risolvere questo problema saltando il nome del file e utilizzando cpdf_output_buffer() per scrivere il documento pdf.
Vedere anche cpdf_close() e cpdf_output_buffer().
(PHP 3 >= 3.0.9, PHP 4, PHP 5 <= 5.0.4)
cpdf_output_buffer -- Scrive il documento pdf nel buffer di memoriaLa funzione cpdf_output_buffer() scrive il documento pdf nello stdout. Il documento deve essere creato in memoria, cosa che si verifica se cpdf_open() è richiamata senza il nome di un file come parametro. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere anche cpdf_open().
La funzione cpdf_page_init() inizia una nuova pagina con altezza height e larghezza width. Restituisce TRUE in caso di successo, FALSE in caso di fallimento. La pagina ha numero numero di pagina e orientamento orientamento. orientamento può essere 0 per l'orientamento verticale e 1 per l'orizzontale. L'ultimo parametro facoltativo unità setta le unità per il sistema di coordinate. Il valore deve essere il numero di punti postscript per unità. Dato che un pollice corrisponde a 72 punti, un valore di 72 setterà l'unità ad un pollice. Il valore di default è sempre 72.
Vedere cpdf_set_current_page().
(PHP 3 >= 3.0.9, PHP 4, PHP 5 <= 5.0.4)
cpdf_place_inline_image -- Inserisce un'immagine nella paginaLa funzione cpdf_place_inline_image() inserisce un'immagine creata con le funzioni per le immagini di PHP nella pagina alla posizione (x-coor, y-coor). L'immagine può essere ridimensionata nello stesso tempo. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Il parametro opzionale mode determina l'unità di misura. Se viene impostato a 0, oppure omesso, si utilizza come default l'unità specificata nella pagina. Altrimenti le coordinate sono misurate in punti postscript ignorando l'unità corrente.
Vedere anche cpdf_import_jpeg().
La funzione cpdf_rect() disegna un rettangolo con l'angolo in basso a sinistra nel punto (x-coor, y-coor). La larghezza è settata a larghezza. L'altezza è settata a altezza. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Il parametro opzionale mode determina l'unità di misura. Se viene impostato a 0, oppure omesso, si utilizza come default l'unità specificata nella pagina. Altrimenti le coordinate sono misurate in punti postscript ignorando l'unità corrente.
Esempio 1. Traccia un rettangolo
|
(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)
cpdf_restore -- Ristabilisce le impostazioni salvate in precedenzaLa funzione cpdf_restore() ristabilisce le impostazioni salvate con cpdf_save(). Funziona come il comando postscript grestore. Molto utile se si vuole traslare o ruotare un oggetto senza intaccare gli altri oggetti. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere anche cpdf_save().
La funzione cpdf_rlineto() disegna una linea dal punto corrente al punto con coordinate relative (x-coor, y-coor). Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Il parametro opzionale mode determina l'unità di misura. Se viene impostato a 0, oppure omesso, si utilizza come default l'unità specificata nella pagina. Altrimenti le coordinate sono misurate in punti postscript ignorando l'unità corrente.
Vedere anche: cpdf_moveto(), cpdf_rmoveto() e cpdf_curveto().
La funzione cpdf_rmoveto() setta il punto corrente alle coordinate relative x-coor e y-coor. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Il parametro opzionale mode determina l'unità di misura. Se viene impostato a 0, oppure omesso, si utilizza come default l'unità specificata nella pagina. Altrimenti le coordinate sono misurate in punti postscript ignorando l'unità corrente.
Vedere anche cpdf_moveto().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
La funzione cpdf_rotate() effettua una rotazione di angolo gradi. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
La funzione cpdf_save_to_file() salva il documento pdf in un file se è stato creato in memoria. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Questa funzione non è necessaria se il documento pdf è stato aperto specificando un nome di un file come parametro di cpdf_open().
Vedere anche: cpdf_output_buffer() e cpdf_open().
La funzione cpdf_save() salva le impostazioni correnti. Funziona come il comando postscript gsave. Molto utile se si vuole traslare o ruotare un oggetto senza intaccare gli altri oggetti. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere anche cpdf_restore().
La funzione cpdf_scale() applica il coefficiente di scala in entrambe le direzioni. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
La funzione cpdf_set_char_spacing() imposta la spaziatura fra caratteri. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere anche cpdf_set_word_spacing() e cpdf_set_leading().
(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)
cpdf_set_creator -- Imposta il campo creatore nel documento pdfLa funzione cpdf_set_creator() imposta il creatore del documento pdf. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere anche: cpdf_set_subject(), cpdf_set_title() e cpdf_set_keywords().
La funzione cpdf_set_current_page() imposta la pagina sulla quale vengono eseguite tute le operazioni. Ci si può spostare sulle pagine finchè una pagina non è chiusa con cpdf_finalize_page(). Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere anche cpdf_finalize_page().
(PHP 4 >= 4.0.6, PHP 5 <= 5.0.4)
cpdf_set_font_directories -- Imposta le directory in cui cercare quando si utilizzano font esterni
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.0.6, PHP 5 <= 5.0.4)
cpdf_set_font_map_file -- Imposta la tabella di associazione tra nome di file e nome di font, quando si usano font esterni
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)
cpdf_set_font -- Seleziona l'aspetto e la dimensione del font correnteLa funzione cpdf_set_font() imposta l'aspetto, la dimensione e la codifica del font corrente. Attualmente solo i font standard postscript sono supportati. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
L'ultimo parametro codifica può assumere i seguenti valori: "MacRomanEncoding", "MacExpertEncoding", "WinAnsiEncoding", e "NULL". "NULL" rappresenta la codifica incorporata del font.
Vedere il manuale di ClibPDF per maggiori informazioni, specialmente su come supportare font asiatici.
(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)
cpdf_set_horiz_scaling -- Imposta il fattore di scala orizzontale del testoLa funzione cpdf_set_horiz_scaling() imposta il fattore di scala orizzontale a scala percento. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)
cpdf_set_keywords -- Imposta i campi chiave del documento pdfLa funzione cpdf_set_keywords() imposta le parole chiave di un documento pdf. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere anche: cpdf_set_title(), cpdf_set_creator() e cpdf_set_subject().
La funzione cpdf_set_leading() imposta la distanza fra righe di testo. Verrà utilizzata se il testo viene scritto con cpdf_continue_text(). Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere cpdf_continue_text().
The cpdf_set_page_animation() function set the transition between following pages. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
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.
(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)
cpdf_set_subject -- Imposta il campo soggetto del documento pdfLa funzione cpdf_set_subject() imposta il soggetto del documento pdf. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere anche cpdf_set_title(), cpdf_set_creator() e cpdf_set_keywords().
La funzione cpdf_set_text_matrix() imposta una matrmatriceice che descrive una trasformazione applicata sul font corrente. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
La funzione cpdf_set_text_pos() imposta la posizione del testo per la prossima chiamata della funzione cpdf_show(). Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Il parametro opzionale mode determina l'unità di misura. Se viene impostato a 0, oppure omesso, si utilizza come default l'unità specificata nella pagina. Altrimenti le coordinate sono misurate in punti postscript ignorando l'unità corrente.
Vedere anche: cpdf_show() e cpdf_text().
The cpdf_set_text_rendering() function determines how text is rendered. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
The possible values for rendermode 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. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
La funzione cpdf_set_title() imposta il titolo di un documento pdf. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere anche: cpdf_set_subject(), cpdf_set_creator() e cpdf_set_keywords().
(PHP 3 >= 3.0.9, PHP 4, PHP 5 <= 5.0.4)
cpdf_set_viewer_preferences -- How to show the document in the viewer
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
La funzione cpdf_set_word_spacing() imposta la spaziatura fra parole. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere anche: cpdf_set_char_spacing() e 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. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
The cpdf_setflat() function set the flatness to a value between 0 and 100. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)
cpdf_setgray_fill -- Imposta il grigio come colore per il riempimentoLa funzione cpdf_setgray_fill() imposta il valore corrente di grigio come riempimento del path. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere anche cpdf_setrgbcolor_fill().
The cpdf_setgray_stroke() function sets the current drawing color to the given gray value. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also cpdf_setrgbcolor_stroke().
(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)
cpdf_setgray -- Imposta il grigio come colore per il disegno e il riempimentoLa funzione cpdf_setgray() imposta come colore per il disegno e il riempimento il valore di grigio passato. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere anche: cpdf_setrgbcolor_stroke() e 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. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
The cpdf_setlinejoin() function set the linejoin parameter between a value of 0 and 2. 0 = miter, 1 = round, 2 = bevel. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
La funzione cpdf_setlinewidth() imposta la larghezza delle linee a larghezza. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
The cpdf_setmiterlimit() function set the miter limit to a value greater or equal than 1. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)
cpdf_setrgbcolor_fill -- Sets filling color to rgb color valueThe cpdf_setrgbcolor_fill() function sets the current rgb color value to fill a path.
Nota: The values are expected to be floating point values between 0.0 and 1.0. (i.e black is (0.0, 0.0, 0.0) and white is (1.0, 1.0, 1.0)).
See also cpdf_setrgbcolor_stroke(), cpdf_setrgbcolor().
(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)
cpdf_setrgbcolor_stroke -- Sets drawing color to rgb color valueThe cpdf_setrgbcolor_stroke() function sets the current drawing color to the given rgb color value. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: The values are expected to be floating point values between 0.0 and 1.0. (i.e black is (0.0, 0.0, 0.0) and white is (1.0, 1.0, 1.0)).
See also cpdf_setrgbcolor_fill(), cpdf_setrgbcolor().
(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)
cpdf_setrgbcolor -- Imposta il valore del colore rgb come colore per il disegno e il riempimentoLa funzione cpdf_setrgbcolor() imposta il colore corrente per il disegno e il riempimento al valore del colore rgb dato. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: The values are expected to be floating point values between 0.0 and 1.0. (i.e black is (0.0, 0.0, 0.0) and white is (1.0, 1.0, 1.0)).
Vedere anche: cpdf_setrgbcolor_stroke() e cpdf_setrgbcolor_fill().
The cpdf_show_xy() function outputs the string text at position with coordinates (x-coor, y-coor). Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Il parametro opzionale mode determina l'unità di misura. Se viene impostato a 0, oppure omesso, si utilizza come default l'unità specificata nella pagina. Altrimenti le coordinate sono misurate in punti postscript ignorando l'unità corrente.
Nota: The function cpdf_show_xy() is identical to cpdf_text() without the optional parameters.
See also cpdf_text().
La funzione cpdf_show() scrive la stringa in testo alla posizione corrente. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere anche: cpdf_text(), cpdf_begin_text() e cpdf_end_text().
(PHP 3 >= 3.0.8, PHP 4, PHP 5 <= 5.0.4)
cpdf_stringwidth -- Restituisce la larghezza del testo nel font correnteLa funzione cpdf_stringwidth() restituisce la larghezza della stringa in testo. Richiede che un font sia settato in precedenza.
Vedere anche cpdf_set_font().
La funzione cpdf_stroke() disegna una linea lungo il path corrente. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere anche: cpdf_closepath() e cpdf_closepath_stroke().
La funzione cpdf_text() scrive la stringa testo alla posizione con coordinate (x-coor, y-coor). Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Il parametro opzionale mode determina l'unità di misura. Se viene impostato a 0, oppure omesso, si utilizza come default l'unità specificata nella pagina. Altrimenti le coordinate sono misurate in punti postscript ignorando l'unità corrente.
Il parametro facoltativo orientamento è la rotazione del testo in gradi.
Il parametro facoltativo allineamento determina come viene allineato il testo.
Vedere la documentazione ClibPDF per i possibili valori.
Vedere anche cpdf_show_xy().
The cpdf_translate() function set the origin of coordinate system to the point (x-coor, y-coor). Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Il parametro opzionale mode determina l'unità di misura. Se viene impostato a 0, oppure omesso, si utilizza come default l'unità specificata nella pagina. Altrimenti le coordinate sono misurate in punti postscript ignorando l'unità corrente.
COM è una tecnologia che permette il riutilizzo del codice scritto in un qualsiasi linguaggio utilizzando una convenzione standard di chiamate e nascondendo dietro a delle API i dettagli di implementazione quali la macchina su cui il Componente è conservato e il file eseguibile che lo ospita. Si può pernsare a COM com a un meccanismo avanzato di Remote Procedure Call (RPC) con alcune basi di programmazione ad oggetti. COM separa l'implementazione dall'interfaccia.
COM incoraggia il versioning, la separazione tra interfaccia e implementazione e l'occultamento dei dettagli dell'implementazione, come la posizione dell'eseguibile e il linguaggio di programmazione.
Non è necessaria nessuna installazione per usare queste funzioni, esse fanno parte del core di PHP.
La versione per Windows di PHP ha già compilato il supporto per questo modulo. Non occorre caricare alcun modulo addizionale per potere utilizzare queste funzioni.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. opzioni di configurazione Com
Nome | Default | Modificabile in | Log variazioni |
---|---|---|---|
com.allow_dcom | "0" | PHP_INI_SYSTEM | Disponibile dal PHP 4.0.5. |
com.autoregister_typelib | "0" | PHP_INI_SYSTEM | PHP_INI_SYSTEM in PHP 4. Disponibile in PHP 4.1.0. |
com.autoregister_verbose | "0" | PHP_INI_SYSTEM | PHP_INI_SYSTEM in PHP 4. Disponibile dal PHP 4.1.0. |
com.autoregister_casesensitive | "1" | PHP_INI_SYSTEM | PHP_INI_SYSTEM in PHP 4. Disponibile dal PHP 4.1.0. |
com.code_page | "" | PHP_INI_ALL | Disponibile dal PHP 5.0.0. |
com.typelib_file | "" | PHP_INI_SYSTEM | Disponibile dal PHP 4.0.5. |
Breve descrizione dei parametri di configurazione.
Quando è impostato a on, il PHP è abilitao ad operare come client D-COM (COM distribuito) e permette agli script PHP di istanziare oggetti COM su un server remoto.
Quando questo parametro è impostato a on il PHP tenta di registrare costanti dalla libreria dei tipi dell'oggetto che istanzia, se l'pggetto implementa l'interfaccia richiesta per ottenere le informazioni in oggetto. Se distinguere tra nomi dlle costanti maiuscoli e minuscoli è controllato dal parametro com.autoregister_casesensitive .
When this is turned on, any problems with loading a typelibrary during object instantiation will be reported using the PHP error mechanism. The default is off, which does not emit any indication if there was an error finding or loading the type library.
When this is turned on (the default), constants found in auto-loaded type libraries will be registered case sensitively. See com_load_typelib() for more details.
It controls the default character set code-page to use when passing strings to and from COM objects. If set to an empty string, PHP will assume that you want CP_ACP, which is the default system ANSI code page.
If the text in your scripts is encoded using a different encoding/character set by default, setting this directive will save you from having to pass the code page as a parameter to the COM class constructor. Please note that by using this directive (as with any PHP configuration directive), your PHP script becomes less portable; you should use the COM constructor parameter whenever possible.
Nota: This configuration directive was introduced with PHP 5.
When set, this should hold the path to a file that contains a list of typelibraries that should be loaded on startup. Each line of the file will be treated as the type library name and loaded as though you had called com_load_typelib(). The constants will be registered persistently, so that the library only needs to be loaded once. If a type library name ends with the string #cis or #case_insensitive, then the constants from that library will be registered case insensitively.
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Per maggiori informazioni su COM si leggano le specifiche COM o si guardi anche la documentazione di Don Box su Yet Another COM Library (YACL)
costruttore della classe COM. Parametri:
nome o class-id del componente desiderato.
nome del server DCOM dal quale deve essere richiamato il componente. Se NULL, si assume localhost. Per permettere l'uso di DCOM il parametro com.allow_dcom deve essere impostato a TRUE in php.ini.
specifica la codepage che verrà usata per convertire le stringhe di PHP in stringhe Unicode e viceversa. I valori possibili sono CP_ACP, CP_MACCP, CP_OEMCP, CP_SYMBOL, CP_THREAD_ACP, CP_UTF7 e CP_UTF8.
Esempio 1. esempio di COM (1)
|
Esempio 2. esempio di COM (2)
|
The DOTNET class allows you to instantiate a class from a .Net assembly and call its methods and access its properties.
DOTNET class constructor. assembly_name specifies which assembly should be loaded, and class_name specifices which class in that assembly to instantiate. You may optionally specify a codepage to use for unicode string transformations; see the COM class for more details on code pages.
The returned object is an overloaded object, which means that PHP does not see any fixed methods as it does with regular classes; instead, any property or method accesses are passed through to COM and from there to DOTNET. In other words, the .Net object is mapped through the COM interoperability layer provided by the .Net runtime.
Once you have created a DOTNET object, PHP treats it identically to any other COM object; all the same rules apply.
Nota: You need to install the .Net runtime on your web server to take advantage of this feature.
costruttore della classe VARIANT. Parametri:
valore iniziale. se omesso viene creato un oggetto VT_EMPTY.
specifica il tipo di contenuto dell'oggetto VARIANT. I valori possibili sono 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 e VT_VARIANT. Questi valori sono mutuallmente esclusivi, ma possono essere combinati con VT_BYREF per specificare che è un valore. Se omesso, viene usato il tipo di valore. Consultare la libreria MSDN per ulteriori informazioni.
specifica la codepage che è usata per convertire le stringhe PHP in stringhe unicode e viceversa. I valori possibili sono CP_ACP, CP_MACCP, CP_OEMCP, CP_SYMBOL, CP_THREAD_ACP, CP_UTF7 e CP_UTF8.
Generates a Globally Unique Identifier (GUID) and returns it as a string. A GUID is generated in the same way as DCE UUID's, except that the Microsoft convention is to enclose a GUID in curly braces.
See also uuid_create() in the PECL uuid extension.
Instructs COM to sink events generated by comobject into the PHP object sinkobject. PHP will attempt to use the default dispinterface type specified by the typelibrary associated with comobject, but you may override this choice by setting sinkinterface to the name of the dispinterface that you want to use.
sinkobject should be an instance of a class with methods named after those of the desired dispinterface; you may use com_print_typeinfo() to help generate a template class for this purpose.
Be careful how you use this feature; if you are doing something similar to the example below, then it doesn't really make sense to run it in a web server context.
Esempio 1. COM event sink example
|
See also com_print_typeinfo(), com_message_pump().
com_get_active_object() is similar to creating a new instance of a COM object, except that it will only return an object to your script if the object is already running. OLE applications use something known as the Running Object Table to allow well-known applications to be launched only once; this function exposes the COM library function GetActiveObject() to get a handle on a running instance.
progid must be either the ProgID or CLSID for the object that you want to access (for example Word.Application). code_page acts in precisely the same way that it does for the COM class.
If the requested object is running, it will be returned to your script just like any other COM object. Otherwise a com_exception will be raised. There are a variety of reasons why this function might fail, the most common being that the object is not already running. In that situation, the exception error code will be MK_E_UNAVAILABLE; you can use the getCode method of the exception object to check the exception code.
Avvertimento |
Using com_get_active_object() in a web server context is not always a smart idea. Most COM/OLE applications are not designed to handle more than one client concurrently, even (or especially!) Microsoft Office. You should read Considerations for Server-Side Automation of Office for more information on the general issues involved. |
Restituisce il valore della proprietà nome_prop del componente COM referenziato da oggetto_com. Restituisce FALSE in caso di errore.
com_invoke() chiama un metodo del componente COM referenziato da oggetto_com. Restituisce FALSE in caso di errore, altrimenti restituisce il valore di ritorno di nome_funzione.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
com_load() crea un nuovo componente COM e ne restituisce un riferimento. Restituisce FALSE in caso di errore. I possibili valori per codepage sono CP_ACP, CP_MACCP, CP_OEMCP, CP_SYMBOL, CP_THREAD_ACP, CP_UTF7 e CP_UTF8.
(PHP 4 >= 4.2.3, PHP 5)
com_message_pump -- Process COM messages, sleeping for up to timeoutms millisecondsThis function will sleep for up to timeoutms milliseconds, or until a message arrives in the queue. If a message or messages arrives before the timeout, they will be dispatched, and the function will return TRUE. If the timeout occurs and no messages were processed, the return value will be FALSE. If you do not specify a value for timeoutms, then 0 will be assumed. A 0 value means that no waiting will be performed; if there are messages pending they will be dispatched as before; if there are no messages pending, the function will return FALSE immediately without sleeping.
The purpose of this function is to route COM calls between apartments and handle various synchronization issues. This allows your script to wait efficiently for events to be triggered, while still handling other events or running other code in the background. You should use it in a loop, as demonstrated by the example in the com_event_sink() function, until you are finished using event bound COM objects.
(PHP 4 >= 4.2.3, PHP 5)
com_print_typeinfo -- Print out a PHP class definition for a dispatchable interfaceThe purpose of this function is to help generate a skeleton class for use as an event sink. You may also use it to generate a dump of any COM object, provided that it supports enough of the introspection interfaces, and that you know the name of the interface you want to display.
comobject should be either an instance of a COM object, or be the name of a typelibrary (which will be resolved according to the rules set out in com_load_typelib()). dispinterface is the name of an IDispatch descendant interface that you want to display. If wantsink is TRUE, the corresponding sink interface will be displayed instead.
See also com_event_sink(), com_load_typelib().
Imposta il valore della proprietà nome_prop del componente COM referenziato da oggetto_com. Restituisce il valore appena impostato in caso di successo,, FALSE altrimenti.
Returns the absolute value of val.
See also abs().
Nota: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
Adds left to right using the following rules (taken from the MSDN library), which correspond to those of Visual Basic:
Tabella 1. Variant Addition Rules
If | Then |
---|---|
Both expressions are of the string type | Concatenation |
One expression is a string type and the other a character | Addition |
One expression is numeric and the other is a string | Addition |
Both expressions are numeric | Addition |
Either expression is NULL | NULL is returned |
Both expressions are empty | Integer subtype is returned |
See also variant_sub().
Nota: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
Performs a bitwise AND operation, according to the following truth table; note that this is slightly different from a regular AND operation.
Tabella 1. Variant AND Rules
If left is | If right is | then the result is |
---|---|---|
TRUE | TRUE | TRUE |
TRUE | FALSE | FALSE |
TRUE | NULL | NULL |
FALSE | TRUE | FALSE |
FALSE | FALSE | FALSE |
FALSE | NULL | FALSE |
NULL | TRUE | NULL |
NULL | FALSE | FALSE |
NULL | NULL | NULL |
See also variant_or().
Nota: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
This function makes a copy of variant and then performs a variant cast operation to force the copy to have the type given by type. type should be one of the VT_XXX constants.
This function wraps VariantChangeType() in the COM library; consult MSDN for more information.
See also variant_set_type().
Concatenates left with right and returns the result.
See also la Sezione Operatori di stringa nel Capitolo 15 for the string concatenation operator; this function is notionally equivalent to $left . $right.
Nota: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
Compares left with right and returns one of the following values:
Tabella 1. Variant Comparision Results
value | meaning |
---|---|
VARCMP_LT | left is less than right |
VARCMP_EQ | left is equal to right |
VARCMP_GT | left is greater than right |
VARCMP_NULL | Either left, right or both are NULL |
This function will only compare scalar values, not arrays or variant records.
lcid is a valid Locale Identifier to use when comparing strings (this affects string collation). flags can be one or more of the following values OR'd together, and affects string comparisons:
Tabella 2. Variant Comparision Flags
value | meaning |
---|---|
NORM_IGNORECASE | Compare case insensitively |
NORM_IGNORENONSPACE | Ignore nonspacing characters |
NORM_IGNORESYMBOLS | Ignore symbols |
NORM_IGNOREWIDTH | Ignore string width |
NORM_IGNOREKANATYPE | Ignore Kana type |
NORM_IGNOREKASHIDA | Ignore Arabic kashida characters |
Nota: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
Converts timestamp from a unix timestamp value into a variant of type VT_DATE. This allows easier interopability between the unix-ish parts of PHP and COM.
See also variant_date_to_timestamp() for the inverse of this operation, mktime(), time().
Converts variant from a VT_DATE (or similar) value into a unix timestamp. This allows easier interopability between the unix-ish parts of PHP and COM.
See also variant_date_from_timestamp() for the inverse of this operation, date(), strftime().
Divides left by right and returns the result, subject to the following rules:
Tabella 1. Variant Division Rules
If | Then |
---|---|
Both expressions are of the string, date, character, boolean type | Double is returned |
One expression is a string type and the other a character | Division and a double is returned |
One expression is numeric and the other is a string | Division and a double is returned. |
Both expressions are numeric | Division and a double is returned |
Either expression is NULL | NULL is returned |
right is empty and left is anything but empty | A com_exception with code DISP_E_DIVBYZERO is thrown |
left is empty and right is anything but empty. | 0 as type double is returned |
Both expressions are empty | A com_exception with code DISP_E_OVERFLOW is thrown |
Nota: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
If each bit in left is equal to the corresponding bit in right then TRUE is returned, otherwise FALSE is returned.
Nota: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
If variant is negative, then the first negative integer greater than or equal to the variant is returned, otherwise returns the integer portion of the value of variant.
See also variant_int(), variant_round(), floor(), ceil(), round().
Avvertimento |
This documentation is based on the MSDN documentation; it appears that this function is either the same as variant_int(), or that there is an error in the MSDN documentation. |
Nota: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
This function returns an integer value that indicates the type of variant, which can be an instance of COM, DOTNET or VARIANT classes. The return value can be compared to one of the VT_XXX constants.
The return value for COM and DOTNET objects will usually be VT_DISPATCH; the only reason this function works for those classes is because COM and DOTNET are descendants of VARIANT.
In PHP versions prior to 5, you could obtain this information from instances of the VARIANT class ONLY, by reading a fake type property. See the VARIANT class for more information on this.
Converts left and right to integer values, and then performs integer division according the following rules:
Tabella 1. Variant Integer Division Rules
If | Then |
---|---|
Both expressions are of the string, date, character, boolean type | Division and integer is returned |
One expression is a string type and the other a character | Division |
One expression is numeric and the other is a string | Division |
Both expressions are numeric | Division |
Either expression is NULL | NULL is returned |
Both expressions are empty | A com_exception with code DISP_E_DIVBYZERO is thrown |
See also variant_div().
Nota: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
Performs a bitwise implication operation, according to the following truth table:
Tabella 1. Variant Implication Table
If left is | If right is | then the result is |
---|---|---|
TRUE | TRUE | TRUE |
TRUE | FALSE | TRUE |
TRUE | NULL | TRUE |
FALSE | TRUE | TRUE |
FALSE | FALSE | TRUE |
FALSE | NULL | TRUE |
NULL | TRUE | TRUE |
NULL | FALSE | NULL |
NULL | NULL | NULL |
Nota: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
If variant is negative, then the first negative integer greater than or equal to the variant is returned, otherwise returns the integer portion of the value of variant.
See also variant_fix(), variant_round(), floor(), ceil(), round().
Nota: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
Divides left by right and returns the remainder.
See also variant_div(), variant_idiv().
Nota: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
Multiplies left by right and returns the result, subject to the following rules:
Tabella 1. Variant Multiplication Rules
If | Then |
---|---|
Both expressions are of the string, date, character, boolean type | Multiplication |
One expression is a string type and the other a character | Multiplication |
One expression is numeric and the other is a string | Multiplication |
Both expressions are numeric | Multiplication |
Either expression is NULL | NULL is returned |
Both expressions are empty | Empty string is returned |
Boolean values are converted to -1 for FALSE and 0 for TRUE.
See also variant_div(), variant_idiv().
Nota: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
Performs logical negation of variant and returns the result.
Nota: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
Performs bitwise not negation on variant and returns the result. If variant is NULL, the result will also be NULL.
Nota: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
Performs a bitwise OR operation, according to the following truth table; note that this is slightly different from a regular OR operation.
Tabella 1. Variant OR Rules
If left is | If right is | then the result is |
---|---|---|
TRUE | TRUE | TRUE |
TRUE | FALSE | TRUE |
TRUE | NULL | TRUE |
FALSE | TRUE | TRUE |
FALSE | FALSE | FALSE |
FALSE | NULL | NULL |
NULL | TRUE | TRUE |
NULL | FALSE | NULL |
NULL | NULL | NULL |
See also variant_and(), variant_xor().
Nota: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
Returns the result of left to the power of right.
See also pow().
Nota: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
Returns the value of variant rounded to decimals decimal places.
See also round().
Nota: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
This function is similar to variant_cast() except that the variant is modified "in-place"; no new variant is created. The parameters for this function have identical meaning to those of variant_cast().
See also variant_cast().
Converts value to a variant and assigns it to the variant object; no new variant object is created, and the old value of variant is freed/released.
(PHP 5)
variant_sub -- subtracts the value of the right variant from the left variant value and returns the resultSubtracts right from left using the following rules:
Tabella 1. Variant Subtraction Rules
If | Then |
---|---|
Both expressions are of the string type | Subtraction |
One expression is a string type and the other a character | Subtraction |
One expression is numeric and the other is a string | Subtraction. |
Both expressions are numeric | Subtraction |
Either expression is NULL | NULL is returned |
Both expressions are empty | Empty string is returned |
See also variant_add().
Nota: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
Performs a logical exclusion, according to the following truth table:
Tabella 1. Variant XOR Rules
If left is | If right is | then the result is |
---|---|---|
TRUE | TRUE | FALSE |
TRUE | FALSE | TRUE |
FALSE | TRUE | TRUE |
FALSE | FALSE | FALSE |
NULL | NULL | NULL |
See also variant_and(), variant_or().
Nota: As with all the variant arithmetic functions, the parameters for this function can be either a PHP native type (integer, string, floating point, boolean or NULL), or an instance of a COM, VARIANT or DOTNET class. PHP native types will be converted to variants using the same rules as found in the constructor for the VARIANT class. COM and DOTNET objects will have the value of their default property taken and used as the variant value.
The variant arithmetic functions are wrappers around the similarly named functions in the COM library; for more information on these functions, consult the MSDN library. The PHP functions are named slightly differently; for example variant_add() in PHP corresponds to VarAdd() in the MSDN documentation.
Queste funzioni permettono di usare la libreria CrackLib per testare la 'forza' di una password. La 'forza' di una password è testata attraverso un controllo sulla lunghezza, sull'uso di maiuscole e minuscole ed un controllo attraverso lo specifico dizionario di CrackLib. CrackLib darà anche utili messaggi diagnostici che aiuteranno nel 'rafforzare' la password.
Nota: Questo modulo è stato spostato nel repository PECL e non sarà più rilascio con il PHP dalla versione 5.0.0.
Maggiori informazioni riguardo CrackLib possono essere trovate, insieme alla libreria, a http://www.crypticide.com/users/alecm/.
This PECL extension is not bundled with PHP. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: http://pecl.php.net/package/crack.
In PHP 4 this PECL extensions source can be found in the ext/ directory within the PHP source or at the PECL link above. Per potere utilizzare queste funzioni, occorre compilare il PHP con il supporto per Crack utilizzando --with-crack[=DIR] option.
Gli utenti di Windows dovranno abilitare php_crack.dll nel php.ini per potere utilizzare queste funzioni. In PHP 4 this DLL resides in the extensions/ directory within the PHP Windows binaries download. You may download this PECL extension DLL from the PHP Downloads page or at http://snaps.php.net/.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. Opzioni di configurazione per Crack
Nome | Default | Modificabile | Log modifiche |
---|---|---|---|
crack.default_dictionary | NULL | PHP_INI_SYSTEM | Disponibile da PHP 4.0.5. |
Questo esempio mostra come aprire un dizionario di CrackLib, testare una determinata password, recuperare ogni messaggio diagnostico e chiudere il dizionario.
Esempio 1. Esempio di CrackLib
|
Nota: Se crack_check() restituisce TRUE, crack_getlastmessage() restituirà 'password forte'.
Restituisce TRUE se password è forte, altrimenti FALSE.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
crack_check() effettua un controllo nascosto della password data nel dizionario specificato. Se dizionario non è specificato viene utilizzato l'ultimo dizionario aperto.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
crack_closedict() chiude l'identificatore del dizionario specificato. Se dizionario non è specificato, verrà chiuso il dizionario corrente.
(PHP 4 >= 4.0.5, PECL)
crack_getlastmessage -- Restituisce il messaggio dell'ultimo controllo nascostoAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
crack_getlastmessage() restituisce il messaggio dell'ultimo controllo nascosto.
Restituisce un identificatore di risorsa dizionario in caso di successo, o FALSE in caso di fallimento.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
crack_opendict() apre il dizionario specificato di CrackLib per usarlo con crack_check().
Nota: Può essere aperto solo un dizionario alla volta.
Vedere anche: crack_check() e crack_closedict().
Le funzioni fornite da questa estensione controllano se un carattere o una stringa rientrano in una classe di caratteri in accordo con l'ambiente corrente (vedere anche setlocale()).
Quando vengono chiamate con un numero intero come argomento queste funzioni si comportano esattamente come il loro equivalente in C presente in ctype.h.
Quando vengono chiamate con una stringa come argomento controlleranno ogni carattere della stringa e ritorneranno TRUE se ogni carattere della stringa soddisfa il criterio richiesto. Quando sono eseguite con una stringa vuota il risultato è sempre TRUE
Passare qualsiasi cosa eccetto una stringa o un numero intero restituirà immediatamenente FALSE.
A partire da PHP 4.2.0 queste funzioni sono abilitate di default. Per le versioni più vecchie bisogna configurare e compilare PHP con --enable-ctype.
La versione per Windows di PHP ha già compilato il supporto per questo modulo. Non occorre caricare alcun modulo addizionale per potere utilizzare queste funzioni.
Nota: Il supporto per CType pre-compilato è disponibile a partire dalla versione 4.3.0.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Restituisce TRUE se ogni carattere di testo è una lettera o una cifra, FALSE in caso contrario. Nell'ambiente standard del C le lettere sono solamente [A-Za-z] e la funzione è equivalente a preg_match('/^[a-z0-9]*$/i', $text).
Esempio 1. Esempio di uso di ctype_alnum() (utilizzando le impostazioni locali di default)
Questo esempio visualizzerà :
|
Vedere anche ctype_alpha(), ctype_digit() e setlocale().
Restituisce TRUE se ogni carattere di testo è una lettera dell'ambiente corrente, FALSE in caso contrario. Nell'ambiente standard del C le lettere sono solo [A-Za-z] e ctype_alpha() è equivalente a (ctype_upper($text) || ctype_lower($text)), se $text è di un singolo carattere, ma altri linguaggi hanno lettere che non sono considerate nè maiuscole nè minuscole.
Esempio 1. Esempio di uso di ctype_alpha() (utilizzando le impostazioni locali di default)
This example will output :
|
Vedere anche ctype_upper(), ctype_lower() e setlocale().
Restituisce TRUE se ogni carattere di testo ha una speciale funzione di controllo, FALSE in caso contrario. I caratteri di controllo sono per esempio line feed (avanza di una riga), tab, esc.
Esempio 1. Esempio di uso di ctype_cntrl()
L'esempio visualizzerà :
|
Restituisce TRUE se ogni carattere di testo è una cifra decimale, FALSE in caso contrario.
Esempio 1. Esempio di uso di ctype_digit()
Questo esempio visualizzerà :
|
Vedere anche ctype_alnum() e ctype_xdigit().
Restituisce TRUE se ogni carattere di testo è stampabile e crea un output realmente visibile (senza spazi bianchi), FALSE in caso contrario.
Esempio 1. Esempio di uso di ctype_graph()
Questo esempio visualizzerà :
|
Vedere anche ctype_alnum(), ctype_print() e ctype_punct().
Restituisce TRUE se ogni carattere di testo è una lettera minuscola nell'ambiente corrente.
Esempio 1. Esempio di uso di ctype_lower() (utilizzando le impostazioni locali di default)
Questo esempio visualizzerà :
|
Vedere anche ctype_alpha(), ctype_upper() e setlocale().
Restituisce TRUE se ogni carattere di testo creerà veramente un output (compresi gli spazi). Restituisce FALSE se testo contiene dei caratteri di controllo o caratteri che non hanno nessun output o che non hanno per niente una funzione di controllo.
Esempio 1. Esempio di uso di ctype_print()
Questo esempio visualizzerà :
|
Vedere anche ctype_cntrl(), ctype_graph() e ctype_punct().
(PHP 4 >= 4.0.4, PHP 5)
ctype_punct -- Controlla ogni carattere stampabile che non è uno spazio o un carattere alfanumericoRestituisce TRUE se ogni carattere di testo è stampabile, ma non è nè una lettera nè; una cifra nè uno spazio, FALSE in caso contrario.
Esempio 1. Esempio di uso di ctype_punct()
Questo esempio visualizzerà :
|
Vedere anche ctype_cntrl() e ctype_graph().
Restituisce TRUE se ogni carattere di testo crea qualche tipo di spazio, FALSE in caso contrario. Oltre allo spazio questo include anche tab, tab verticale, line feed (avanza di una riga), carriage return (a capo) e form feed (avanza di un modulo).
Esempio 1. Esempio di uso di ctype_space()
Questo esempio visualizzerà :
|
Vedere anche ctype_cntrl(), ctype_graph() e ctype_punct().
Restituisce TRUE se ogni carattere di testo è una lettera maiuscola nell'ambiente corrente.
Esempio 1. Esempio di uso di ctype_upper() (utilizzando le impostazioni locali di default)
Questo esempio visualizzerà :
|
Vedere anche ctype_alpha(), ctype_lower(), e setlocale().
(PHP 4 >= 4.0.4, PHP 5)
ctype_xdigit -- Controlla i caratteri che rappresentano una cifra esadecimaleRestituisce TRUE se ogni carattere di testo è una 'cifra' esadecimale, cioè una cifra decimale o un carattere fra [A-Fa-f] , FALSE in caso contrario.
Esempio 1. Esempio di uso di ctype_xdigit()
Questo esempio visualizzerà :
|
Vedere anche ctype_digit().
PHP supporta libcurl, una libreria creata da Daniel Stenberg, che permette di collegarsi e comunicare con parecchi tipi di server e con parecchi tipi di protocolli. Libcurl al momento supporta i protocolli http, https, ftp, gopher, telnet, dict, file, e ldap. libcurl supporta anche i certificati HTTPS, HTTP POST, HTTP PUT, l'upload via FTP (questo può essere ottenuto anche con l'estensione ftp di PHP), upload attraverso una form HTTP, proxy, cookie e autenticazione con utente e password.
Queste funzioni sono state aggiunte in PHP 4.0.2.
Per utilizzare le funzioni CURL occorre installare il pacchetto CURL. PHP richiede che si usi CURL 7.0.2-beta o successivi. PHP non funzionerà con alcuna versione di CURL antecedente alla 7.0.2-beta. Dalla versione 4.2.3 di PHP è necessario usare CURL versione 7.9.0 o successiva. Con PHP 4.3.0 occorre avere CURL 7.9.8 o successive. PHP 5.0.0 molto probabilmente richiederà CURL 7.10.5 o successiva.
Al fine di utilizzare il supporto CURL occorre anche compilare PHP con --with-curl[=DIR] dove DIR è il percorso della directory che contiene le directory lib e include. Nella directory "include" ci dovrebbe essere una cartella chiamata "curl" che dovrebbe contenere i file easy.h e curl.h. Ci dovrebbe essere un file chiamato libcurl.a nella directory "lib". A cominciare da PHP 4.3.0 si può configurare PHP all'uso di CURL per gli URL stream --with-curlwrappers.
Nota agli utenti Win32: Per abilitare questo modulo in ambiente Windows, occorre copiare libeay32.dll e ssleay32.dll dalla cartella delle DLL del pacchetto PHP/Win32 nella cartella SYSTEM32 della propria macchina Windows. (Es: C:\WINNT\SYSTEM32 o C:\WINDOWS\SYSTEM)
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Disponibile da PHP 5.1.0
Available since PHP 5.1.0
Available since PHP 5.1.0
Disponibile da PHP 5.1.0
Una volta compilato PHP con supporto CURL, si possono usare le funzioni CURL. L'idea di fondo che sta dietro le funzioni CURL è: si inizializza una sessione CURL usando curl_init(), si impostano le opzioni per il trasferimento tramite curl_setopt(), si esegue la sessione usando curl_exec() e quindi si termina la sessione con curl_close(). Qui di seguito si trova un esempio che fa uso delle funzioni CURL per scaricare la homepage del sito example.com e metterla in un file:
Questa funzione chiude una sessione CURL e libera tutte le risorse. L'handle CURL ch viene anch'esso eliminato.
Esempio 1. Inizializza una sessione CURL e scarica una pagina
|
Vedere anche: curl_init().
This function copies a cURL handle, returning a new cURL handle with the same preferences.
Esempio 1. Copying a cURL handle.
|
La funzione resituisce il numero dell'errore per l'ultima operazione cURL sulla risorsa ch, oppure 0 (zero) se non vi sono errori.
Vedere anche curl_error() e I codici di errore CURL.
(PHP 4 >= 4.0.3, PHP 5)
curl_error -- Restituisce una stringa contenente l'ultimo errore relativo alla sessione correnteLa funzione restituisce un messaggio di errore testuale per l'ultima operazione cURL eseguita sulla risorsa ch, oppure '' (una stringa vuota) se non vi sono errori.
Vedere anche curl_errno() e Codici di errore CURL.
Questa funzione deve essere chiamata dopo aver inizializzato una sessione CURL e dopo che tutte le opzioni per la sessione sono state impostate. La sua funzione è semplicemente quella di eseguire la sessione CURL predefinita (identificata dal parametro ch).
Esempio 1. Inizializza una sessione CURL e scarica una pagina web.
|
Nota: Se si desidera avere restituito il risultato anzichè averlo visualizzato direttamente sul browser, utilizzare l'opzione CURLOPT_RETURNTRANSFER di curl_setopt().
La funzione restituisce informazioni sull'ultimo trasferimento, il parametro opt può assumere uno dei seguenti valori:
"CURLINFO_EFFECTIVE_URL" - L'ultimo URL reale
"CURLINFO_HTTP_CODE" - L'ultimo codice HTTP ricevuto
"CURLINFO_FILETIME" - Data del documento remoto ricevuto, -1 indica che la data del documento è sconosciuta
"CURLINFO_TOTAL_TIME" - Tempo totale in secondi per l'ultimo trasferimento
"CURLINFO_NAMELOOKUP_TIME" - Tempo in secondi impiegato per risolvere il nome
"CURLINFO_CONNECT_TIME" - Tempo in secondi necessario per stabilire la connessione
"CURLINFO_PRETRANSFER_TIME" - Tempo in secondi dall'inizio fino a prima di cominciare il trasferimento
"CURLINFO_STARTTRANSFER_TIME" - Tempo in secondi fino a quando comincia il trasferimento del primo byte
"CURLINFO_REDIRECT_TIME" - Tempo in secondi richiesto dai passi di redirezione prima che sia cominciata la transazione finale
"CURLINFO_SIZE_UPLOAD" - Numero totale dei byte inviati
"CURLINFO_SIZE_DOWNLOAD" - Numero totale dei byte scaricati
"CURLINFO_SPEED_DOWNLOAD" - Velocità media di download
"CURLINFO_SPEED_UPLOAD" - Velocità media di upload
"CURLINFO_HEADER_SIZE" - Dimensione totale di tutte le header ricevute
"CURLINFO_REQUEST_SIZE" - Dimensione totale delle richieste, attualmente solo per le richieste HTTP
"CURLINFO_SSL_VERIFYRESULT" - Risultato delle verifiche del certificato richieste da CURLOPT_SSL_VERIFYPEER
"CURLINFO_CONTENT_LENGTH_DOWNLOAD" - Lunghezza del download ottenuta dal campo Content-Length:
"CURLINFO_CONTENT_LENGTH_UPLOAD" - Dimensione specificata dell'upload
"CURLINFO_CONTENT_TYPE" - Content-type dell'oggetto scaricato, il valore NULL indica che il server non ha inviato un Content-Type: valido
Se la funzione viene eseguita senza il parametro opzionale opt, sarà restituito un array contenente i seguenti elementi corrispondenti alle opzioni di opt:
"url"
"content_type"
"http_code"
"header_size"
"request_size"
"filetime"
"ssl_verify_result"
"redirect_count"
"total_time"
"namelookup_time"
"connect_time"
"pretransfer_time"
"size_upload"
"size_download"
"speed_download"
"speed_upload"
"download_content_length"
"upload_content_length"
"starttransfer_time"
"redirect_time"
curl_init() inizializza una nuova sessione e restituisce un handle CURL da usarsi con le funzioni curl_setopt(), curl_exec() e curl_close(). Se viene dato il parametro opzionale url, allora l'opzione CURLOPT_URL verrà impostata al valore di quel parametro. Questo si può impostare manualmente usando la funzione curl_setopt().
Esempio 1. Inizializzare una nuova sessione CURL e scaricare una pagina web
|
Vedere anche: curl_close() e curl_setopt().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Vedere anche curl_multi_init(), curl_init() e curl_multi_remove_handle().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Vedere anche curl_multi_init() e curl_close().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Vedere anche curl_multi_init() e curl_exec().
(PHP 5)
curl_multi_getcontent -- Restituisce il contenuto di un handle cURL se è impostato CURLOPT_RETURNTRANSFERAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Vedere anche curl_multi_init().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Vedere anche curl_multi_init().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Vedere anche curl_init() e curl_multi_close().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Vedere anche curl_multi_init(), curl_init() e curl_multi_add_handle().
(PHP 5)
curl_multi_select -- Restituisce tutti i socket associati alla estensione cURL che possono essere "selected"Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Vedere anche curl_multi_init().
Imposta le opzioni per una sessione CURL identificata dal parametro ch. opzione specifica quale opzione impostare e valore specifica il valore per l'opzione data.
valore dovrebbe essere di tipo booleano per i seguenti valori del parametro opzione):
Option | Set value to | Notes |
---|---|---|
CURLOPT_BINARYTRANSFER | TRUE restituisce la riga di output quando CURLOPT_RETURNTRANSFER è usata. | |
CURLOPT_CRLF | TRUE per convertire la Unix newlines in CRLF newlines per i trasferimenti. | |
CURLOPT_DNS_USE_GLOBAL_CACHE | TRUE per usare una cache gobale DNS. Questa opzione non è thread-safe ed è abilitata per default. | |
CURLOPT_FAILONERROR | TRUE per terminare in maniera silenziosa se il codice HTTP restituito è maggiore di 300. Il comportamento di default è di restituire la pagina normalmente, ignorando il codice. | |
CURLOPT_FILETIME | TRUE per cercare di recuperare la data di modifica del documento remoto. Si può cercare di ripristinare questo valore usando l'opzione CURLINFO_FILETIME con curl_getinfo(). | |
CURLOPT_FOLLOWLOCATION | TRUE per seguire una qualunque "Location: " intestazione inviata dal server come parte dell' header HTTP (notare che è ricorsiva, PHP seguirà come molte "Location: " intestazioni inviate, a meno che CURLOPT_MAXREDIRS sia impostata). | |
CURLOPT_FORBID_REUSE | TRUE forza la chiusura esplicita della connessione quando ha finito il processo e non può essere riutilizzata. | |
CURLOPT_FRESH_CONNECT | TRUE forza l'uso di una nuova connessione invece di usarne una in cache. | |
CURLOPT_FTP_USE_EPRT | TRUE per usare EPRT (e LPRT) quando si opera un download FTP. Usa FALSE per disaibilitare EPRT e LPRT e usare PORT solamente. | |
CURLOPT_FTP_USE_EPSV | TRUE prima cerca un comando EPSV per trasferimento FTP prima di ritornare alla modalità PASV. Imposta a FALSE per disabilitare EPSV. | |
CURLOPT_FTPAPPEND | TRUE per accodare aò file remoto invece di sovrascriverlo. | |
CURLOPT_FTPASCII | Un alias di CURLOPT_TRANSFERTEXT. Usarlo al suo posto. | |
CURLOPT_FTPLISTONLY | TRUE per elencare solamente i nomi di una directory FTP. | |
CURLOPT_HEADER | TRUE per includere l'intestazione in output. | |
CURLOPT_HTTPGET | TRUE per resettare la richiesta HTTP col metodo GET. Dopo che GET è il default, diventa necessario solo se il metodo di richiesta è cambiato. | |
CURLOPT_HTTPPROXYTUNNEL | TRUE per passare attraverso un proxy HTTP fornito. | |
CURLOPT_MUTE | TRUE per essere totalemtne silenzioso nei riguardi di una funzione CURL. | |
CURLOPT_NETRC | TRUE per condurre il file ~/.netrc a trovare username e password per il sito remoto col quale si stabilisce una connessione. | |
CURLOPT_NOBODY | TRUE esclude il corpo dall'output. | |
CURLOPT_NOPROGRESS |
TRUE per disabilitare il progress meter per trasferimetni CURL.
| |
CURLOPT_NOSIGNAL | TRUE per ignorare qualunque funzione CURL che causa l'invio di un segnale a un processo PHP. Ciò è settato come default con le multi-threaded SAPI in modo che le opzioni di timeout possano essere ancora usate. | Aggiunto in CURL 7.10. |
CURLOPT_POST | TRUE per compiere un regolare HTTP POST. Questo POST è il tipo normale di application/x-www-form-urlencoded, più comunemente usata dai form HTML. | |
CURLOPT_PUT | TRUE per HTTP PUT un file. Il file da PUT deve essere impostato con CURLOPT_INFILE e CURLOPT_INFILESIZE. | |
CURLOPT_RETURNTRANSFER | TRUE per restituire il trasferimento come una stringa del valore restituito di curl_exec() al posto di metterlo in output direttamente. | |
CURLOPT_SSL_VERIFYPEER | FALSE per fermare CURL dal verificare i certificati dei peer. Un certificato alternativo di verificare può essere specificato con l'opzione CURLOPT_CAINFO o una directory certificata può essere specificata con l'opzione CURLOPT_CAPATH . CURLOPT_SSL_VERIFYHOST può anche dover essere messa TRUE o FALSE se CURLOPT_SSL_VERIFYPEER è disabilitata (il default è 2). | TRUE per default nel CURL 7.10. Default bundle installed as of CURL 7.10. |
CURLOPT_TRANSFERTEXT | TRUE per usare la modalità ASCII per trasferimenti FTP. Per LDAP, riporta i dati in testo iano invece che in HTML. Sui sistemi Windows, non imposterà STDOUT alla modalità binaria. | |
CURLOPT_UNRESTRICTED_AUTH | TRUE invia username e password quando le seguenti locazioni (che usano CURLOPT_FOLLOWLOCATION), anche quando l'hostname è cambiato. | |
CURLOPT_UPLOAD | TRUE per preparare un upload. | |
CURLOPT_VERBOSE | TRUE per inviare un'informazione di tipo verbose. Scrive l'output su STDERR, o sul file specificato usando CURLOPT_STDERR. |
value dovrebbe essere un intero per i seguenti valori del parametro option :
Option | Set value to | Notes |
---|---|---|
CURLOPT_BUFFERSIZE | La dimensione del buffer da utilizzare per ogni lettura. Non è garantito che questa richiesta venga soddisfatta, comunque. | Aggiunto in CURL 7.10. |
CURLOPT_CLOSEPOLICY | Anche CURLCLOSEPOLICY_LEAST_RECENTLY_USED or CURLCLOSEPOLICY_OLDEST. Ci sono altri tre CURLCLOSEPOLICY_ costanti, ma CURL non li supporta ancora. | |
CURLOPT_CONNECTTIMEOUT | Il numero di secondi da aspettare mentre si cerca di connettersi. Usare 0 per aspettare indefinitamente. | |
CURLOPT_DNS_CACHE_TIMEOUT | Il numero di secondi con cui mantenere le istanze DNS in memoria. Questa opzio è posta a 120 (2 minuti) per default. | |
CURLOPT_FTPSSLAUTH | Il metodo di autenticazione FTP (quando attivato): CURLFTPAUTH_SSL (cerca per primo SSL), CURLFTPAUTH_TLS (cerca per primo SSL), o CURLFTPAUTH_DEFAULT (lascia decidere a CURL). | Aggiunto in CURL 7.12.2 e disponibile da PHP 5.1.0 |
CURLOPT_HTTP_VERSION | CURL_HTTP_VERSION_NONE (default, lascia decidere CURL quale versione usare), CURL_HTTP_VERSION_1_0 (forza HTTP/1.0), o CURL_HTTP_VERSION_1_1 (forza HTTP/1.1). | |
CURLOPT_HTTPAUTH |
Il metodo(i) di autenticazione HTTP da usare. Le opzioni sono: CURLAUTH_BASIC, CURLAUTH_DIGEST, CURLAUTH_GSSNEGOTIATE, CURLAUTH_NTLM, CURLAUTH_ANY, e CURLAUTH_ANYSAFE. Si può usre l'operatore binario | (or) per combinare più di un metodo. In questo caso, CURL testerà il server per vedere quali metodi esso supporta e sceglierà il migliore. CURLAUTH_ANY è un alias per CURLAUTH_BASIC | CURLAUTH_DIGEST | CURLAUTH_GSSNEGOTIATE | CURLAUTH_NTLM. CURLAUTH_ANYSAFE è un alias per CURLAUTH_DIGEST | CURLAUTH_GSSNEGOTIATE | CURLAUTH_NTLM. | |
CURLOPT_INFILESIZE | La grandezza attesa, in bytes, del file quando si invia (upload) un file a un sito remoto. | |
CURLOPT_LOW_SPEED_LIMIT | La velocità di trasferimento, in bytes al secondo, in cui la trasmissione dovrebbe stare al di sotto durante CURLOPT_LOW_SPEED_TIME secondi affinchè PHP to consideri la trasmissione troppo lenta e la abortisca. | |
CURLOPT_LOW_SPEED_TIME | Il numero di secondi in cui il trasferimento dovrebbe stare al di sotto CURLOPT_LOW_SPEED_LIMIT in modo che PHP consideri la rasmisiosne troppo lenta e la abortisca. | |
CURLOPT_MAXCONNECTS | L'ammontare massimo di connessioni persistenti consentite. Quando il limite è raggiunto, CURLOPT_CLOSEPOLICY viene usata per determinare quale connessione chiudere. | |
CURLOPT_MAXREDIRS | L'ammontare massimo di redirezioni HTTP da seguire. Usare questa opzione insieme a CURLOPT_FOLLOWLOCATION. | |
CURLOPT_PORT | Un numero di porta alternativo a cui connettersi. | |
CURLOPT_PROXYAUTH | Il metodo di autenticazione HTTP da usare per la connessione al proxy. Usare la stessa bitmask come descritto in in CURLOPT_HTTPAUTH. Per l'autenticazione del proxy, solo CURLAUTH_BASIC e CURLAUTH_NTLM sono attualmente supportate. | Aggiunto in CURL 7.10.7 e PHP 5.1.0. |
CURLOPT_PROXYPORT | Il numero di porta del proxy alla quale connettersi. Questo numero può essere anche impostato in CURLOPT_PROXY. | |
CURLOPT_PROXYTYPE | Anche CURLPROXY_HTTP (default) o CURLPROXY_SOCKS5. | Aggiunto in CURL 7.10. |
CURLOPT_RESUME_FROM | L' offset, in byte, per ripristinare un trasferimento. | |
CURLOPT_SSL_VERIFYHOST | 1 per verificare l'esistenza di un nome comune nel certificato SSL peer . 2 per verificare l'esistenza di un nome comune e verificare inoltre che soddisfi l'hostname fornito. | |
CURLOPT_SSLVERSION | La versione SSL (2 or 3) da usare. Per default PHP cercherà di determinare ciò da se stesso, benchè in alcuni casi si possa impostarlo manualmente. | |
CURLOPT_TIMECONDITION | Come CURLOPT_TIMEVALUE è trattato. Usare CURL_TIMECOND_IFMODSINCE per restituire la pagina solo se è stata mpdificata dalla data specificata in CURLOPT_TIMEVALUE. Se non è stata modificata, un "304 Not Modified" header sarà restituito assumendo che CURLOPT_HEADER è TRUE. Usare CURL_TIMECOND_ISUNMODSINCE per l'effetto opposto. CURL_TIMECOND_IFMODSINCE è il default. | Aggiunto in PHP 5.1.0. |
CURLOPT_TIMEOUT | Il numero massimo di secondi per permettere alle funzioni CURL di essere eseguite. | |
CURLOPT_TIMEVALUE | Il tempo in secondi dal 1 Gennaio 1970. Il tempo verrà usato da CURLOPT_TIMECONDITION. Per default, CURL_TIMECOND_IFMODSINCE è usato. |
value dovrebbe essere una stringa per i seguenti valori del parametro option :
Option | Set value to | Notes |
---|---|---|
CURLOPT_CAINFO | Il nome di un file contenente uno o più certificati che verificano la parità. Ciò ha significato solo quando usato in combinazione con CURLOPT_SSL_VERIFYPEER. | |
CURLOPT_CAPATH | Una directory che contiene certificati multipli CA. Usare questa opzione insieme a CURLOPT_SSL_VERIFYPEER. | |
CURLOPT_COOKIE | The contents of the "Set-Cookie: " header to be used in the HTTP request. | |
CURLOPT_COOKIEFILE | Il nome del file che contiene i dati del cookie. Il cookie può essere nel formato Netscape, o solo un semplice header HTTP-style allegato in un file. | |
CURLOPT_COOKIEJAR | Il nome di un file in cui salvare tutti i cookie interni finchè la connessione termina. | |
CURLOPT_CUSTOMREQUEST |
Un metodo custom di richiesta da usare al posto di
"GET" o "HEAD" quando avviene una
richiesta HTTP. Ciò è utile per un
"DELETE" o altro, in più nasconde le richieste HTTP.
Valori validi sono termini quali "GET",
"POST", "CONNECT" e così via;
i.e. Non inserire un'intera riga di richieste HTTP qui. Ad esempio,
scrivere "GET /index.html HTTP/1.0\r\n\r\n"
sarebbe errato.
| |
CURLOPT_EGBSOCKET | Come CURLOPT_RANDOM_FILE, ecetto un filename per un Entropy Gathering Daemon socket. | |
CURLOPT_ENCODING | I contenuti di un' "Accept-Encoding: " header. Ciò abilita la decodifica della risposta. Termini supportati sono "identity", "deflate", e "gzip". Se viene impostata una stringa vuota, "", viene inviato un header contenente tutti i tipi di termini supportati. | |
CURLOPT_FTPPORT | Il valore che verrà utilizzato per ottenere un indirizzo IP da usare per l'istruzione FTP "POST" . L'istruzione "POST" indica al server remoto il proprio indirizzo IP a cui connettersi. La stringa può essere un semplice indirizzo IP, un hostname, un nome di un'interfaccia di rete (sotto Unix), o un semplice '-' per usare l'indirizzo Ip del sistema di default. | |
CURLOPT_INTERFACE | Il nome di un'interfaccia di rete di uscita da usare. Può essere il nome di un'interfaccia, un indirizzo IP o un host name. | |
CURLOPT_KRB4LEVEL | Il livello di sicurezza KRB4 (Kerberos 4). Uno qualunque dei valori seguenti (in ordine dal meno al più significativo) sono validi: "clear", "safe", "confidential", "private".. Se la stringa non corrisponde a uno di questi, si usa "private". Impostando questa opzione a NULL disabilita la sicurezza KRB4. Attualmente la sicurezza KRB4 lavora solamente con transazioni FTP. | |
CURLOPT_POSTFIELDS | I dati completi da mandare in post in un'operazione HTTP "POST" . | |
CURLOPT_PROXY | Il proxy HTTP in cui veicolare le richieste. | |
CURLOPT_PROXYUSERPWD | Username e password formattate come "[username]:[password]" da usare per la connessione al proxy. | |
CURLOPT_RANDOM_FILE | IL nome del file da passare al generatore di numeri casuali per SSL. | |
CURLOPT_RANGE | Intervallo(i) di dati da ricevere nel formato "X-Y" dove X o Y sono opzionali. I trasferimenti HTTP supportano inoltre svariati intervalli, separati da virgole nel formato "X-Y,N-M". | |
CURLOPT_REFERER | Il contenuto dell'header "Referer: " da usare in una richiesta HTTP. | |
CURLOPT_SSL_CIPHER_LIST | Elenco di cifre da usare con SSL. Per esempio, RC4-SHA e TLSv1 sono elenchi validi di cifre. | |
CURLOPT_SSLCERT | Il nome di un file contenente un certificato PEM formattato. | |
CURLOPT_SSLCERTPASSWD | La password richiesta per usare il CURLOPT_SSLCERT certificato. | |
CURLOPT_SSLCERTTYPE | Il formato del certificato. Formati ammessi sono "PEM" (default), "DER", e "ENG". | Aggiunto in CURL 7.9.3. |
CURLOPT_SSLENGINE | L' identificatore per il cripto-motore della chiave privata SSL specificata in CURLOPT_SSLKEY. | |
CURLOPT_SSLENGINE_DEFAULT | L' identificatore per il motore crypto usato per cripto-operazioni asimmetriche. | |
CURLOPT_SSLKEY | Il nome di un file contenente una chiave privata SSL. | |
CURLOPT_SSLKEYPASSWD |
La password segreta necessaria per usare la chiave privata SSL specificata in
CURLOPT_SSLKEY.
| |
CURLOPT_SSLKEYTYPE | Il tipo di chiave della chiave privata SSL specificata in CURLOPT_SSLKEY. I tipi di chiavi supportate sono "PEM" (default), "DER", e "ENG". | |
CURLOPT_URL | L' URL da raggiungere. E' possibnile impostarla quando si inizializza una sessione con curl_init(). | |
CURLOPT_USERAGENT | I contenuti dell'header "User-Agent: " da usare in una richiesta HTTP. | |
CURLOPT_USERPWD | Username e password formattate come "[username]:[password]" da usare per la connessione. |
value dovrebbe essere un array per i seguenti valori del parametro option :
Option | Set value to | Notes |
---|---|---|
CURLOPT_HTTP200ALIASES | Un array di 200 risposte HTTP che saranno trattate come risposte valide e non come errori. | Aggiunto in CURL 7.10.3. |
CURLOPT_HTTPHEADER | Un array di campi di header HTTP da impostare. | |
CURLOPT_POSTQUOTE | Un array di comandi FTP da eseguire sul server dopo che la richiesta FTP è stata eseguita. | |
CURLOPT_QUOTE | Un array di comandi FTP commands da eseguire sul server prima della richiesta FTP. |
value dovrebbe essere una risorsa di streaming (usando fopen(), per esempio) per i seguenti valori del parametro option :
Option | Set value to | Notes |
---|---|---|
CURLOPT_FILE | Il file che il trasferimento dovrebbe scrivere. Il default è STDOUT (la finestra del browser). | |
CURLOPT_INFILE | Il file ce il trasferimento dovrebbe leggere quando si fa un upload. | |
CURLOPT_STDERR | Una locazione alternativa per gli errori di output al posto di STDERR. | |
CURLOPT_WRITEHEADER | Il file su cui viene scritto l' header parte del trasferimento. |
value dovrebbe essere una stringa col nome di una funzione di callback valida per i seguenti valori del parametro option :
Option | Set value to | Notes |
---|---|---|
CURLOPT_HEADERFUNCTION | Il nome della funzione di callback la quale prende due parametri. il primo è la risorsa CURL, il secondo è una stringa con i dati dell'header da scrivere. Usando questa funzione di callback, diventa propria la responsabilità di scrivere i dati di header. Restituisce il numero di bytes scritti. | |
CURLOPT_PASSWDFUNCTION | Il nome della funzione di callback che prende tre parametri. Il primo è la risorsa CURL, il secondo è una stringa contenente la richiesta di password e il terzo è la lunghezza massima della password. Restituisce la stringa che contiene la password. | |
CURLOPT_READFUNCTION | Il nome della funzione di callback che prende due parametri. Il primo è la risorsa CURL, e il secondo è una stringa con i dati da leggere. Usindo questa funzione di callback, diventa propria la responsabilità di leggere i dati. Restituisce il numero di bytes letti. Restituisce 0 per un segnale di EOF. | |
CURLOPT_WRITEFUNCTION | Il nome della funzione di callback che prende due parametri. Il primo è la risorsa CURL, e il secondo è una stringa con i dati da scrivere. Usindo questa funzione di callback, diventa propria la responsabilità di scrivere i dati. Deve restituire l'esatto numero di bytes scritti altrimenti fallisce. |
Esempio 1. Inizializza una sessione CURL nuova e carica una pagina web
|
Queste funzione sono disponibili solo se l'interprete è stato compilato con l'opzione --with-cybercash=[DIR].
A partire da PHP 4.3.0 questo modulo è stato spostato, ed ora è reperibile in PECL.
Se si hanno dubbi sullo stato di CyberCash vedere CyberCash Faq In breve, CyberCash è stato acquisito da VeriSign e, sebbene il servizio CyberCash continui ad esistere, VeriSign incoraggia gli utenti a spostarsi. Vedere la faq precedente e PECL per dettagli.
La funzione restituisce un array associativo con gli elementi "errcode" e, se "errcode" è FALSE, "outbuff" (stringa), "outLth" (long) and "macbuff" (stringa).
Questa estensione vi permette di processare le transazioni delle carte di credito usando il sistema Crédit Mutuel CyberMUT (http://www.creditmutuel.fr/centre_commercial/vendez_sur_internet.html).
CynerMUT, in Francia, è un popolare servizio di pagamento tramite web, fornito dalla banca Crédit Mutuel. Se siete stranieri in Francia, queste funzioni non saranno utili.
Queste funzioni sono disponibili se PHP è stato compilato con l'opzione --with-cybermut[=DIR], dove DIR è la locazione di libcm-mac.a e cm-mac.h. Verrà richiesto l'appropriato SDK per la piattaforma, che sarà spedito dopo la sottoscrizione al servizio CyberMUT (contattateli via Web, o recatevi presso il più vicino Crédit Mutuel).
L'uso di queste funzioni è abbastanza simile alle funzioni originali, ad eccezione dei parametri restituiti da cybermut_creerformulairecm() e cybermut_creerreponsecm(), che sono restituiti direttamente dalle funzioni PHP, mentre loro sono passati in riferimento nelle funzioni originali.
Queste funzioni sono state aggiunte in PHP 4.0.6.
Nota: Queste funzioni forniscono solo un link all'SDK di CyberMUT. Assicuratevi di leggere la Guida per gli Sviluppatori del CyberMUT per i dettagli completi dei parametri richiesti.
(4.0.5 - 4.2.3 only, PECL)
cybermut_creerformulairecm -- Genera un form HTML per la richiesta di pagamentocybermut_creerformulairecm() è usato per generare il form HTML per la richiesta di pagamento.
Esempio 1. Primo passo di pagamento (equiv cgi1.c)
|
Vedere anche cybermut_testmac() e cybermut_creerreponsecm().
(4.0.5 - 4.2.3 only, PECL)
cybermut_creerreponsecm -- Genera la conferma della consegna della conferma di pagamentocybermut_creerreponsecm() restituisce una stringa contenente un messaggio di conferma di consegna.
Il parametro è "OK" se il messaggio di conferma del pagamento è stato correttamente autenticato da cybermut_testmac(). Ogni altra catena è considerata come un messaggio di errore.
Vedere anche cybermut_creerformulairecm() e cybermut_testmac().
(4.0.5 - 4.2.3 only, PECL)
cybermut_testmac -- Assicura che non siano contenuti dati manipolati nel messaggio di conferma ricevutocybermut_testmac() è usato per assicurare che non siano contenuti dati manipolati nel messaggio di conferma ricevuto. Prestate attenzione ai parametri code-retour e texte-libre, che non possono essere valutati tal quali, a causa del trattino. Dovete recuperarli usando:
<?php $code_retour=$HTTP_GET_VARS["code-retour"]; $texte_libre=$HTTP_GET_VARS["texte-libre"]; ?> |
Esempio 1. Ultimo passaggio del pagamento (equiv cgi2.c)
|
Vedere anche cybermut_creerformulairecm() e cybermut_creerreponsecm().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Nota: Questo modulo non è disponibile su piattaforme Windows.
Questo modulo è disponibile soltanto se PHP è stato configurato con l'opzione --with-cyrus .
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Queste funzioni ti permettono di scaricare la data e l'orario dal server dove gira il PHP. Puoi usare queste funzioni per formattare l'output delle date e degli orari in diversi modi.
Nota: Ricordati che queste funzioni dipendono dai settaggi locali del tuo server. Considera specialmente l'ora legale e gli anni bisestili.
Non è necessaria nessuna installazione per usare queste funzioni, esse fanno parte del core di PHP.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Restituisce TRUE se la data inserita è valida; altrimenti restituisce FALSE. Controlla la validità di una data formata dagli argomenti. Una data è considerata valida se:
anno è compreso tra 1 e 32767
mese è compreso tra 1 e 12
Giorno è compreso tra il numero dei giorni possibile per il mese dato. Gli anno(i) bisestili sono presi in considerazione.
Guarda anche mktime() e strtotime().
(PHP 5 >= 5.1.0RC1)
date_default_timezone_get -- Gets the default timezone used by all date/time functions in a scriptThis functions returns the default timezone, using the following "guess" order:
The timezone set using the date_default_timezone_set() function (if any)
The TZ environment variable (if non empty)
The date.timezone ini option (if set)
"magical" guess (if the operating system supports it)
If none of the above options succeeds, return UTC
(PHP 5 >= 5.1.0RC1)
date_default_timezone_set -- Sets the default timezone used by all date/time functions in a scriptdate_default_timezone_set() sets the default timezone used by all date/time functions.
Nota: Since PHP 5.1.0 (when the date/time functions were rewritten), every call to a date/time function will generate a E_NOTICE if the timezone isn't valid, and/or a E_STRICT message if using the system settings or the TZ environment variable.
The timezone identifier, like UTC or Europe/Lisbon. The list of valid identifiers is available in the Appendice H.
date_sunrise() returns the sunrise time for a given day (specified as a timestamp) and location. The latitude, longitude and zenith parameters default to the date.default_latitude, date.default_longitude and date.sunrise_zenith configuration options, respectively.
The latitude defaults to North. So, if you want to specify a South value, you must pass a negative value. The same note applies to longitude, which defaults to East.
The gmt_offset parameter is specified in hours.
Tabella 1. format constants
constant | description | example |
---|---|---|
SUNFUNCS_RET_STRING | returns the result as string | 16:46 |
SUNFUNCS_RET_DOUBLE | returns the result as float | 16.78243132 |
SUNFUNCS_RET_TIMESTAMP | returns the result as integer (timestamp) | 1095034606 |
Esempio 1. date_sunrise() example
Il precedente esempio visualizzerà qualcosa simile a:
|
See also date_sunset().
date_sunset() returns the sunset time for a given day (specified as a timestamp) and location. The latitude, longitude and zenith parameters default to the date.default_latitude, date.default_longitude and date.sunset_zenith configuration options, respectively.
The latitude defaults to North. So, if you want to specify a South value, you must pass a negative value. The same note applies to longitude, which defaults to East.
The gmt_offset parameter is specified in hours.
Tabella 1. format constants
constant | description | example |
---|---|---|
SUNFUNCS_RET_STRING | returns the result as string | 16:46 |
SUNFUNCS_RET_DOUBLE | returns the result as float | 16.78243132 |
SUNFUNCS_RET_TIMESTAMP | returns the result as integer (timestamp) | 1095034606 |
Esempio 1. date_sunset() example
Il precedente esempio visualizzerà qualcosa simile a:
|
See also date_sunrise().
Restituisce una stringa formattata in accordo con il formato della stringa usato nell' intero timestamp o nell'attuale orario locale se timestamp non è assegnato.
Nota: Il valido intervallo del timestamp è abitualmente da Fri, 13 Dec 1901 20:45:54 GMT a Tue, 19 Jan 2038 03:14:07 GMT. (Queste date corrispondono al valore minimo e al massimo per un intero segnato a 32-bit.)
Per generare un timestamp da una stringa rappresentante la data, devi sapere usare strtotime(). In aggiunta, dei databases hanno funzioni che convertono i loro formati di data in timestamps (come la funzione di MySQL, UNIX_TIMESTAMP).
I seguenti caratteri sono utilizzati nella stringa formato:
a - "am" o "pm"
A - "AM" o "PM"
B - Swatch Internet time
d - giorno del mese, 2 cifre senza tralasciare gli zero; i.e. "01" a "31"
D - giorno della settimana, testuale, 3 lettere; i.e. "Fri"
F - mese, testuale, long; i.e. "January"
g - ora, formato a 12-ore senza eventuali zero; i.e. "1" a "12"
G - ora, formato a 24-ore senza eventuali zero; i.e. "0" a "23"
h - ora, formato a 12-ore; i.e. "01" a "12"
H - ora, formato a 24-ore; i.e. "00" a "23"
i - minuti; i.e. "00" a "59"
I (i grande) - "1" se c'è l'ora legale, "0" altrimenti.
j - giorno del mese senza eventuali zero; i.e. "1" a "31"
l ('L' piccola) - giorno della settimana, testuale, long; i.e. "Friday"
L - valore booleano per stabilire se è un anno bisestile; i.e. "0" o "1"
m - mese; i.e. "01" a "12"
M - mese, testuale, 3 lettere; i.e. "Jan"
n - mese senza eventuali zero; i.e. "1" a "12"
O - Differenza in ore dal fuso orario Greenwich; i.e. "+0200"
r - Data formattata RFC 822; i.e. "Thu, 21 Dec 2000 16:01:07 +0200" (aggiunto nel PHP 4.0.4)
s - secondi; i.e. "00" a "59"
S - Suffisso ordinale Inglese per i giorni del mese, 2 caratteri; i.e. "th", "nd"
t - numero di giorni del mese dato; i.e. "28" a "31"
T - Fuso orario di questo computer; i.e. "MDT"
U - secondi dall'epoca since the epoch
w - giorno della settimana, numerico, i.e. "0" (Domenica) a "6" (Sabato)
W - ISO-8601 Numero della settimana dell'anno, le settimane iniziano il lunedì (aggiunto in PHP 4.1.0) (Sabato)
Y - anno, 4 cifre; i.e. "1999"
y - anno, 2 cifre; i.e. "99"
z - giorno dell'anno; i.e. "0" a "365"
Z - Fuso orario in secondi (i.e. "-43200" a "43200"). Il fuso orario ad ovest dell'UTC è sempre negativo, e per quelli ad est è sempre positivo.
Puoi utilizzare un carattere utilizzabile nella stringa del formato come carattere normale facendolo semplicemente precedere dal carattere di escape, il backslash. Se il carattere con un backslash è ancora una sequenza speciale, devi inserire di nuovo il carattere di escape per il backslash.
È possibile usare date() e mktime() assieme per cercare delle date nel futuro o nel passato.
Esempio 3. Esempio di date() e mktime()
|
Nota: Questo può essere più affidabile della semplice addizione e sottrazione del numero di secondi in un giorno o mese a un timestamp a causa del daylight savings time.
Alcuni esempi della formattazione di date(). Nota che puoi scrivere qualsiasi altro carattere senza escape, il quale attualmente non dovrebbe produrre risultati indesiderati, ma altri caratteri potrebbero essere assegnati come caratteri della stringa di formattazione nelle prossime versioni del PHP. Quando si utilizza il carattere di escape, assicurati di usare un singolo apice per prevenire che caratteri come \n facciano iniziare una nuova linea.
Esempio 4. Formattazione con date()
|
Per formattare le date in lingue diverse dall'inglese, dovresti usare le funzioni setlocale() e strftime().
Guarda anche getlastmod(), gmdate(), mktime(), strftime() e time().
Restituisce un array associativo contenente le informazioni sulla data del timestamp, o dell'attuale orario locale se non è stato assegnato timestamp, con i seguenti elementi di array:
"seconds" - secondi
"minutes" - minuti
"hours" - ore
"mday" - giorno del mese
"wday" - giorno della settimana, numerico : da 0 come Domenica a 6 come Sabato
"mon" - mese, numerico
"year" - anno, numerico
"yday" - giorno dell'anno, numerico; i.e. "299"
"weekday" - giorno della settimana, testuale, per intero; i.e. "Friday"
"month" - mese, testuale, per intero; i.e. "January"
Questa è un'interfaccia di gettimeofday(2). Restituisce un array associativo contenente i dati restituiti dalla chiamata al sistema.
"sec" - secondi
"usec" - microsecondi
"minuteswest" - minuti ovest di Greenwich
"dsttime" - tipo di correzione dell'ora legale
Identica alla funzione date() eccetto per il fatto che l'orario restituito è del Greenwich Mean Time (GMT). Per esempio, quando si è in Finlandia (GMT +0200), la prima linea sotto scrive "Jan 01 1998 00:00:00", mentre la seconda scrive "Dec 31 1997 22:00:00".
Guarda anche date(), mktime(), gmmktime() e strftime().
Identica alla funzione mktime() eccetto per il paramentro passato, che rappresenta una data GMT.
(PHP 3 >= 3.0.12, PHP 4, PHP 5)
gmstrftime -- Formatta una data/ora GMT/UTC secondo i parametri localiSi comporta allo stesso modo della funzione strftime() eccetto che l'orario restituito è del Greenwich Mean Time (GMT). Ad esempio, quando si è nell' Eastern Standard Time (GMT -0500), la prima linea sotto scrive "Dec 31 1998 20:00:00", mentre la seconda scrive "Jan 01 1999 01:00:00".
Guarda anche strftime().
Returns a number formatted according to the given format string using the given integer timestamp or the current local time if no timestamp is given. In other words, timestamp is optional and defaults to the value of time().
Unlike the function date(), idate() accepts just one char in the format parameter.
Tabella 1. The following characters are recognized in the format parameter string
format character | Description |
---|---|
B | Swatch Beat/Internet Time |
d | Day of the month |
h | Hour (12 hour format) |
H | Hour (24 hour format) |
i | Minutes |
I | returns 1 if DST is activated, 0 otherwise |
L | returns 1 for leap year, 0 otherwise |
m | Month number |
s | Seconds |
t | Days in current month |
U | Seconds since the Unix Epoch - January 1 1970 00:00:00 GMT - this is the same as time() |
w | Day of the week (0 on Sunday) |
W | ISO-8601 week number of year, weeks starting on Monday |
y | Year (1 or 2 digits - check note below) |
Y | Year (4 digits) |
z | Day of the year |
Z | Timezone offset in seconds |
Nota: As idate() returns always an integer and as they can't start with a "0", idate() may return less digits then you would expect. See the example below:
La funzione localtime() restituisce un array identico a quello della struttura della chimata della funzione di C. Il primo argomento per localtime() è il timestamp, se non esiste viene assegnato di default l'orario attuale. Il secondo argomento di localtime() è is_associative, se questo è settato a 0 o non sostituito l'array restituirà un regolare array numerico indicizzato. Se l'argomento è settato a 1, localtime() è un array associativo contenente tutti gli elementi differenti della struttura restituita dalla funzione chiamata localtime di C. Il nome delle differenti chiavi dell'array associativo sono le seguenti:
"tm_sec" - secondi
"tm_min" - minuti
"tm_hour" - ora
"tm_mday" - giorno del mese
"tm_mon" - mese dell'anno, iniziando con 0 per Gennaio
"tm_year" - Anni dal 1900
"tm_wday" - Giorno della settimana
"tm_yday" - Giorno dell'anno
"tm_isdst" - Se l'ora legale è effettiva
Restituisce la stringa "msec sec" dove sec è l'attuale orario misurato nel numero di secondi dalla Unix Epoch (0:00:00 January 1, 1970 GMT), e msec è la parte in microsecondi. Questa funzione è disponibile solo su sistemi operativi che supportano la chiamata di sistema gettimeofday().
Entrambi le parti della stringa sono restituite in unità di secondi.
Esempio 1. Esempio di microtime()
|
Vedere anche time().
Attenzione: Nota lo strano ordine degli argomenti, che differiscono dal normale ordine degli argomenti in una normale chiamata UNIX mktime() e che non si presta bene a far comparire i parametri da destra a sinistra (guarda sotto). E' un comune errore la confusione di questi argomenti in uno script.
Restituisce la Unix timestamp corrispondente all'argomento dato. Questa timestamp è un intero lungo contenente il numero di secondi tra la Unix Epoch (January 1 1970) e la data e orario specificati.
Gli argomenti possono essere omessi nell'ordine da destra a sinistra; degli argomenti omessi saranno impostati con l'attuale valore accordandolo alla data e orario locale.
is_dst può essere impostato su 1 se l'orario è nell'ora legale, 0 altrimenti, o -1 (di default) se è sconosciuta la presenza dell'ora legale o meno. Se è sconosciuto, il PHP proverà ad impostarlo da se. Questo può causare un risultato non aspettato (ma non sbagliato).
Nota: is_dst è stato aggiunto nella verisone 3.0.10.
mktime() è usata per fare calcoli tra date e validazioni, come può calcolare automaticamente il corretto valore per un valore fuori dall'intervallo valido. Per esempio, ognuna delle seguenti linee produce la stringa "Jan-01-1998".
L'ultimo giorno del mese dato può essere espresso come il giorno "0" del mese successivo, non come il giorno -1. Entrami i seguenti esempi produrranno la stringa "L'ultimo giorno di Feb 2000 è: 29".
Date con anno, mese e giorno uguali a 0 non sono considerate valide (altrimenti saranno considerate come 30.11.1999, quando hanno uno strano behavior).
(PHP 3, PHP 4, PHP 5)
strftime -- Formatta una data/orario locale accordandola/o alle impostazioni locali according to locale settingsRestituisce una stringa formattata in accordo con la stringa del formato data usando il parametro dato timestamp o l'attuale orario locale se non è stato dato il timestamp. I nomi di mesi e giorni della settimana e le altre stringhe dipendenti dalla lingua rispettano le attuali impostazioni locali con setlocale().
Le seguenti sequenze di caratteri sono utilizzate nella stringa del formato:
%a - Nome del giorno della settimana abbreviato in accordo con i parametri locali
%A - Nome completo del giorno della settimana in accordo con i parametri locali
%b - Nome del mese abbreviato in accordo con i parametri locali
%B - Nome completo del mese in accordo con i parametri locali
%c - Rappresentazione preferita di data e orario per le attuali impostazioni locali
%C - numero del secolo (l'anno diviso 100 e troncato in un intero, intervallo tra 00 e 99)
%d - giorno del mese come numero decimale (intervallo tra 01 e 31)
%D - come %m/%d/%y
%e - giorno del mese come numero decimale, un singolo carattere è preceduto da uno spapzio (intervallo tra ' 1' e '31')
%g - come %G, ma senza il secolo.
%G - L'anno a 4 cifre corrispondente al numero di setitmana ISO (vedi %V). Questa ha lo stesso formato e valore di %Y, eccetto che se il numero di settimana ISO appartiene al precedente o prossimo anno, è invece utilizzato l'anno attuale.
%h - come %b
%H - ora come numero decimale usando il sistema a 24 ore (intervallo tra 00 e 23)
%I - ora come numero decimale usando il sistema a 12 ore (intervallo tra 01 e 12)
%j - giorno dell'anno come numero decimale (intervallo tra 001 e 366)
%m - mese come numero decimale (intervallo tra 01 e 12)
%M - minuto come numero decimale
%n - carattere di nuova linea
%p - entrambi `am' o `pm' accordati a un valore di tempo dato, o alle stringhe corrispondenti per le impostazioni locali
%r - orario in notazione a.m. e p.m
%R - orario nella notazione a 24 ore
%S - secondi come numero decimale
%t - Carattere di tabella
%T - orario attuale, identico a %H:%M:%S
%u - giorno della settimana come numero decimale [1,7], dove 1 rappresenta il Lunedì
Avvertimento |
Sun Solaris sembra far iniziare con la Domenica a come 1 sebbe la ISO 9889:1999 (l'attuale standard di C) specifica chiaramente che dovrebbe iniziare dal Lunedì. |
%U - numero della settimana dell'anno in corso come numero decimale, iniziando dalla prima Domenica come primo giorno della prima settimana
%V - Il numero di settimana ISO 8601:1988 dell'anno attuale come numero decimale, intervallo tra 01 e 53, dove la settimana 1 è la prima settimana che ha almeno 4 giorni dell'attuale anno, e con il Lunedì come primo giorno della settimana. (Utilizza %G o %g per l'anno componente che corrisponde al numero di settimana per il timestamp specificato.)
%W - numero della settimana dell'attuale anno come numero decimale, partendo con il primo Lunedì come primo giorno della prima settimana
%w - giorno della settimana come decimale, dove la Domenica è 0
%x - visualizzazione della data preferita dalle impostazioni del sistema locale senza orario
%X - visualizzazione dell'orario preferito dalle impostazioni del sistema locale senza data
%y - anno come numero decimale senza secolo (intervallo tra 00 e 99)
%Y - anno come numero decimale incluso il secolo
%Z - fuso orario o abbreviazione
%% - il carattere `%'
Nota: Non tutte le sequenze di caratteri potrebbero essere supportate dalla tua libreria locale di C, in tal caso la funzione strftime() non sarà supportata dal PHP. Questo significa che %T e %D non funzioneranno sotto Windows.
Guarda anche setlocale() e mktime() e le specifiche dell' Open Group per strftime().
strptime() returns an array with the date parsed, or FALSE on error.
Month and weekday names and other language dependent strings respect the current locale set with setlocale() (LC_TIME).
Nota: Questa funzione non è implementata su piattaforme Windows
The string to parse (e.g. returned from strftime())
The format used in date (e.g. the same as used in strftime()).
For more information about the format options, read the strftime() page.
Returns an array, or FALSE on failure.
Tabella 1. The following parameters are returned in the array
parameters | Description |
---|---|
tm_sec | Seconds after the minute (0-61) |
tm_min | Minutes after the hour (0-59) |
tm_hour | Hour since midnight (0-23) |
tm_mday | Day of the month (1-31) |
tm_mon | Months since January (0-11) |
tm_year | Years since 1900 |
tm_wday | Days since Sunday (0-6) |
tm_yday | Days since January 1 (0-365) |
unparsed | the date part which was not recognized using the specified format |
Esempio 1. strptime() example
Il precedente esempio visualizzerà qualcosa simile a:
|
(PHP 3 >= 3.0.12, PHP 4, PHP 5)
strtotime -- Analizza le descrizioni testuali di datetime in Inglese nell'UNIX timestampLa funzione aspetta di avere una stringa contenente un formato di data in Inglese e proverà a passare questo formato all'UNIX timestamp relativo al timestamp dato in now, o l'attuale orario se non è stato passato il parametro. Sul fallimento, è restituito -1.
Perché strtotime() si comporti in accordo con la sintassi della data GNU, dai uno sguardo alla pagina del manuale GNU intitolata Date Input Formats. Descrive se c'è una sinstassi valida per il parametro time.
Esempio 1. strtotime() - esempi
|
Nota: L'intervallo valido di un timestamp è normalmente da Fri, 13 Dec 1901 20:45:54 GMT a Tue, 19 Jan 2038 03:14:07 GMT. (Queste sono le date ce corrispondono al minimo e al massimo valore per un intero segnato a 32 bit.)
Restituisce l'attuale data e orario misurata in numero di secondi dalla Unix Epoch (January 1 1970 00:00:00 GMT).
Guarda anche date().
Avvertimento |
Questo modulo è SPERIMENTALE. Ovvero, il comportamento di queste funzioni, i nomi di queste funzioni, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questo modulo è a vostro rischio. |
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.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Most db++ functions operate on or return dbplus_relation resources. A dbplus_relation is a handle to a stored relation or a relation generated as the result of a query.
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Tabella 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 |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Calling dbplus_close() will close a relation previously opened by dbplus_open().
Returns TRUE on success or DBPLUS_ERR_UNKNOWN on failure.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_errno() will return the error code returned by the last db++ operation.
See also dbplus_errcode().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_freealllocks() will free all tuple locks held by this client.
See also dbplus_getlock(), dbplus_freelock(), and dbplus_freerlocks().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_freerlocks() will free all tuple locks held on the given relation.
See also dbplus_getlock(), dbplus_freelock(), and dbplus_freealllocks().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_curr() will read the data for the previous 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().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_rchperm() will change access permissions as specified by mask, user and group. The values for these are operating system specific.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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, PECL)
dbplus_rcrtexact -- Creates an exact but empty copy of a relation including indicesAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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.
Returns resource on success or DBPLUS_ERR_UNKNOWN on failure.
(4.1.0 - 4.2.3 only, PECL)
dbplus_rcrtlike -- Creates an empty copy of a relation with default indicesAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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.
Returns resource on success or DBPLUS_ERR_UNKNOWN on failure.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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.
Returns resource on success or DBPLUS_ERR_UNKNOWN on failure.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_rrename() will change the name of relation to name.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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.
Returns resource on success or DBPLUS_ERR_UNKNOWN on failure.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_unlink() will close and remove the relation.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_rzap() will remove all tuples from relation.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_unlockrel() will release a write lock previously obtained by dbplus_lockrel().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Calling dbplus_unselect() will remove a constraint previously set by dbplus_find() on relation.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_update() replaces the tuple given by old with the data from new if and only if old completely matches a tuple within relation.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_xlockrel() will request an exclusive lock on relation preventing even read access from other clients.
See also dbplus_xunlockrel().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
dbplus_xunlockrel() will release an exclusive lock on relation previously obtained by dbplus_xlockrel().
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.
Tabella 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 4.3.2. |
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 at http://cr.yp.to/cdb.html. 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 bundled 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. |
inifile | This is available since PHP 4.3.3 to be able to modify php.ini files from within PHP scripts. When working with ini files you can pass arrays of the form array(0=>group,1=>value_name) or strings of the form "[group]value_name" where group is optional. As the functions dba_firstkey() and dba_nextkey() return string representations of the key there is a new function dba_key_split() available since PHP 5 which allows to convert the string keys into array keys without loosing FALSE. |
qdbm | This is available since PHP 5.0.0. The qdbm library can be loaded from http://qdbm.sourceforge.net. |
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 module 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.
Avvertimento |
After configuring and compiling PHP you must execute the following test from commandline: php run-tests.php ext/dba. This shows whether your combination of handlers works. Most problematic are dbm and ndbm which conflict with many installations. The reason for this is that on several systems these libraries are part of more than one other library. The configuration test only prevents you from configuring malfaunctioning single handlers but not combinations. |
Tabella 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.
|
inifile |
To enable support for inifile add
--with-inifile.
|
qdbm |
To enable support for qdbm add
--with-qdbm[=DIR].
|
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 misconfigurations.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
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.
dba_close() closes the established database and frees all resources of the specified database handle.
dba_delete() deletes the specified entry from the database.
The key of the entry which is deleted.
The database handler, returned by dba_open() or dba_popen().
dba_exists() checks whether the specified key exists in the database.
The key the check is performed for.
The database handler, returned by dba_open() or dba_popen().
dba_fetch() fetches the data specified by key from the database specified with handle.
The key the data is specified by.
Nota: When working with inifiles this function accepts arrays as keys where index 0 is the group and index 1 is the value name. See: dba_key_split().
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.
The database handler, returned by dba_open() or dba_popen().
dba_firstkey() returns the first key of the database and resets the internal key pointer. This permits a linear search through the whole database.
dba_handlers() list all the handlers supported by this extension.
Turns on/off full information display in the result. The default is FALSE.
Returns an array of database handlers. If full_info is set to TRUE, the array will be associative with the handlers names as keys, and their version information as value. Otherwise, the result will be an indexed array of handlers names.
Nota: When the internal cdb library is used you will see cdb and cdb_make.
Esempio 1. dba_handlers() Example
Il precedente esempio visualizzerà qualcosa simile a:
|
dba_insert() inserts the entry described with key and value into the database.
The key of the entry to be inserted. If this key already exist in the database, this function will fail. Use dba_replace() if you need to replace an existent key.
The value to be inserted.
The database handler, returned by dba_open() or dba_popen().
dba_key_split() splits a key (string representation) into an array representation.
Returns an array of the form array(0 => group, 1 => value_name). This function will return FALSE if key is NULL or FALSE.
dba_nextkey() returns the next key of the database and advances the internal key pointer.
dba_open() establishes a database instance for path with mode using handler.
Commonly a regular path in your filesystem.
It 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.
Additionally you can set the database lock method with the next char. Use l to lock the database with a .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 absolutely 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.
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 following table:
Tabella 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.
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.
Versione | Descrizione |
---|---|
4.3.0 | It's 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. |
4.3.0 | Locking and the mode modifiers "l", "d", "-" and "t" were added. In previous PHP versions, you must use semaphores to guard against simultaneous database access for any database handler with the exception of GDBM. See System V semaphore support. |
before 4.3.5 | open mode 'c' is broken for several internal handlers and truncates the database instead of appending data to an existent database. Also dbm and ndbm fail on mode 'c' in typical configurations (this cannot be fixed). |
dba_popen() establishes a persistent database instance for path with mode using handler.
Commonly a regular path in your filesystem.
It 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.
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_replace() replaces or inserts the entry described with key and value into the database specified by handle.
The key of the entry to be replaced.
The value to be replaced.
The database handler, returned by dba_open() or dba_popen().
Queste funzioni consentono di accedere ai record memorizzati nei database in formato dBase (dbf).
Non è previsto il supporto per indici o campi memo. Manca anche il supporto per il locking. E' probabile che due processi concorrenti che modifichino lo stesso database, finiscano con il rovinare il Database.
I files dBase sono semplici files sequenziali o records a lunghezza fissa. I record sono aggiunti (append) alla fine del file e quelli cancellati sono conservati fino alla chiamata della funzione dbase_pack().
Si raccomanda di non usare i files dBase come database di lavoro. Scegliere piuttosto qualsiasi reale SQL server; MySQL o Postgres sono scelte comuni con PHP. Il supporto dBase è presente per permettervi di importare ed esportare dati da e verso il vostro web database, perchè il formato del file è comunemente ben interpretato dai fogli elettronici e dagli organizers di Windows.
Allo scopo di abilitare le librerie dbase fornite e di usare queste funzioni, si deve compilare PHP con l'opzione --enable-dbase .
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Aggiunge i dati nel record al database. Se il numero di items nel record non è uguale al numero di campi nel database, l'operazione fallirà e sarà restituito FALSE.
Chiude il database associato con il dbase_identifier.
dBase_create()crea un database dBase nel filefilename con i campifields
Il parametro fields è un array di arrays, ciascun array descrive il formato di un campo nel database. Ogni campo consiste di un nome, un carattere che indica il tipo di campo, una lunghezza, e una precisione.
I tipi di campo disponibili sono:
Boolean. Questi non hanno una lunghezza o una precisione.
Memo. (Nota che non sono supportati da PHP.) Questi non hanno una lunghezza o una precisione.
Date (memorizzate nel formato YYYYMMDD). Questi non hanno una lunghezza o una precisione.
Number. Questi hanno sia una lunghezza sia una precisione (il numero di decimali).
String.
Se il database è creato con successo, viene restituito un dbase_identifier, altrimenti viene restituito FALSE.
Esempio 1. Creare un file di database dBase
|
Marca il record da cancellare dal database. Per rimuovere il record dal database, è necessario chiamare la funzione dbase_pack().
Restituisce informazioni sulla struttura delle colonne del database referenziato da dbase_identifier. Per ogni colonna del database, esiste un valore specificato in un array ad indice numerico. L'indice dell'array inizia da 0. Ogni elemento dell'array contiene un array associativo di informazioni sulle colonne. Se l'informazione dell'header dell'array non può esssere letta, viene restituito, FALSE .
Gli elementi dell'array sono:
Il nome della colonna
Il nome del tipo di colonna del dBase riconoscibile dall'utente (es. data, boolean, etc)
Il numero di bytes che la colonna può contenere
Il numero di cifre della precisione decimale della colonna
Un formato di printf() suggerito, specifico per la colonna
L'offest, in byte, della colonna dall'inizio riga
Esempio 1. Mostra le informazioni dell'header di un file di database in formato dBase
|
(PHP 3 >= 3.0.4, PHP 4, PHP 5)
dbase_get_record_with_names -- Estrae un record da un database dBase come un array associativoRestituisce i dati da record in un array associativo. L'array include anche un membro associativo chiamato 'deleted' che è settato a 1 se il record è stato marcato per la cancellazione (vedere dbase_delete_record()).
Ogni campo è convertito all'appropriato tipo PHP, Fanno eccezione:
Le date, che sono lasciate come stringhe.
Gli interi che avrebbero causato un overflow (> 32 bits) sono restituiti come stringhe.
Restituisce i dati da record in un array. L'array è indicizzato partendo da 0, e include un membro associativo chiamato 'deleted' che è settato a 1 se il record è stato marcato per la cancellazione (vedere dbase_delete_record()).
Ogni campo è convertito all'appropriato tipo PHP, Fanno eccezione:
Le date, che sono lasciate come stringhe.
Gli interi che avrebbero causato un overflow (> 32 bits) sono restituiti come stringhe.
Restituisce il numero di campi (colonne) nel databaase specificato. I numeri dei campi sono compresi tra 0 e dbase_numfields($db)-1, mentre i numeri dei records sono compresi tra 1 e dbase_numrecords($db).
Restituisce il numero di records (righe) nel database specificato. I numeri dei records sono compresi tra 1 e dbase_numrecords($db), mentre i numeri dei campi sono compresi tra 0 e dbase_numfields($db)-1.
Restituisce un dbase_identifier per il database aperto, o FALSE se il database non può essere aperto
I parametri flags corrispondono a quelli della system call open() (Tipicamente, "0" significa sola-lettura, "1" significa sola scrittura e "2" lettura-scrittura).
Nota: Quando safe-mode è abilitato, PHP controlla che i file o le directory sulle quali si sta andando a lavorare, abbiano lo stesso UID dello script che è in esecuzione.
Stabilizza il database specificato (cancellando permanentemente tutti i records marcati per la cancellazione usando dbase_delete_record()).
Sostituisce i dati associati con il record record_number con i dati nel record nel database. Se il numero di items nel record non è uguale al numero di campi nel database, l'operazione fallirà e sarà restituito FALSE.
dbase_record_number è un integer che va da 1 al numero di records nel database (come restituito da dbase_numrecords()).
Questa funzioni consentono lo storage di records memorizzati in un dbm-style database. Questo tipo di database (supportato da Berkeley DB, GDBM, e qualche libreria di sistema, così come una built-in flatfile library) memorizza coppie key/value (al contrario dei full-blown records supportati dai database relazionali).
Nota: Il supporto per dbm è deprecato e si incoraggia ad utilizzare Database (dbm-style) abstraction layer functions.
Per utilizzare queste funzioni occorre compilare il PHP con il supporto per un database sottostante. Vedere l'elenco dei database supoprtati.
Per potere utilizzare queste funzioni occorre compilare il PHP con il supporto dbm utilizzando l'opzione --with-db. Inoltre occorre garantire il supporto per il sottostante database oppure occorre utilizzare qualche libreria di sistema.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
La funzione dbmopen() restituisce un identificatore di database che può essere utilizzato con le altre funzioni dbm.
Cancella il valore per key nel database.
Restituisce FALSE se la chiave non esisteva nel database.
Restituisce TRUE se c'è un valore associato con la key.
Restituisce il valore associato con key.
Restituisce la prima chiave nel database. Da notare che nessun ordine particolare è garantito dal momento che il database potrebbe essere stato costruito usando una hash-table, che non garantisce nessun ordine.
Aggiunge il valore al database con la chiave specificata.
Restituisce -1 se il database è stato aperto in modalità read-only (sola lettura), 0 se l'inserimento è andato a buon fine, e 1 se la chiave specificata già esiste. (Per sostituire il valore, usa dbmreplace().)
Restituisce la chiave successiva dopo key. Chiamando la funzione dbmfirstkey() seguita da successive chiamate alla funzione dbmnextkey() è possibile visionare ciascuna coppia key/value nel database DBM. Per esempio:
Il primo argomento è il nome (con il percorso completo) del file DBM da aprire e il secondo è l' open mode del file che può essere "r", "n", "c" or "w" per sola lettura, nuovo (implica lettura-scrittura, e molto probabilmente troncherà un database esistente con lo stesso nome), crea (implica lettura-scrittura, e non troncherà un database esistente con lo stesso nome) e lettura-scrittura rispettivamente.
Restituisce un identifier da passare alle altre funzioni DBM in caso di successo, o FALSE se fallisce.
Se è usato il supporto NDBM, NDBM creerà i file filename.dir e filename.pag. GDBM usa solo un file, in quanto fa l' internal flat-file support, e il Berkeley DB crea un filename.db file. Da notare che PHP fa il suo file locking in aggiunta a quello che eventualmente potrebbe fare la stessa libreria DBM. PHP non cancella i files .lck che crea. Semplicemente usa questi files come fixed inodes su cui fare il file locking. Per maggiori informazioni sui files DBM, guarda le pagine del tuo manuale UNIX, o scarica GNU's GDBM.
Nota: Quando safe-mode è abilitato, PHP controlla che i file o le directory sulle quali si sta andando a lavorare, abbiano lo stesso UID dello script che è in esecuzione.
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.
Nota: Questo modulo è stato spostato nel repository PECL e non sarà più rilascio con il PHP dalla versione 5.1.0.
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, the 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).
SQLite (PHP 5).
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.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. DBX Configuration Options
Name | Default | Changeable | Changelog |
---|---|---|---|
dbx.colnames_case | "unchanged" | PHP_INI_SYSTEM | Available since PHP 4.3.0. |
Breve descrizione dei parametri di configurazione.
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 holds the result of a query.
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
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
Esempio 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)
DBX_SQLITE or "sqlite" (PHP 5)
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, PHP 5 <= 5.0.4)
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).
(PHP 4 >= 4.3.0, PHP 5 <= 5.0.4)
dbx_escape_string -- Escape a string so it can safely be used in an sql-statementdbx_escape_string() returns the text, escaped where necessary (such as quotes, backslashes etc). It returns NULL on error.
Esempio 1. dbx_escape_string() example
|
See also dbx_query().
(PHP 5 <= 5.0.4)
dbx_fetch_row -- Fetches rows from a query-result that had the DBX_RESULT_UNBUFFERED flag setdbx_fetch_row() returns a row on success, and 0 on failure (e.g. when no more rows are available). When the DBX_RESULT_UNBUFFERED is not set in the query, dbx_fetch_row() will fail as all rows have already been fetched into the results data property.
As a side effect, the rows property of the query-result object is incremented for each successful call to dbx_fetch_row().
Esempio 1. How to handle the returned value
|
The result_identifier parameter is the result object returned by a call to dbx_query().
The returned object contains the same information as any row would have in the dbx_query result data property, including columns accessible by index or fieldname when the flags for dbx_guery were set that way.
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 (i.e. a SELECT query, even if the result set is empty).
Esempio 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.
This flag will not create the data property, and the rows property will initially be 0. Use this flag for large datasets, and use dbx_fetch_row() to retrieve the results row by row.
The dbx_fetch_row() function will return rows that are conformant to the flags set with this query. Incidentally, it will also update the rows each time it is called.
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 returned 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"].
Esempio 3. outputs the content of data property into HTML table
|
Esempio 4. How to handle UNBUFFERED queries
|
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(), dbx_fetch_row() and dbx_connect().
(PHP 4 >= 4.0.6, PHP 5 <= 5.0.4)
dbx_sort -- Sort a result from a dbx_query by a custom sort functionRestituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: It is always better to use ORDER BY SQL clause instead of dbx_sort(), if possible.
Esempio 1. dbx_sort() example
|
See also dbx_compare().
Il PHP supporta funzioni per l'I/O diretto, come descritto dallo standard POSIX (Sezione 6), per potere eseguire operazioni di I/O ad un livello inferiore rispetto agli streams del linguaggio C (fopen(), fread(),..). Si dovrebbe prendere in considerazione l'uso delle funzioni di DIO soltanto nei casi in cui occorra un controllo diretto del device. In tutti gli altri casi le funzioni filesystem sono più che adeguate.
Nota: Questo modulo è stato spostato nel repository PECL e non sarà più rilascio con il PHP dalla versione 5.1.0.
Questo modulo è disponibile sulla piattaforma Windows solo dal PHP 5.0.0
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Questa estensione definisce un solo tipo di risorsa: un descrittore di file restituito dalla funzione dio_open().
La funzione dio_fcntl() esegue le operazioni specificate dal parametro cmd sul descrittore di file fd. Qualora i comandi richiedano informazioni addizionali occorre valorizzare args con tali informazioni.
Nota: Questa funzione non è implementata su piattaforme Windows
Descrittore di file restituito da dio_open().
Può indicare una delle seguenti operazioni:
F_SETLK - imposta o azzera un lock. Se il lock è impostato da un'altro processo la funzione dio_fcntl() restituisce -1.
F_SETLKW - come F_SETLK, ma nel caso in cui il lock sia impostato da un'altro processo la funzione dio_fcntl() attende sino a quando il blocco non viene rimosso.
F_GETLK - la dio_fcntl() restituisce un array associativo (come descritto precedentemente) se qualche altro processo impedisce il lock. Se non vi sono problemi la chiave "type" sarà impostata a F_UNLCK.
F_DUPFD - trova il più piccolo numero di descrittore di file disponibile che sia maggiore o uguale rispetto ad args e lo restituisce.
F_SETFL - Imposta i flag del descrittore di file al valore specificato da args. Tale valore può essere O_APPEND, O_NONBLOCK oppure O_ASYNC. Per utilizzare O_ASYNC occorre utilizzare l'estensione PCNTL.
Il parametro args è un array associativo, nei casi in cui cmd è impostato a F_SETLK oppure a F_SETLLW, contiene le seguenti chiavi:
"start" - offset da cui comincia il lock
"length" - dimensione dell'area bloccata, zero significa fine file
"wenth" - a cosa l_start è relativo: può valere SEEK_SET, SEEK_END o SEEK_CUR
"type" - tipo di lock: può essere F_RDLCK (lock in lettura), F_WRLCK (lock in scrittura) oppure F_UNLCK (rimozione del lock)
Esempio 1. Impostare e cancellare un lock
|
(PHP 4 >= 4.2.0, PHP 5 <= 5.0.4)
dio_open -- Apre un nuovo file nella modalità specificata da flags e i permessi indicati in modeLa funzione dio_open() apre un file e restituisce un nuovo descrittore di file per questo.
Il file aperto.
Il parametro flags può contenere qualsiasi combinazione dei seguenti valori:
O_CREAT - crea un file, se questo non esiste già.
O_EXCL - se sono impostati sia O_CREAT e sia O_EXCL, la funzione dio_open() fallisce se il file esiste.
O_TRUNC - se il file esiste, ed è aperto in scrittura, il file verrà portato a lunghezza zero.
O_APPEND - nelle operazioni di scrittura, scrive i dati alla fine del file.
O_NONBLOCK - imposta la modalità non blocking.
Se flags vale O_CREAT, allora il parametro mode imposta la modalità del file (permessi di creazione).
O_RDONLY - apre il file per accessi in lettura.
O_WRONLY - apre il file in scrittura.
O_RDWR - apre il file sia in lettura sia in scrittura.
La funzione dio_read() legge e restituisce len bytes dal file indicato dal descrittore fd.
Descrittore di file restituito da dio_open().
Numero di byte da leggere. Se non indicato dio_read() legge blocchi da un 1k.
La funzione dio_seek() viene utilizzata per modificare la posizione nel file indicato dal descrittore fd.
Descrittore di file restituito da dio_open().
La nuova posizione.
specifica come debba essere interpretata la posizione indicata da pos:
SEEK_SET (default) - Indica che pos è determinato dall'inizio del file.
SEEK_CUR - Indica che pos è il numero di caratteri dalla posizione attuale. Questo valore può essere positivo o negativo.
SEEK_END - Indica che pos è il numero di caratteri dalla fine del file. Un valore negativo specifica una posizione all'interno dell'estensione del file; un valore positivo specifica una posizione oltre la fine corrente del file. Se si specifica una posizione oltre la fine del file, e vi si scrive dei dati, il file sarà allungato e riempito di zero fino a quella posizione.
Esempio 1. Posizionamento in un file
|
(PHP 4 >= 4.2.0, PHP 5 <= 5.0.4)
dio_stat -- Restituisce le informazioni relative al file indicato da fdLa funzione dio_stat() restituisce le informazioni sul dato descrittore di file.
Restituisce un array associativo contenente le seguenti chiavi:
"device" - device
"inode" - inode
"mode" - mode
"nlink" - numero di link
"uid" - user id
"gid" - group id
"device_type" - device type (se inode device)
"size" - total size in bytes
"blocksize" - blocksize
"blocks" - dimensione totale in byte
"atime" - data dell'ultimo accesso
"mtime" - data dell'ultima modifica
"ctime" - data dell'ultimo cambiamento
(PHP 4 >= 4.3.0, PHP 5 <= 5.0.4)
dio_tcsetattr -- Imposta gli attributi terminale e la velocità per una porta serialeLa funzione dio_tcsetattr() imposta gli attributi di terminale e la velocità della porta aperta fd.
Nota: Questa funzione non è implementata su piattaforme Windows
Descrittore di file restituito da dio_open().
Attualmente le opzioni disponibili sono:
'baud' - velocità della porta - può essere 38400,19200,9600,4800,2400,1800,1200,600,300,200,150,134,110,75 oppure 50, il valore di default è 9600
'bits' - bit di dati - può essere 8,7,6 oppure 5 il valore di default è 8.
'stop' - bit di stop - può essere 1 o 2 il valore di default è 1.
'parity' - può essere 0,1 o 2 il valore di default è 0.
Esempio 1. Esempio di impostazione della velocità di una porta seriale
|
(PHP 4 >= 4.2.0, PHP 5 <= 5.0.4)
dio_truncate -- Tronca il file indicato da fd ad un numero di byte specificatoLa funzione dio_truncate() tronca il file indicato da fd ad una lunghezza massima di offset bytes.
Se in precedenza il file ha una dimensione maggiore, i dati in eccesso sono persi. Al contrario se il file è più corto, non è specificato se si debba lasciarlo inalterato o debba essere allungato. Nell'ultimo caso la parte aggiunta viene riempita a zero.
Nota: Questa funzione non è implementata su piattaforme Windows
(PHP 4 >= 4.2.0, PHP 5 <= 5.0.4)
dio_write -- Scrive dati sul file indicato da fd con la possibilità di troncarne la lunghezzaLa funzione dio_write() scrive fino a len bytes da data nel file fd.
Descrittore di file restituito da dio_open().
I dati scritti.
Lunghezza dei dati da scrivere in byte. Se non indicato, la funzione scrive tutti i dati nel file indicato.
Non è necessaria nessuna installazione per usare queste funzioni, esse fanno parte del core di PHP.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Nota: La costante PATH_SEPARATOR è stata inserita dalla versione 4.3.0-RC2.
Per funzioni correlate, quali dirname(), is_dir(), mkdir() e rmdir(), vedere la sezione Filesystem.
Cambia la directory in uso da parte del PHP in directory. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: Quando safe-mode è abilitato, PHP controlla che la directory nella quale si sta lavorando, abbia lo stesso UID dello script che è in esecuzione.
Vedere anche getcwd().
Cambia la directory di root del processo in esecuzione in directory. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Questa funzione è disponibile soltanto se il sistema la supporta e se si sta utilizzando il PHP come CLI, CGI o Embed SAPI.
Nota: chroot() richiede i privilegi di root.
Nota: Questa funzione non è implementata su piattaforme Windows
Un meccanismo pseudo orientato agli oggetti per leggere una directory. La directory data è aperta. Due proprietà sono disponibili nonappena la directory è stata aperta. La proprietà handle può essere usata in congiunzione ad altre funzioni relative alle directory, quali readdir(), rewinddir() e closedir(). La proprietà path è impostata alla directory che è stata aperta. Sono disponibili tre metodi: read (leggi), rewind (riavvolgi) e close (chiudi).
Fare attenzione al modo in cui il valore restituito dalla funzione dir() è controllato nell'esempio sotto riportato. Controlliamo esplicitamente che il valore restituito sia identico a (uguale a e dello stesso tipo di (fare riferimento a Comparison Operators per maggiori informazioni) FALSE altrimenti, ogni risultato il cui nome non venga valutato FALSE farà interrompere il ciclo.
Nota: L'ordine nel quale vengono restituiti i dati dal metodo read è dipendente dal sistema usato.
Nota: Questo definisce la classe interna Directory, ciò significa che non sarà possibile definire una nuova classe con lo stesso nome. Per una lista completa delle classi predefinite presenti in PHP, fare riferimento a Predefined Classes.
Chiude il flusso directory indicato da dir_handle. Il flusso deve essere stato aperto in precedenza da opendir().
Restituisce la directory di lavoro in uso al momento o FALSE in caso di errore.
Nota: In alcune versioni di Unix, getcwd() restituirà FALSE se una delle directory superiori non ha i permessi di lettura o di ricerca abilitati, anche se li ha la directory corrente Vedere chmod() per maggiori infprmazioni sui permessi.
Restituisce un handle della directory da usare nelle chiamate alle funzioni closedir(), readdir() e rewinddir().
Se percorso non è una directory valida o la directory non può essere aperta a causa di restrizioni sui permessi di accesso o a causa di errori del filesystem, opendir() restituisce FALSE e genera un errore PHP di tipo E_WARNING. Si può sopprimere l'output dell'errore di opendir() anteponendo '@' davanti al nome della funzione.
Dal PHP 4.3.0 path può essere anche un URL che suuporto la visualizzazione del contenuto della directory, tuttavia, in PHP 4.3.0, soltanto il wrapper URL file:// supporta ciò. A partire da PHP 5.0.0, sarà disponibile il supporto per ftp://.
Restituisce il nomefile del file successivo della directory. I nomi dei file vengono restituiti secondo l'ordine in cui sono memorizzati nel filesystem.
Si faccia caso al modo in cui il valore restituito da readdir() viene controllato negli esempi successivi. Viene controllato esplicitamente che il valore restituito sia identico a (uguale a e dello stesso tipo di (vedere Comparison Operators per maggiori informazioni) FALSE altrimenti avverrebbe che ogni nome di directory il cui nome fosse valutato FALSE interromperebbe il loop (per esempio una directory chiamata "0").
Esempio 1. Elenca tutti i file presenti in una directory
|
Nota che readdir() restituirà le voci . e ... Se non si vogliono ottenere queste, si possono semplicemente eliminare:
Reimposta il flusso della directory indicato da dir_handle all'inizio della directory.
Returns an array of files and directories from the directory.
The directory that will be scanned.
By default, the sorted order is alphabetical in ascending order. If the optional sorting_order is used (set to 1), then the sort order is alphabetical in descending order.
For a description of the context parameter, refer to the streams section of the manual.
Returns an array of filenames on success, or FALSE on failure. If directory is not a directory, then boolean FALSE is returned, and an error of level E_WARNING is generated.
Esempio 1. A simple scandir() example
Il precedente esempio visualizzerà qualcosa simile a:
|
Esempio 2. PHP 4 alternatives to scandir()
Il precedente esempio visualizzerà qualcosa simile a:
|
Suggerimento: È possibile utilizzare una URL come un nome di file con questa funzione se fopen wrappers è stata abilitata. Per maggiori informazioni su come specificare i nomi di file vedere fopen() e Appendice M per avere la lista dei protocolli URL supportati.
L'estensione DOM è la sostituzione dell'estensione DOM XML del PHP 4. Questo modulo continua a contenere diverse vecchie funzioni, ma non dovrebbereo essere più utilizzate. In particolar modo si dovrebbe evitare le funzioni che non sono orientate agli oggetti.
L'estensione permette di lavorare su un documento XML con le API DOM.
Non è necessaria nessuna installazione per usare queste funzioni, esse fanno parte del core di PHP.
Le APi del modulo seguono lo standard DOM Level 2 il più fedelmente possibile. Di conseguenza la API sono completamente ad oggetti. E' consigliabile avere a portata di mano lo standard DOM quando si utilizza questo modulo.
Questo modulo definisce diverse classi, che sono illustrate nelle seguenti tabelle. Quelle con una corrispondente classe nello standard DOM sono chia,ate DOMxxx.
Estende DOMNode. L'interfaccia DOMAttr rappresenta un attributo dell'oggetto DOMElement.
Espande DOMNode.
DOMCharacterData->appendData() - Aggiunge un testo alla fine dei dati di un nodo
DOMCharacterData->deleteData() - Rimuove un range di caratteri dal nodo
DOMCharacterData->insertData() - Inserisce una stringa alla posizione indicata
DOMCharacterData->replaceData() - Sostituisce una posizione di testo nel nodo DOMCharacterData
DOMCharacterData->substringData() - Estrai una porzione di dati dal nodo
Espande DOMNode.
DOMDocument->createAttribute() - Crea un nuovo attributo
DOMDocument->createAttributeNS() - Crea un nuovo nodo attributo con associato uno spazio dei nomi
DOMDocument->createCDATASection() - Crea un nuovo nodo cdata
DOMDocument->createComment() - Crea un nuovo nodo commento
DOMDocument->createDocumentFragment() - Crea un nuovo nodo frammento
DOMDocument->createElement() - Crea un nuovo nodo elemento
DOMDocument->createElementNS() - Crea un nuovo nodo elemento con associato uno spazio dei nomi
DOMDocument->createEntityReference() - Crea un nuovo nodo entità
DOMDocument->createProcessingInstruction() - CRea un nuovo nodo PI
DOMDocument->createTextNode() - Crea un nuovo nodo testo
DOMDocument->getElementById() - Cerca un elemento con un certo ID
DOMDocument->getElementsByTagName() - Cerca tutti gli elementi per un dato tag
DOMDocument->getElementsByTagNameNS() - Cerca tutti gli elementi per un dato tag in un specifico spazio dei nomi
DOMDocument->importNode() - Importa il nodo nel documento corrente
DOMDocument->load() - Carica un file XML
DOMDocument->loadHTML() - Carica un documento HTML da una stringa
DOMDocument->loadHTMLFile() - Carica un file HTML
DOMDocument->loadXML() - Carica un documento XML da una stringa
DOMDocument->normalize() - Normalizza il documento
DOMDocument->relaxNGValidate() - Esegue una validazione relaxNG sul documento
DOMDocument->relaxNGValidateSource() - Esegue una validazione relaxNG sul documento
DOMDocument->save() - Scrive l'albero XML in un file
DOMDocument->saveHTML() - Scarica il docuemnto interno in una stringa formattato in HTML
DOMDocument->saveHTMLFile() - Scarica il docuemnto interno in un file formattato in HTML
DOMDocument->saveXML() - Scrive l'albero XML in un file in una stringa
DOMDocument->schemaValidate() - Valida il documento in base ad uno schema
DOMDocument->schemaValidateSource() - Valida il documento in base ad uno schema
DOMDocument->validate() - Valida il documento in base ad al suo DTD
DOMDocument->xinclude() - Sostituisce gli XIncludes in un oggetto DOMDocument
Tabella 3.
Nome | Tipo | Sola lettura | Descrizione |
---|---|---|---|
actualEncoding | string | sì | |
config | DOMConfiguration | sì | |
doctype | DOMDocumentType | sì | Dichiarazione del tipo documento associato al docuemnto. |
documentElement | DOMElement | sì | Attributo di convenienza per accedere direttamente al nodo figlio, che è l'elemento del documento. |
documentURI | string | no | Luogo del documento oppure NULL se indefinito. |
encoding | string | no | |
formatOutput | bool | no | |
implementation | DOMImplementation | sì | L'oggetto DOMImplementation che gestisce questo documento. |
preserveWhiteSpace | bool | no | Non rimuovere gli spazi ridondanti. Default TRUE. |
recover | bool | no | |
resolveExternals | bool | no | Impostare a TRUE per caricare le entità esterne dalla dichiarazione doctype. Questo è utile per includere entità di caratteri nel documento XML. |
standalone | bool | no | |
strictErrorChecking | bool | no | Genera un DOMException in caso di errore. Default TRUE. |
substituteEntities | bool | no | |
validateOnParse | bool | no | Carica e valida nei confronti della DTD. Default FALSE. |
version | string | no | |
xmlEncoding | string | sì | L'attributo specifica, come parte della dichiarazione XML, la codifica del docuemnto. Vale NULL se non specificato oppure quando non è noto, come quando il documento è creato in memoria. |
xmlStandalone | bool | no | Attributo che specifica, come parte della dichiarazione XML, se il documento è standalone. Vale FALSE se non specificato. |
xmlVersion | string | no | Attributo che specifica, come parte della dichiarazione XML, il numero di versione del documento. Se non viè una dichiarazione e se il documento supporta le spcifiche "XML", vale "1.0". |
Espande DOMNode
Ciascun DOMDocument possiede un attributo doctype il cui valore può essere o NULL o un oggetto DOMDocumentType.
Tabella 4.
Nome | Tipo | Sola lettura | Descrizione |
---|---|---|---|
publicId | string | sì | Identificatore pubblico del subset esterno. |
systemId | string | sì | Identificatore di sistema del subset esterno. Può essere un URI assoluto o meno. |
name | string | sì | Il nome della DTD; ad esempio il nome che segue immediatamente la parola chiave DOCTYPE. |
entities | DOMNamedNodeMap | sì | Un oggetto DOMNamedNodeMap che contiene le entità generali, sia interne che esterne, dichiarate nella DTD. |
notations | DOMNamedNodeMap | sì | Un oggetto DOMNamedNodeMap contenente le notazioni dichiarate nella DTD. |
internalSubset | string | sì | SubSet interno definito come stringa, oppure null se non vi è nulla. Questo non contiene le parentesi quadre di delimitazione. |
Espande DOMNode.
DOMElement->getAttribute() - Restituisce il valore di un attributo
DOMElement->getAttributeNode() - Restituisce il nodo attributo
DOMElement->getAttributeNodeNS() - Restituisce il nodo attributo
DOMElement->getAttributeNS() - Restituisce il valore di un attributo
DOMElement->getElementsByTagName() - Restituisce gli elementi in base al nome tag
DOMElement->getElementsByTagNameNS() - Restituisce gli elementi in base all UTRI dello spazio dei nomi ed il nome locale
DOMElement->hasAttribute() - Verifica se l'attributo esiste
DOMElement->hasAttributeNS() - Verifica se l'attributo esiste
DOMElement->removeAttribute() - Rimuove l'attributo
DOMElement->removeAttributeNode() - Rimuove l'attributo
DOMElement->removeAttributeNS() - Rimuove l'attributo
DOMElement->setAttribute() - Aggiunge un nuovo attributo
DOMElement->setAttributeNode() - Aggiunge un nuovo nodo attributo all'elemento
DOMElement->setAttributeNodeNS() - Aggiunge un nuovo nodo attributo all'elemento
DOMElement->setAttributeNS() - Aggiunge un nuovo attributo
Espande DOMNode
Questa interfaccia rappresenta una entità nota, sia interpretata che no, in un documento XML.
Tabella 6.
Nome | Tipo | Sola lettura | Descrizione |
---|---|---|---|
publicId | string | sì | Identificatore pubblico associato all'entità, se indicato, altrimenti NULL. |
systemId | string | sì | Identificatore di sistema associato all'entità, se indicato, altrimenti NULL. Può essere un URI assoluto. |
notationName | string | sì | Per le entità non interpretate, il nome della notazione dell'entità. Per le entità interpretate vale NULL. |
actualEncoding | string | no | Attributo che indica la codifica utilizzata per questa entità al momento dell'intepretazione, in caso di interpretazione di entità esterne. Vale NULL se si tratta di un'entità interna, o se non è noto. |
encoding | string | sì | Attributo che indica, come parte del testo di dichiarazione, la codifica dell'entità, in caso di entità esterna. Negli altri casi vale NULL. |
version | string | sì | Attributo che indica, come parte del testo di dichiarazione, il numero di versione di questa entità, in caso di entità esterna. Altrimenti NULL. |
Le funzioni DOM, in casi particolari, generano delle eccezioni, ad esempio quando un'operazione non può essere eseguita per motivi logici.
Vedere anche Capitolo 20.
L'interfaccia DOMImplementation fornisce diversi metodi per eseguire operazioni che sono indipendenti da qualsiasi istanza del modello ad oggetti del documento.
DOMImplementation->createDocument() - Crea un nuovo oggetto DOM Document del tipo specificato con il suo elemento documento
DOMImplementation->createDocumentType() - Crea un oggetto DOMDocumentType vuoto
DOMImplementation->hasFeature() - Verifica se l'implementazione DOM supporta specifiche caratteristiche
DOMNode->appendChild() - Aggiunge un nuovo nodo figlio alla fine dei nodi figli
DOMNode->cloneNode() - Clona un nodo
DOMNode->hasAttributes() - Verifica se il nodo ha attributi
DOMNode->hasChildNodes() - Verifica se il nodo ha figli
DOMNode->insertBefore() - Aggiunge un nuovo figlio prima del nodo indicato
DOMNode->isSameNode() - Indica se due nodi sono lo stesso nodo
DOMNode->isSupported() - Verifica se la caratteristica chiesta è supportata dalla versione
DOMNode->lookupNamespaceURI() - Restituisce l'URI dello spazio dei nomi del nodo in base al suo prefisso
DOMNode->lookupPrefix() - Restituisce il prefisso dello spazio dei nomi del nodo in base all'URI dello spazio dei nomi
DOMNode->normalize() - Normalizza il nodo
DOMNode->removeChild() - Rimuove un nodo figlio dall'elenco dei nodi figli
DOMNode->replaceChild() - Sostituisce un nodo figlio
Tabella 8.
Nome | Tipo | Sola lettura | Descrizione |
---|---|---|---|
nodeName | string | sì | Restituisce un nome più accurato per il tipo di nodo. |
nodeValue | string | no | Valore di questo nodo, dipende dal tipo. |
nodeType | int | sì | Tipo di nodo. Una delle costanti XML_xxx_NODE predefinite. |
parentNode | DOMNode | sì | Nodo genitore di questo nodo. |
childNodes | DOMNodeList | sì | Un oggetto DOMNodeList che contiene tutti i nodi figli di questo nodo. Se non vi sono nodi figli, questa è un DOMNodeList vuoto. |
firstChild | DOMNode | sì | Il primo figlio di questo nodo. Se tale nodo non esiste, restituisce NULL. |
lastChild | DOMNode | sì | L'ultimo figlio di questo nodo. Se tale nodo non esiste, restituisce NULL. |
previousSibling | DOMNode | sì | Il nodo immediatamente precedente a questo. Se tale nodo non esiste, restituisce NULL. |
nextSibling | DOMNode | sì | Il nodo immediatamente seguente a questo. Se tale nodo non esiste, restituisce NULL. |
attributes | DOMNamedNodeMap | sì | Un oggetto DOMNamedNodeMap contenente gli attributi di questo nodo (se si tratta di un DOMElement) oppure NULL. |
ownerDocument | DOMDocument | sì | L'oggetto DOMDocument associato a questo nodo. |
namespaceURI | string | sì | L'URI dello spazio dei nomi di questo nodo, oppure NULL se non specificato. |
prefix | string | no | Prefisso dello spazio dei nomi del nodo, oppure NULL se non specificato. |
localName | string | sì | Restituisce la parte locale del nome qualificato del nodo. |
baseURI | string | sì | L'URI assoluto del nodo oppure NULL se l'implementazione non è in grado di ottenere l'URI assoluto. |
textContent | string | no | Questo attributo restituisce il testo contenuto nel nodo e nei suoi discendenti. |
Espande DOMNode.
DOMProcessingInstruction->__construct() - costruisce un nuovo oggetto DOMProcessingInstruction
Espande DOMCharacterData.
DOMText->isWhitespaceInElementContent() - Indica se questo nodo contiene degli spazi
DOMText->splitText() - Divide il nodo in due alla posizione indicata
DOMXPath->registerNamespace() - Registers the namespace with the DOMXpath object
DOMXPath->evaluate() - Evaluates the given XPath expression and returns a typed result if possible
DOMXPath->query() - Evaluates the given XPath expression
Many examples in this reference require an XML file. We will use book.xml that contains the following:
Esempio 1. chapter.xml
|
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Tabella 14. Costanti XML
Costante | Valore | Descrizione |
---|---|---|
XML_ELEMENT_NODE (integer) | 1 | Il nodo è un DOMElement |
XML_ATTRIBUTE_NODE (integer) | 2 | Il nodo è un DOMAttr |
XML_TEXT_NODE (integer) | 3 | Il nodo è un DOMText |
XML_CDATA_SECTION_NODE (integer) | 4 | Il nodo è un oggetto DOMCharacterData |
XML_ENTITY_REF_NODE (integer) | 5 | Il nodo è un oggetto DOMEntityReference |
XML_ENTITY_NODE (integer) | 6 | Il nodo è un DOMEntity |
XML_PI_NODE (integer) | 7 | Il nodo è un DOMProcessingInstruction |
XML_COMMENT_NODE (integer) | 8 | Il nodo è un DOMComment |
XML_DOCUMENT_NODE (integer) | 9 | Il nodo è un DOMDocument |
XML_DOCUMENT_TYPE_NODE (integer) | 10 | Il nodo è un oggetto DOMDocumentType |
XML_DOCUMENT_FRAG_NODE (integer) | 11 | Il nodo è un oggetto DOMDocumentFragment |
XML_NOTATION_NODE (integer) | 12 | Il nodo è un oggetto DOMNotation |
XML_HTML_DOCUMENT_NODE (integer) | 13 | |
XML_DTD_NODE (integer) | 14 | |
XML_ELEMENT_DECL_NODE (integer) | 15 | |
XML_ATTRIBUTE_DECL_NODE (integer) | 16 | |
XML_ENTITY_DECL_NODE (integer) | 17 | |
XML_NAMESPACE_DECL_NODE (integer) | 18 | |
XML_ATTRIBUTE_CDATA (integer) | 1 | |
XML_ATTRIBUTE_ID (integer) | 2 | |
XML_ATTRIBUTE_IDREF (integer) | 3 | |
XML_ATTRIBUTE_IDREFS (integer) | 4 | |
XML_ATTRIBUTE_ENTITY (integer) | 5 | |
XML_ATTRIBUTE_NMTOKEN (integer) | 7 | |
XML_ATTRIBUTE_NMTOKENS (integer) | 8 | |
XML_ATTRIBUTE_ENUMERATION (integer) | 9 | |
XML_ATTRIBUTE_NOTATION (integer) | 10 |
Tabella 15. Costanti DOMException
Costante | Valore | Descrizione |
---|---|---|
DOM_INDEX_SIZE_ERR (integer) | 1 | Se l'indice o la dimensione sono negativi, o maagiori del valore ammesso. |
DOMSTRING_SIZE_ERR (integer) | 2 | Se il range di testo indicato non rientra nell'oggetto DOMString. |
DOM_HIERARCHY_REQUEST_ERR (integer) | 3 | Se il nodo è inserito in posti non attesi |
DOM_WRONG_DOCUMENT_ERR (integer) | 4 | Se il nodo viene utilizzato in documenti differenti rispetto a quello che lo ha creato. |
DOM_INVALID_CHARACTER_ERR (integer) | 5 | Carattere invalido o illegale. |
DOM_NO_DATA_ALLOWED_ERR (integer) | 6 | Dati indicati per un nodo che non gestisce i dati. |
DOM_NO_MODIFICATION_ALLOWED_ERR (integer) | 7 | Tentativo di modifica di un oggetto che non permette modifiche. |
DOM_NOT_FOUND_ERR (integer) | 8 | Riferimento ad un nodo in un contesto in cui non esiste. |
DOM_NOT_SUPPORTED_ERR (integer) | 9 | Tipo di oggetto oppure operazione non supportata dall'implementazione. |
DOM_INUSE_ATTRIBUTE_ERR (integer) | 10 | Tentativo di aggiungere un attributo già in uso altrove. |
DOM_INVALID_STATE_ERR (integer) | 11 | Utilizzo di un oggetto che non è più utilizzabile. |
DOM_SYNTAX_ERR (integer) | 12 | Stringa non valida o illegale. |
DOM_INVALID_MODIFICATION_ERR (integer) | 13 | Tentativo di modificare il tipo dell'oggetto sottostante. |
DOM_NAMESPACE_ERR (integer) | 14 | Tentativo di creare o modficiare un oggetto in un modo che non è corretto rispetto allo spazio dei nomi. |
DOM_INVALID_ACCESS_ERR (integer) | 15 | Parametro od operazione non supportati dall'oggetto. |
DOM_VALIDATION_ERR (integer) | 16 | Chiamata ad un metodo tipo insertBefore oppure removeChild che renda il nodo invalido ripetto ad una 'validazione parziale'; questa eccezione comporta la mancata esecuzione dell'operazione. |
(no version information, might be only in CVS)
DOMAttr->__construct() -- Crea un nuovo oggetto DOMAttrCrea un nuovo oggetto DOMAttr. Questo oggetto è in sola lettura. Può essere aggiunto al documento, ma non vi possono essere aggiunti nodi fino a quando DOMDocument->createAttribute().
Nome tag dell'attributo- The tag name of the attribute.
Valore dell'attributo.
Esempio 1. Esempio di creazione di un nuovo DOMAttr
|
(no version information, might be only in CVS)
DOMAttr->isId() -- Verifica se l'attributo è un ID definitoQuesta funzione verifica se l'attributo sia un ID definito.
In base allo standard DOM, questa funzione riochiede la presenza di una DTD che definisca l'attributo ID di tipo ID. Occorre validare il documento con DOMDocument->validate() oppure DOMDocument::validateOnParse prima di utilizzare questa funzione.
Esempio 1. DOMAttr->isId() Example
|
(no version information, might be only in CVS)
DOMCharacterData->appendData() -- Aggiunge una stringa alla fine del testo di un nodoAggiunge la stringa data alla fine dei dati del nodo.
DOMCharacterData->deleteData() |
DOMCharacterData->insertData() |
DOMCharacterData->replaceData() |
DOMCharacterData->substringData() |
(no version information, might be only in CVS)
DOMCharacterData->deleteData() -- Rimuove un range di caratteri da un nodoRimuove un numero di caratteri pari a count a partire dalla posizione offset.
Offset da cui partire a rimuovere.
Il numero di caratteri da rimuovere. Se la somma di offset e count eccede la lunghezza del testo, saranno cancellati tutti i caratteri fino alla fine.
Eccezione generata se offset è negativo oppure più grande di un numero di 16 bit, oppure se count è negativo.
DOMCharacterData->appendData() |
DOMCharacterData->insertData() |
DOMCharacterData->replaceData() |
DOMCharacterData->substringData() |
(no version information, might be only in CVS)
DOMCharacterData->insertData() -- Inserisce una stringa all'offset di 16 bit indicatoInserisce la stringa data alla posizione offset.
L'offset del carattere da cui cominciare ad inserire.
La stringa da inserire.
DOMCharacterData->appendData() |
DOMCharacterData->deleteData() |
DOMCharacterData->replaceData() |
DOMCharacterData->substringData() |
(no version information, might be only in CVS)
DOMCharacterData->replaceData() -- Sostituisce una stringa all'interno di un nodo DOMCharacterDataSostituisce count caratteri a partire dalla posizione offset con data.
Offset da cui iniziare la sostituzione.
Numero di caratteri da sostituire. Se la somma di offset e count eccede la lunghezza, allora saranno sostituiti tutti i caratteri fino alla fine.
La stringa con cui sostituire i caratteri del range indicato.
Generato se offset è negativo o maggiore di un numero di 16 bit, oppure se count è negativo.
DOMCharacterData->appendData() |
DOMCharacterData->deleteData() |
DOMCharacterData->insertData() |
DOMCharacterData->substringData() |
(no version information, might be only in CVS)
DOMCharacterData->substringData() -- Estrae un tange di dati da un nodoRestituisce la stringa richiesta.
Offset di partenza della stringa richiesta.
Numero di caratteri da estrarre.
La stringa richiesta. Se la somma di offset e count supera in lunghezza i dati del nodo, considerati tutti a 16 bit, viengono restituiti tutti i dati fino alla fine.
Generato se offset è negativo o maggiore di un numero di 16 bit, oppure se count è negativo.
DOMCharacterData->appendData() |
DOMCharacterData->deleteData() |
DOMCharacterData->insertData() |
DOMCharacterData->replaceData() |
(no version information, might be only in CVS)
DOMComment->__construct() -- Crea un nuovo oggetto DOMCommentCrea un nuovo oggetto DOMComment. Questo oggetto è in sola lettura. Può essere aggiunto ad un documento, ma non si possono inserire nodi aggiuntivi a questo nodo sino a quando il nodo è associato al docuemnto. Per creare un modo modificabile utilizzare DOMDocument->createComment().
Esempio 1. Esempio di creazione di un nuovo DOMComment
|
(no version information, might be only in CVS)
DOMDocument->__construct() -- Crea un nuovo oggetto DOMDocumentCrea un nuovo oggetto DOMDocument.
Numero di versione del documento come parte della dichiarazione XML.
Codifica del docuemnto utilizzata nella dichisrazione XML.
(no version information, might be only in CVS)
DOMDocument->createAttribute() -- Crea un nuovo attributoQuesta funzione crea una nuova istanza della classe DOMAttr. This node will not show up in the document unless it is inserted with e.g. DOMNode->appendChild().
DOMNode->appendChild() |
DOMDocument->createAttributeNS() |
DOMDocument->createCDATASection() |
DOMDocument->createComment() |
DOMDocument->createDocumentFragment() |
DOMDocument->createElement() |
DOMDocument->createElementNS() |
DOMDocument->createEntityReference() |
DOMDocument->createProcessingInstruction() |
DOMDocument->createTextNode() |
(no version information, might be only in CVS)
DOMDocument->createAttributeNS() -- Crea un nuovo nodo attributo con associato lo spazio dei nomiQuesta funzione crea una nuova istanza della classe DOMAttr. This node will not show up in the document unless it is inserted with e.g. DOMNode->appendChild().
L' URI dello spazio dei nomi.
Il nome del tag e prefisso dell'attributo nella struttura prefix:tagname.
Generato se qualifiedName contiene carattei non validi.
Generato se qualifiedName se è un nome malformato, oppure se qualifiedName ha un prefisso e namespaceURI vale NULL.
DOMNode->appendChild() |
DOMDocument->createAttribute() |
DOMDocument->createCDATASection() |
DOMDocument->createComment() |
DOMDocument->createDocumentFragment() |
DOMDocument->createElement() |
DOMDocument->createElementNS() |
DOMDocument->createEntityReference() |
DOMDocument->createProcessingInstruction() |
DOMDocument->createTextNode() |
(no version information, might be only in CVS)
DOMDocument->createCDATASection() -- Crea un nuovo nodo cdataQuesta funzione crea una nuova istanza della classe DOMCDATASection. This node will not show up in the document unless it is inserted with e.g. DOMNode->appendChild().
DOMNode->appendChild() |
DOMDocument->createAttribute() |
DOMDocument->createAttributeNS() |
DOMDocument->createComment() |
DOMDocument->createDocumentFragment() |
DOMDocument->createElement() |
DOMDocument->createElementNS() |
DOMDocument->createEntityReference() |
DOMDocument->createProcessingInstruction() |
DOMDocument->createTextNode() |
(no version information, might be only in CVS)
DOMDocument->createComment() -- Crea un nuovo nodo di commentoQuesta funzione crea una nuova istanza della classe DOMComment. This node will not show up in the document unless it is inserted with e.g. DOMNode->appendChild().
DOMNode->appendChild() |
DOMDocument->createAttribute() |
DOMDocument->createAttributeNS() |
DOMDocument->createCDATASection() |
DOMDocument->createDocumentFragment() |
DOMDocument->createElement() |
DOMDocument->createElementNS() |
DOMDocument->createEntityReference() |
DOMDocument->createProcessingInstruction() |
DOMDocument->createTextNode() |
(no version information, might be only in CVS)
DOMDocument->createDocumentFragment() -- Crea un nuovo frammento di documentoQuesta funzione crea una nuova istanza della classe DOMDocumentFragment. This node will not show up in the document unless it is inserted with e.g. DOMNode->appendChild().
DOMNode->appendChild() |
DOMDocument->createAttribute() |
DOMDocument->createAttributeNS() |
DOMDocument->createCDATASection() |
DOMDocument->createComment() |
DOMDocument->createElement() |
DOMDocument->createElementNS() |
DOMDocument->createEntityReference() |
DOMDocument->createProcessingInstruction() |
DOMDocument->createTextNode() |
(no version information, might be only in CVS)
DOMDocument->createElement() -- Crea un nuovo nodo elementoQuesta funzione crea una nuova istanza della classe DOMElement. This node will not show up in the document unless it is inserted with e.g. DOMNode->appendChild().
Il nome del tag dell'elemento.
Il valore dell'elemento. Per default si crea un elemento vuoto. Il valore può essere impostato in un secondo momento tramite DOMElement->nodeValue.
Restituisce una nuova istanza della classe DOMElement oppure FALSE in caso di errore.
Esempio 1. Esempio di creazione di un nuovo elemento ed inserimento nel documento come root
Il precedente esempio visualizzerà:
|
DOMNode->appendChild() |
DOMDocument->createAttribute() |
DOMDocument->createAttributeNS() |
DOMDocument->createCDATASection() |
DOMDocument->createComment() |
DOMDocument->createDocumentFragment() |
DOMDocument->createElementNS() |
DOMDocument->createEntityReference() |
DOMDocument->createProcessingInstruction() |
DOMDocument->createTextNode() |
(no version information, might be only in CVS)
DOMDocument->createElementNS() -- Crea un nuovo nodo elemento con associato lo spazio dei nomiQuesta funzione crea un nuovo nodo elemento con associato lo spazio dei nomi. This node will not show up in the document unless it is inserted with e.g. DOMNode->appendChild().
L' URI dello spazio dei nomi.
Un nuome qualificato pe l'elemento del tipo prefix:tagname.
Il valore dell'elemento. Per default si crea un elemento vuoto. Il valore può essere impostato in un secondo momento tramite DOMElement->nodeValue.
Generato se qualifiedName contiene caratteri non validi.
Generato se qualifiedName se è un nome qualificato invalido.
Esempio 1. Esempio di creazione di un nuovo elemento ed inserimento nel documento come root
Il precedente esempio visualizzerà:
|
DOMNode->appendChild() |
DOMDocument->createAttribute() |
DOMDocument->createAttributeNS() |
DOMDocument->createCDATASection() |
DOMDocument->createComment() |
DOMDocument->createDocumentFragment() |
DOMDocument->createElement() |
DOMDocument->createEntityReference() |
DOMDocument->createProcessingInstruction() |
DOMDocument->createTextNode() |
(no version information, might be only in CVS)
DOMDocument->createEntityReference() -- Crea un nuovo nodo riferimento ad entitàQuesta funzione crea una nuova istanza della classe DOMEntityReference. This node will not show up in the document unless it is inserted with e.g. DOMNode->appendChild().
Il contenuto del riferimento all'entità, ad esempio il riferimento all'entità meno & iniziale e ; finale.
DOMNode->appendChild() |
DOMDocument->createAttribute() |
DOMDocument->createAttributeNS() |
DOMDocument->createCDATASection() |
DOMDocument->createComment() |
DOMDocument->createDocumentFragment() |
DOMDocument->createElement() |
DOMDocument->createElementNS() |
DOMDocument->createProcessingInstruction() |
DOMDocument->createTextNode() |
(no version information, might be only in CVS)
DOMDocument->createProcessingInstruction() -- Crea un nuovo nodo PIQuesta funzione crea una nuova istanza della classe DOMProcessingInstruction. This node will not show up in the document unless it is inserted with e.g. DOMNode->appendChild().
Il target delle itrsuzioni di processamento.
Il contenuto della PI.
DOMNode->appendChild() |
DOMDocument->createAttribute() |
DOMDocument->createAttributeNS() |
DOMDocument->createCDATASection() |
DOMDocument->createComment() |
DOMDocument->createDocumentFragment() |
DOMDocument->createElement() |
DOMDocument->createElementNS() |
DOMDocument->createEntityReference() |
DOMDocument->createTextNode() |
(no version information, might be only in CVS)
DOMDocument->createTextNode() -- Crea un nuovo nodo di testoQuesta funzione crea una nuova istanza della classe DOMText. This node will not show up in the document unless it is inserted with e.g. DOMNode->appendChild().
DOMNode->appendChild() |
DOMDocument->createAttribute() |
DOMDocument->createAttributeNS() |
DOMDocument->createCDATASection() |
DOMDocument->createComment() |
DOMDocument->createDocumentFragment() |
DOMDocument->createElement() |
DOMDocument->createElementNS() |
DOMDocument->createEntityReference() |
DOMDocument->createProcessingInstruction() |
(no version information, might be only in CVS)
DOMDocument->getElementById() -- Cerca un elemento con un certo idQuesta funzione è simile a DOMDocument->getElementsByTagName(), ma cerca un elemento per il dato id.
In base allo standard DOM, questa funzione riochiede la presenza di una DTD che definisca l'attributo ID di tipo ID. Occorre validare il documento con DOMDocument->validate() oppure DOMDocument->validateOnParse prima di utilizzare questa funzione.
Esempio 1. Esempio di uso di DOMDocument->getElementById()
Il precedente esempio visualizzerà:
|
(no version information, might be only in CVS)
DOMDocument->getElementsByTagName() -- Cerca tutti gli eleemnti per un dato nome di tagQuesta funzione crea una nuova istanza della classe DOMNodeList contenente gli elementi con il nome tag cercato.
(no version information, might be only in CVS)
DOMDocument->getElementsByTagNameNS() -- Ricerca tutti gli elementi per un dato nome tag nello spazio dei nomi indicato.Restituicse un DOMNodeList contenente tutti gli elementi con il nome e lo spazio dei nomi indicati.
L' URI dello spazio dei nomi degli elementi da cercare. Il valore speciale * indica tutti.
Il nome locale degli elementi da cercare. Il valore speciale * indica tutti.
Esempio 1. Ottienet tutti gli elementi XInclude
Il precedente esempio visualizzerà:
|
(no version information, might be only in CVS)
DOMDocument->importNode() -- Importa un nodo nel documento correnteQuesta funzione restituisce una copia del nodo da importare e lo associa al documento corrente.
Il nodo da importare.
Se impostato a TRUE, questo metodo importerà in modo ricorsivo il sotto-albero di importedNode.
(no version information, might be only in CVS)
DOMDocument->load() -- Carica un documento XML da un fileCarica un documento XML da un file.
Questo metodo può essere richiamato staticamente per caricare e creare un oggetto DOMDocument. L'inbvocazione statica può essere utilizzata quando non occorre impostare le proprietà di DOMDocument prima del caricamento.
(no version information, might be only in CVS)
DOMDocument->loadHTML() -- Carica una pagina HTML da una stringaLa funzione esegue il parsing di una pagina HTML contenuta nella stringa source. A differenza del carico di un documento XML, il documento HTML non deve essere ben formato per potere essere caricato. Questa funzione può essere richiamata staticamente per caricare e creare un oggetto DOMDocument. L'invocazione statica può essere utilizzata quando non debbano essere impostate proprietà per DOMDocument prima del caricamento.
La funzione esegue il parsing del file HTML filename. A differenza del carico di un documento XML, il documento HTML non deve essere ben formato per potere essere caricato.
Questa funzione può essere richiamata staticamente per caricare e creare un oggetto DOMDocument. L'invocazione statica può essere utilizzata quando non debbano essere impostate proprietà per DOMDocument prima del caricamento.
(no version information, might be only in CVS)
DOMDocument->loadXML() -- Carica un documento XML da una stringaCarica un documento XML da una stringa.
Questa funzione può essere richiamata staticamente per caricare e creare un oggetto DOMDocument. L'invocazione statica può essere utilizzata quando non debbano essere impostate proprietà per DOMDocument prima del caricamento.
(no version information, might be only in CVS)
DOMDocument->relaxNGValidate() -- Esegue una validazione relaxNG sul documentoEsegue una validazione relaxNG sul documento in base allo schema RNG dato.
DOMDocument->relaxNGValidateSource() |
DOMDocument->schemaValidate() |
DOMDocument->schemaValidateSource() |
DOMDocument->validate() |
(no version information, might be only in CVS)
DOMDocument->relaxNGValidateSource() -- Esegue una validazione relaxNG sul documentoEsegue una validazione relaxNG sul documento in base alla sorgente RNG data.
DOMDocument->relaxNGValidate() |
DOMDocument->schemaValidate() |
DOMDocument->schemaValidateSource() |
DOMDocument->validate() |
(no version information, might be only in CVS)
DOMDocument->save() -- Scarica l'albero XML interno in un fileCrea un docuemnto XML dalla rappresentazione DOM. Usualmente questa funzione è chiamata dopo la creazione da zero di un nuovo documento DOM come nell'esempio seguente.
La funzione restituisce il numero di byte scritti, oppure FALSE in caso di errore.
Esempio 1. Salvataggio di un albero DOM in un file
|
(no version information, might be only in CVS)
DOMDocument->saveHTML() -- Dumps the internal document into a string using HTML formattingCreates an HTML document from the DOM representation. This function is usually called after building a new dom document from scratch as in the example below.
Esempio 1. Saving a HTML tree into a string
|
(no version information, might be only in CVS)
DOMDocument->saveHTMLFile() -- Dumps the internal document into a file using HTML formattingCreates an HTML document from the DOM representation. This function is usually called after building a new dom document from scratch as in the example below.
Esempio 1. Saving a HTML tree into a file
|
(no version information, might be only in CVS)
DOMDocument->saveXML() -- Dumps the internal XML tree back into a stringCreates an XML document from the DOM representation. This function is usually called after building a new dom document from scratch as in the example below.
Use this parameter to output only a specific node without XML declaration rather than the entire document.
Additional Options. Currently only LIBXML_NOEMPTYTAG is supported.
Esempio 1. Saving a DOM tree into a string
Il precedente esempio visualizzerà:
|
(no version information, might be only in CVS)
DOMDocument->schemaValidate() -- Validates a document based on a schemaValidates a document based on the given schema file.
DOMDocument->schemaValidateSource() |
DOMDocument->relaxNGValidate() |
DOMDocument->relaxNGValidateSource() |
DOMDocument->validate() |
(no version information, might be only in CVS)
DOMDocument->schemaValidateSource() -- Validates a document based on a schemaValidates a document based on a schema defined in the given string.
DOMDocument->schemaValidate() |
DOMDocument->relaxNGValidate() |
DOMDocument->relaxNGValidateSource() |
DOMDocument->validate() |
(no version information, might be only in CVS)
DOMDocument->validate() -- Valida il documento in base alla sua DTDValida il documento in base alla sua DTD.
Si può anche utilizzare la proprietà validateOnParse di DOMDocument per ottenere una validazione DTD.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento. Se il documenti non ha una DTD collegata, questo metodo restituisce FALSE.
Esempio 1. Esempio di validazione con DTD
Si può anche validare il documento mentre lo si carica:
|
DOMDocument->schemaValidate() |
DOMDocument->schemaValidateSource() |
DOMDocument->relaxNGValidate() |
DOMDocument->relaxNGValidateSource() |
(no version information, might be only in CVS)
DOMDocument->xinclude() -- Sostituisce gli XIncludes in un oggetto DOMDocumentSostituisce gli XIncludes in un oggetto DOMDocument.
Nota: Poichè libxml2 risolve automaticamente le entità, quetso metodo può dare risultati inaspettati si il fil eXML incluso ha una DTD collegata.
Esempio 1. Esempio di uso di DOMDocument->xinclude()
Il precedente esempio visualizzerà qualcosa simile a:
|
(no version information, might be only in CVS)
DOMElement->__construct() -- Crea un nuovo oggetto DOMElementCrea un nuovo oggetto DOMElement. Questo oggetto è in sola lettura. Può essere aggiunto al documento, ma nodi addizionali non possono essere aggiunti a questo, fino a quando il nodo è associatoi al docuemnto. Per creare un nodo modificabile utilizzare DOMDocument->createElement() oppure DOMDocument->createElementNS().
Nome del tag dell'elemento. Quando si passa l'URI di uno spazio dei nomi, il nome dell'elemento può avere un prefisso per essere associato all'URI.
Valore dell'elemento.
URI dello spazio dei nomi, usato per creare l'elemento nello spazio dei nomi indicato.
Esempio 1. Creazione di un nuovo DOMElement
|
(no version information, might be only in CVS)
DOMElement->getAttribute() -- Restituisce il valore di un attributoRestituisce il valore dell'attributo con nome name per il nodo corrente.
La funzione restituisce il valore dell'attributo oppure una stringa vuota se non si trova alcun attributo con nome name.
(no version information, might be only in CVS)
DOMElement->getAttributeNode() -- Restituisce il nodo attributoRestituisce il nodo attributo con nome name per l'elemento corrente.
DOMElement->hasAttribute() |
DOMElement->setAttributeNode() |
DOMElement->removeAttributeNode() |
(no version information, might be only in CVS)
DOMElement->getAttributeNodeNS() -- Restituisce un nodo attributoRestituisce il nodo attributo cone nome localName nello spazio dei nomi namespaceURI per il nodo corrente.
DOMElement->hasAttributeNS() |
DOMElement->setAttributeNodeNS() |
DOMElement->removeAttributeNode() |
(no version information, might be only in CVS)
DOMElement->getAttributeNS() -- Restituisce il valore di un attributoRestituisce il valore dell'attributo con nome localName nello spazio dei nomi namespaceURI per il nodo corrente.
Il valore dell'attributo, oppure una stringa vuota nel caso in cui non si trovi un attributo con i dati localName e namespaceURI.
DOMElement->hasAttributeNS() |
DOMElement->setAttributeNS() |
DOMElement->removeAttributeNS() |
(no version information, might be only in CVS)
DOMElement->getElementsByTagName() -- Restituisce gli elementi in base al nome del tagQuesta funzione restituisce una nuova istanza della classe DOMNodeList contenente gli elementi i cui nomi di tag corrispondono al parametro name, nell'ordine in cui sono incontrati durante l'attraversamento dell'albero.
Il nome del tag. Utilizzare "*" per indicare di restituire tutti gli elementi del documento.
Questa funzione crea una nuova istanza della classe DOMNodeList contenente tutti gli elementi trovati.
(no version information, might be only in CVS)
DOMElement->getElementsByTagNameNS() -- Restituisce gli elementi per spazio dei nomi e nome localeQuesta funzione scarica tutti gli elementi con un dato localName e namespaceURI.
URI dello spazio dei nomi.
Nome locale. Utilizzare come nome "*" per restituire tutti gli elementi presenti nell'albero degli elementi.
Questa funzione crea una nuova istanza della classe DOMNodeList contenente tutti gli elementi trovati nell'ordine in cui sono incontrati durante l'atttraversamento dell'albero degli elementi.
(no version information, might be only in CVS)
DOMElement->hasAttribute() -- Verifica se l'attributo esisteIndica se l'attributo name esiste come menbro dell'elemento.
DOMElement->hasAttributeNS() |
DOMElement->getAttribute() |
DOMElement->setAttribute() |
DOMElement->removeAttribute() |
(no version information, might be only in CVS)
DOMElement->hasAttributeNS() -- Verifica se esiste l'attributoIndica se l'attributo nello spazio dei nomi namespaceURI con nome localName esiste come membro dell'elemento.
DOMElement->hasAttribute() |
DOMElement->getAttributeNS() |
DOMElement->setAttributeNS() |
DOMElement->removeAttributeNS() |
Rimuove l'attributo name dall'elemento.
Generato se il nodo non può essere modificato (in sola lettura).
(no version information, might be only in CVS)
DOMElement->removeAttributeNode() -- Rimuove gli attributiRimuove l'attributo oldnode dall'elemento.
Generato se il nodo è in sola lettura.
Generato se oldnode non è un attributo dell'elemento.
DOMElement->hasAttribute() |
DOMElement->getAttributeNode() |
DOMElement->setAttributeNode() |
(no version information, might be only in CVS)
DOMElement->removeAttributeNS() -- Rimuove gli attributiRimuove l'attributo localName nello spazio dei nomi namespaceURI dall'elemento.
(no version information, might be only in CVS)
DOMElement->setAttribute() -- Aggiunge un nuovo attributoImposta l'attributo con nome name al dato valore. Se l'attributo non esiste lo crea.
(no version information, might be only in CVS)
DOMElement->setAttributeNode() -- Aggiunge un nuovo nodo attributo all'elementoAggiunge un nuovo nodo attributo attr all'elemento.
DOMElement->hasAttribute() |
DOMElement->getAttributeNode() |
DOMElement->removeAttributeNode() |
(no version information, might be only in CVS)
DOMElement->setAttributeNodeNS() -- Aggiunge un nuovo nodo attributo all'elementoAggiunge un nuovo nodo attr all'elemento.
DOMElement->hasAttributeNS() |
DOMElement->getAttributeNodeNS() |
DOMElement->removeAttributeNode() |
(no version information, might be only in CVS)
DOMElement->setAttributeNS() -- Aggiunge un nuovo attributoImposta un attributo di nome name nello spazio dei nomi namespaceURI al valore dato. Se l'attributo non esiste viene creato.
URI dello spazio dei nomi.
Nome qualificato dell'attributo, nella forma prefisso:nometag.
Valore dell'attributo.
Generato se il nodo è in sola lettura.
Generato se qualifiedName è un nome qualificato malformato, oppure se qualifiedName ha un prefisso, ma namespaceURI è NULL.
DOMElement->hasAttributeNS() |
DOMElement->getAttributeNS() |
DOMElement->removeAttributeNS() |
(no version information, might be only in CVS)
DOMAttr->__construct() -- Crea un nuovo oggetto DOMEntityReferenceCrea un nuovo oggetto DOMEntityReference.
Esempio 1. Creazione di un nuovo DOMEntityReference
|
(no version information, might be only in CVS)
DOMImplementation->__construct() -- Crea un nuovo oggetto DOMImplementationCrea un nuovo oggetto DOMImplementation.
(no version information, might be only in CVS)
DOMImplementation->createDocument() -- Crea un oggetto DOMDocument del tipo indicato con il suo elemento documentoCrea un oggetto DOMDocument del tipo specificato, con l'elemento documento.
URI dello spazio dei nomi dell'elemento documento da creare.
Nome qualificato dell'elemento documento da creare.
Tipo del documento da creare oppure NULL.
Restituisce un nuovo oggetto DOMDocument. Se namespaceURI, qualifiedName, e doctype sono a null, l'oggetto DOMDocument restituito è vuoto, cioè privo dell'elemento documento.
Generato se doctype è già utilizzato in un documento differente oppure è stato creato con una differente implementazione.
Generato se esiste un errore nello spazio dei nomi indicato da namespaceURI e qualifiedName.
(no version information, might be only in CVS)
DOMImplementation->createDocumentType() -- Crea un oggetto DOMDocumentType vuotoCrea un oggetto DOMDocumentType vuoto. Le dichiarazioni delle entità e notazioni non sono disponibili. L'espansione delle entità e gli attributi di default non sono presenti.
Nome qualificato del tipo documento da creare.
Identificatore pubblico esterno.
Identificatore di sistema esterno.
Esempio 1. Creazione di un documento con una DTD collegata
Il precedente esempio visualizzerà:
|
Generato se vi è un errore nello spazio dei nomi indicato da qualifiedName.
(no version information, might be only in CVS)
DOMImplementation->hasFeature() -- Verifica se l'implementazione DOM ha una specifica caratteristicaVerifica se l'implementazione DOM ha una specifica feature.
Si può avere l'eleneco di tutte le caratteristiche alla sezione Conformance delle specifiche DOM.
Caratteristica da verificare.
Numero di versione della feature da verificare. Nel livello 2 questo parametro può valere 2.0 o 1.0.
Esempio 1. Verifica dell'implementazione DOM
|
(no version information, might be only in CVS)
DOMNamedNodeMap->getNamedItem() -- Recupera un nodo indicandone il nomeRecupera il nodo indicato da nodeName.
Il nodo (di qualsiasi tipo) con il nome richiesto, oppure NULL se non viene trovato.
(no version information, might be only in CVS)
DOMNamedNodeMap->getNamedItemNS() -- Recupera un nodo indicando il nome locale e l'URI dello spazio dei nomiRecupera il nodo indicato da localName e namespaceURI.
URI dello spazio dei nomi del nodo da cercare
Nome locale del nodo da cercare.
Un nodo (di qualsiasi tipo) con il nome locale ed l'URI dello spazio dei nomi richiesti, oppure NULL se non viene trovato nulla.
(no version information, might be only in CVS)
DOMNamedNodeMap->item() -- Recupera un nodo tramite il suo indiceRecupera un nodo tramite l'indice index all'interno dell'oggetto DOMNamedNodeMap.
Il nodo alla posizione indexnella tabella, oppure NULL se non si tratta di un indice valido (maggiore o uguale al numero dei nodi in questa tabella).
(no version information, might be only in CVS)
DOMNode->appendChild() -- Aggiunge un nuovo nodo figlio alla fine dei nodi figliQuesta funzione accoda un nodo figlio ad una lista esistente di nodi figlio oppure crea una nuova lista. Il nodo figlio può essere creato, ad esempio, con DOMDocument->createElement(), DOMDocument->createTextNode() ecc. oppure semplicemente utilizzando un'altro nodo.
Generato se questo nodo è in sola lettura, oppure se il nodo genitore del nodo da inserire è in sola lettura.
Generato se questo nodo è del tipo che non ammette figli del tipo di newnode, oppure se il nodo da aggiungere è uno dei genitori del nodi o di se stesso.
Generato se newnode è stato creato in un documento differente rispetto al nodo che crea questo.
Indica se occorre copiare tutti i nodi sottostanti. Questo parametro, opzionale, ha come default FALSE.
(no version information, might be only in CVS)
DOMNode->hasAttributes() -- Verifica se un nodo ha degli attributiQuesta funzione verifica se un nodo ha degli attributi. Il nodo verificato deve essere di tipo XML_ELEMENT_NODE.
(no version information, might be only in CVS)
DOMNode->hasChildNodes() -- Verifica se un nodo ha nodi figliQuesta funzione verifica se un nodo ha nodi figli.
(no version information, might be only in CVS)
DOMNode->insertBefore() -- Aggiunge un nuovo nodo figlio prima del riferimentoQuesta funzione inserisce un nuovo nodo prima del nodo di riferimento. Se si prevede di fare ulteriori aggiunte al nodo aggiunto, utilizzare il nodo restituito.
Il nuovo nodo.
Nodo di riferimento. Se non viene fornito, newnode viene accodato ai nodi figli.
Generato se il nodo è in sola lettura o se il precedente nodo padre del nodo da aggiungere è in sola lettura.
Generato se questo nodo è di un tipo che non permette l'aggiunta di nodi figli del tipo di newnode, o se il nodo da aggiungere è uno dei genitori di questo nodo, oppure se si tratta proprio di questo nodo.
Generato se newnode è stato creato in un docuemnto differente rispetto al documento in cui è sttao creato questo nodo.
Generato se refnode non è un nodo figlio di questo nodo.
(no version information, might be only in CVS)
DOMNode->isSameNode() -- Indica se due nodi sono il medesimo nodoQuesta funzione indica se due nodi sono il medesimo nodo. Il confronto NON è basato sul contenuto.
(no version information, might be only in CVS)
DOMNode->isSupported() -- Verifica se una caratteristica è supportata dalla versione indicataVerifica se una feature è supportata dalla version indicata.
Caratteristica da verificare. Vedere l'esempio di DOMImplementation->hasFeature() per avere l'elenco delle caratteristiche.
Numero di versione della feature da verificare.
(no version information, might be only in CVS)
DOMNode->lookupNamespaceURI() -- Restituisce l'URI dello spazio dei nomi in base al prefissoRestituisce l'URI dello spazio dei nomi del nodo in base al prefisso prefix.
(no version information, might be only in CVS)
DOMNode->lookupPrefix() -- Resituisce il prefisso dello spazio dei nomi in base all'URI dello spazio dei nomiResituisce il prefisso dello spazio dei nomi in base all'URI dello spazio dei nomi.
(no version information, might be only in CVS)
DOMNode->removeChild() -- Rimuove un nodo figlio dalla lista dei nodi figliQuesta funzione rimuove un nodo figlio dalla lista dei nodi figli.
Se si riesce a rimuovere il nodo figlio, la funzione restituisce il vecchio nodo figlio.
Generato se il nodo è in sola lettura.
Generato se oldnode non è un figlio di questo nodo.
Nel seguente esempio si rimuoverà il nodo 'chapter' dal nostro documento XML.
Esempio 1. Rimozione di un nodo figlio
Il precedente esempio visualizzerà:
|
Questa funzione sostituisce il nodo figlio oldnode con il nuovo nodo fornito. Se il nuovo nodo è già un nodo figlio, questo non verrà inserito una seconda volta. Se la sostituzione ha avuto successo, la funzione restituisce il vecchio nodo.
Il nuovo nodo. Deve essere membro del docuemnto di destinazione, ad esempio creato da uno dei metodi DOMDocument->createXXX() oppure importato nel documento con DOMDocument->importNode().
Il vecchio nodo.
Generato se questo nodo è in sola lettura oppure se il precdente padre del nodo da inserire è in sola lettura.
Generato se il nodo è di un tipo che non ammette nodi figli del tipo di newnode, oppure se il nodo da inserire è uno dei padri del nodo, oppure se è il nodo stesso.
Generato se newnode è stato creato in un docuemnto differente rispetto al documento in cui è stato creato il nodo.
Generato se oldnode non è figlio del nodo.
(no version information, might be only in CVS)
DOMNodelist->item() -- Recupera il nodo indicato dall'indiceTrova il nodo indicato dall'indice index all'interno di un oggetto DOMNodeList.
Suggerimento: Se occorre conoscere il numero di nodi di una collezzione utilizzare la prorpietà length dell'oggetto DOMNodeList.
Il nodo alla posizione index in DOMNodeList, oppure NULL se non è un indice valido.
Esempio 1. Attraversamento di tutti gli elementi di una tabella
Oppure si può utilizzare foreach, che è molto pratico:
Il precedente esempio visualizzerà:
|
(no version information, might be only in CVS)
DOMProcessingInstruction->__construct() -- Crea un nuovo oggetto DOMProcessingInstructionCrea un nuovo oggetto DOMProcessingInstruction. Questo oggetto è in sola lettura. Può essere aggiunto al documento, ma non possono essere inseriti nodi aggiuntivi fino a quando il nodo è associato al documento. Per creare un nodo modificabile utilizzare DOMDocument->createProcessingInstruction().
Nome del tag dell'istruzione di processamento.
Valore dell'istruzione di processamento.
Esempio 1. Creazione di un nuovo DOMProcessingInstruction
|
(no version information, might be only in CVS)
DOMText->__construct() -- Crea un nuovo oggetto DOMText
Valore del nodo di testo. Se non fornito, sarà creato un nodo con il testo vuoto.
Esempio 1. Creazione di un nuovo DOMText
|
(no version information, might be only in CVS)
DOMText->isWhitespaceInElementContent() -- Indica se questo nodo di testo contiene spaziIndica se questo nodo di testo contiene spazi. Si determina se un nodo di testo contiene spazi durante la fase di caricamento del documento.
(no version information, might be only in CVS)
DOMText->splitText() -- Spezza il nodo in due all'offset specificatoSpezza questo nodo in due all'offset indicato, mantenendo entrambi nell'albero come nodi fratelli.
Dopo la divisione, questo nodo conterrà tutto il testo fino a offset. Se il nodo originale ha un nodo genitore, allora il nuovo nodo sarà inserito come successivo al nodo originale. Nel caso in cui offset sia uguale alla lunghezza del nodo, il nuovo nodo non conterrà dati.
(no version information, might be only in CVS)
DOMXPath->__construct() -- Crea un nuovo oggetto DOMXPath(no version information, might be only in CVS)
DOMXPath->evaluate() -- Valuta l'espressione XPath data e restituisce un risultato se possibileEsegue l'espressione XPath data e restituisce un risultato se possibile
L'espressione XPath da eseguire.
Il parametro opzinale contextnode serve per indicare di eseguire query XPath relative. Per default le query sono relative all'elemento radice.
Restituisce un risultato oppure un oggetto DOMNodeList contenente tutti i nodi che soddisfano la query XPath .
Esempio 1. Ottenere il numero dei libri inglesi
Il precedente esempio visualizzerà:
|
Esegue la query XPath data.
La query XPath da eseguire.
Il parametro opzinale contextnode serve per indicare di eseguire query XPath relative. Per default le query sono relative all'elemento radice.
Restituisce un oggetto DOMNodeList contenente tutti i nodi che soddisfano la condizione expression. Qualsiasi espressione che non restituisce nodi creerà un DOMNodeList vuoto.
Esempio 1. Ottenere il numero dei libri inglesi
Il precedente esempio visualizzerà:
Possiamo utilizzare il parametro contextnode per ridurre l'espressione:
|
(no version information, might be only in CVS)
DOMXPath->registerNamespace() -- Registra lo spazio dei nomi nell'oggetto DOMXpathRegistra lo spazio dei nomi namespaceURI e prefix nell'oggetto DOMXpath.
Questa funzione prende il nodo node della classe SimpleXML e lo converte in un nodo DOMElement. Questo nuovo oggetto può essere utilizzato come nodo DOMElement nativo.
Esempio 1. Importare SimpleXML nel DOM con dom_import_simplexml()
|
Nella versione 4.3.0 di PHP l'estensione DOM XML è stata rivista in modo da fornire una migliore adesione allo standard DOM. Il modulo contiene ancora diverse vecchie funzioni, ma non dovrebbero essere più usate. Specialmente quelle funzioni non orientate agli oggetti.
Questo modulo permette di operare con un documento XML utilizzando API DOM. Inoltre viene fornita una funzione, domxml_xmltree(), per convertire l'intero documento XML in un albero di oggetti PHP. Attualmente questo albero dovrebbe essere considerato di sola lettura, è possibile modificarlo, ma questa operazione non avrebbe senso dato che la funzione DomDocument_dump_mem() non può essere applicata all'albero. Pertanto se si desidera leggere un file XML e scriverne una versione modificata, occorre utilizzare le funzioni DomDocument_create_element(), DomDocument_create_text_node(), set_attribute(), ecc. ed infine DomDocument_dump_mem().
Nota: Questo modulo è stato spostato nel repository PECL e non sarà più rilascio con il PHP dalla versione 5.0.0.
Questo modulo utilizza la libreria GNOME XML library. Fare il download ed installare questa libreria. Occorre avere almeno la libxml-2.4.14. Per potere utilizzare le caratteristiche previste nel DOM XSLT occorre utilizzare libxslt library ed EXSLT enhancements da http://www.exslt.org/. Scaricare ed installare queste librerie se si prevede di utilizzare la funzioni avanzate di XSLT. Occorre almeno la versione libxslt-1.0.18.
This PECL extension is not bundled with PHP. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: http://pecl.php.net/package/domxml.
In PHP 4 this PECL extensions source can be found in the ext/ directory within the PHP source or at the PECL link above. Questo modulo è disponibile soltanto se il PHP è stato configurato con --with-dom=[DIR]. Aggiungere --with-dom-xslt[=DIR] per includere il supporto al DOM XSLT support. DIR indica la directory in cui è installato libxslt. Aggiungere --with-dom-exslt[=DIR] per includere il supporto al DOM EXSLT, dove DIR indica la directory in cui è installato libexslt.
Gli utenti Windows devono abilitare php_domxml.dll dal php.ini per potere utilizzare queste funzioni. In PHP 4 this DLL resides in the extensions/ directory within the PHP Windows binaries download. You may download this PECL extension DLL from the PHP Downloads page or at http://snaps.php.net/. Inoltre, per potere utilizzare queste funzioni, occorre che una DLL aggiuntiva sia presente nella PATH del sistema. In PHP 4 questa DLL si trova nella directory dlls/. Il suo nome: Per PHP <= 4.2.0, è libxml2.dll. Per PHP >= 4.3.0, è iconv.dll. E dal PHP 5.0.0 iconv è compilata nell'eseguibile PHP per Windows, percui non vi è più bisogno di dll aggiuntive.
Esistono alcune funzioni che non rientrano nello standard DOM e quindi non dovrebbero essere più utilizzate come evidenziato nella tabella seguente. La funzione DomNode_append_child() ha modificato il suo comportamento. Attualmente aggiunge un figlio e non un elemento fratello. Se ciò crea problemi alle applicazioni si può usare la funzione non DOM
Tabella 1. Funzioni deprecate e loro sostituti
Vecchia funzione | Nuova funzione |
---|---|
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() seguita da DomNode_append_child() |
DomDocument_dtd | DomDocument_doctype() |
DomDocument_root | DomDocument_document_element() |
DomDocument_children | DomNode_child_nodes() |
DomDocument_imported_node | Nessun sostituto. |
DomNode_add_child | Creare un nuovo nodo con, ad esempio, DomDocument_create_element() e aggiungere il figlio con DomNode_append_child(). |
DomNode_children | DomNode_child_nodes() |
DomNode_parent | DomNode_parent_node() |
DomNode_new_child | Creare un nuovo nodo con, ad esempio, DomDocument_create_element() e aggiungere il figlio con DomNode_append_child(). |
DomNode_get_content | Il contenuto è semplicemente un nodo di testo ed è accessibile tramite DomNode_child_nodes(). |
DomNode_set_content | Il contenuto è semplicemente un nodo di testo e può essere aggiunto con DomNode_append_child(). |
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Tabella 2. Costanti XML
Costante | Valore | Descrizione |
---|---|---|
XML_ELEMENT_NODE (integer) | 1 | Il nodo è un elemento |
XML_ATTRIBUTE_NODE (integer) | 2 | Il nodo è un attributo |
XML_TEXT_NODE (integer) | 3 | Il nodo è un segmento di testo |
XML_CDATA_SECTION_NODE (integer) | 4 | |
XML_ENTITY_REF_NODE (integer) | 5 | |
XML_ENTITY_NODE (integer) | 6 | Il nodo è un'entità come, ad esempio, |
XML_PI_NODE (integer) | 7 | Il nodo è una istruzione di processamento |
XML_COMMENT_NODE (integer) | 8 | Il nodo è un commento |
XML_DOCUMENT_NODE (integer) | 9 | Il nodo è un documento |
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) |
Le API di questo modulo aderiscono il più possibile allo standard DOM di livello 2. Di conseguenza le API sono completamente orientate agli oggetti. Si ritiene una buona idea avere disponibile lo standard DOM quando si utilizza questo modulo. Sebbene le API siano orientate agli oggetti, vi sono alcune funzioni che possono essere richiamate in modo non orientato agli oggetti, passando l'oggetto su cui operare come primo argomento. Queste funzioni sono state mantenute per compatibilità verso le vecchie versioni del modulo, ma non se ne incoraggia l'uso nello sviluppo di nuovi prodotti.
Queste API differiscono della API DOM ufficiali per due aspetti. Primo, gli attributi della classe sono implermentati come funzioni con il medesimo nome e, secondo, i nomi delle funzioni seguono la convenzione del PHP. Questo significa che la funzione DOM lastChild() sarà chiamata last_child().
In questo modulo sono definite diverse classi, queste saranno elencate - compresi i loro metodi - nella seguente tabella. Le classi con un equivalente nello standard DOM sono chiamate DOMxxx.
Tabella 3. Elenco delle classi
Nome della classe | Classe genitrice |
---|---|
DomAttribute | DomNode |
DomCData | DomNode |
DomComment | DomCData : DomNode |
DomDocument | DomNode |
DomDocumentType | DomNode |
DomElement | DomNode |
DomEntity | DomNode |
DomEntityReference | DomNode |
DomProcessingInstruction | DomNode |
DomText | DomCData : DomNode |
Parser | Attualmente chiamata DomParser |
XPathContext |
Tabella 4. Classe DomDocument (DomDocument : DomNode)
Metodi | Funzioni | Note |
---|---|---|
doctype | DomDocument_doctype() | |
document_element | 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() | non standard DOM |
dump_file | DomDocument_dump_file() | non standard DOM |
html_dump_mem | DomDocument_html_dump_mem() | non standard DOM |
xpath_init | xpath_init | non standard DOM |
xpath_new_context | xpath_new_context | non standard DOM |
xptr_new_context | xptr_new_context | non standard DOM |
Tabella 5. Classe DomElement (DomElement : DomNode)
Metodo | Funzioni | Note |
---|---|---|
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() |
Tabella 6. Classe DomNode
Metodo | Note |
---|---|
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() | non standard DOM. Questa funzione emula il comportamento di DomNode_append_child(). |
DomNode_remove_child() | |
DomNode_has_child_nodes() | |
DomNode_has_attributes() | |
DomNode_clone_node() | |
DomNode_attributes() | |
DomNode_unlink_node() | non standard DOM |
DomNode_replace_node() | non standard DOM |
DomNode_set_content() | non standard DOM, deprecata |
DomNode_get_content() | non standard DOM, deprecata |
DomNode_dump_node() | non standard DOM |
DomNode_is_blank_node() | non standard DOM |
Tabella 7. Classe DomAttribute (DomAttribute : DomNode)
Metodo | Note | |
---|---|---|
name | DomAttribute_name() | |
value | DomAttribute_value() | |
specified | DomAttribute_specified() |
Tabella 8. Classe DomProcessingInstruction (DomProcessingInstruction : DomNode)
Metodo | Funzione | Note |
---|---|---|
target | DomProcessingInstruction_target() | |
data | DomProcessingInstruction_data() |
Tabella 10. Classe XPathContext
Metodo | Funzione | Note |
---|---|---|
eval | XPathContext_eval() | |
eval_expression | XPathContext_eval_expression() | |
register_ns | XPathContext_register_ns() |
Tabella 11. Classe DomDocumentType (DomDocumentType : DomNode)
Metodo | Funzione | Note |
---|---|---|
name | DomDocumentType_name() | |
entities | DomDocumentType_entities() | |
notations | DomDocumentType_notations() | |
public_id | DomDocumentType_public_id() | |
system_id | DomDocumentType_system_id() | |
internal_subset | DomDocumentType_internal_subset() |
La classe DomDtd è derivata da DomNode. Mentre DomComment è derivata da DomCData
Diversi esempi presenti in questo manuale richiedono un testo XML. Anzichè ripetere questo testo in ogni esempio, si inserirà il testo in un file che verrà incluso in ogni esempio. Questo file di include verrà illustrato nel seguente esempio. Si può anche creare un documento XML e leggerlo con DomDocument_open_file().
Esempio 1. File di include example.inc con testo XML
|
(no version information, might be only in CVS)
DomAttribute->name -- Restituisce il nome di un attributoLa funzione restituisce il nome di un attributo.
Vedere anche domattribute_value() per un esempio.
(no version information, might be only in CVS)
DomAttribute->set_value -- Sets the value of an attributeThis function sets the value of an attribute.
(no version information, might be only in CVS)
DomAttribute->specified -- Verifica se l'attributo è presenteRifarsi allo standard DOM per una descrizione dettagliata.
(no version information, might be only in CVS)
DomAttribute->value -- Restituisce il valore di un attributoQuesta funzione restituisce il valore di un attributo.
Esempio 1. Ottenere tutti gli attributi di un nodo
Il precedente esempio visualizzerà:
|
Vedere anche domattribute_name().
(no version information, might be only in CVS)
DomDocument->add_root -- Aggiunge un nodo radice [deprecated]Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Aggiunge un nodo radice ad un documento DOM e restituisce il nuovo nodo. Il nome dell'elemento viene passato come parametro.
(no version information, might be only in CVS)
DomDocument->create_attribute -- Crea un nuovo attributoQuesta funzione restituisce una nuova istanza della classe DomAttribute. Il nome dell'attributo viene passato come primo parametro. Mentre il valore viene passato nel secondo parametro. Questo nodo non sarà presente nel documento fino a quando non viene inserito con funzioni tipo domnode_append_child().
La funzione restituisce FALSE se si verifica un errore.
Vedere anche domnode_append_child(), domdocument_create_element(), domdocument_create_text(), domdocument_create_cdata_section(), domdocument_create_processing_instruction(), domdocument_create_entity_reference() e domnode_insert_before().
(no version information, might be only in CVS)
DomDocument->create_cdata_section -- Crea un nuovo nodo cdataQuesta funzione restituisce una nuova istanza della classe DomCData. Il contenuto del nodo cdata viene passato tramite il parametro. Questo nodo non sarà presente nel documento fino a quando non viene inserito con funzioni tipo domnode_append_child().
La funzione restituisce FALSE se si verifica un errore.
Vedere anche domnode_append_child(), domdocument_create_element(), domdocument_create_text(), domdocument_create_attribute(), domdocument_create_processing_instruction(), domdocument_create_entity_reference() e domnode_insert_before().
Questa funzione restituisce una nuova istanza della classe DomComment. Il contenuto del commento viene fornito tramite il parametro. Questo nodo non sarà presente nel documento fino a quando non viene inserito con funzioni tipo domnode_append_child().
La funzione restituisce FALSE se si verifica un errore.
Vedere anche domnode_append_child(), domdocument_create_element(), domdocument_create_text(), domdocument_create_attribute(), domdocument_create_processing_instruction(), domdocument_create_entity_reference() e domnode_insert_before().
(no version information, might be only in CVS)
DomDocument->create_element_ns -- Crea un nodo elemento con il relativo spazio dei nomiQuesta funzione restituisce una nuova istanza della classe DomElement. Il nome del tag dell'elemento viene fornito tramite il parametro nome. L'URI dello spazio dei nomi vene passato tramite il parametro uri. Se nel nodo radice del documento esiste già uno spazio dei nomi con il medesimo URI, si utilizza il prefisso di questo, altrimenti si utilizzerà quello fornito tramite il parametro opzionale prefix oppure ne verrà generato uno casuale. Questo nodo non sarà presente nel documento fino a quando non viene inserito con funzioni tipo domnode_append_child().
La funzione restituisce FALSE se si verifica un errore.
Vedere anche 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() e domnode_insert_before().
La funzione restituisce una nuova istanza della classe DomElement. Il nome del tag dell'elemento viene passato tramite il parametro. Questo nodo non sarà presente nel documento fino a quando non viene inserito con funzioni tipo domnode_append_child().
La funzione restituisce FALSE se si verifica un errore.
Vedere anche domdocument_create_element_ns(), domnode_append_child(), domdocument_create_text(), domdocument_create_comment(), domdocument_create_attribute(), domdocument_create_processing_instruction(), domdocument_create_entity_reference() e domnode_insert_before().
Questa funzione restituisce una nuova istanza della classe DomEntityReference. Il contenuto dell'entità è passato tramite il parametro. Questo nodo non sarà presente nel documento fino a quando non viene inserito con funzioni tipo domnode_append_child().
La funzione restituisce FALSE se si verifica un errore.
Vedere anche domnode_append_child(), domdocument_create_element(), domdocument_create_text(), domdocument_create_cdata_section(), domdocument_create_processing_instruction(), domdocument_create_attribute() e domnode_insert_before().
(no version information, might be only in CVS)
DomDocument->create_processing_instruction -- Crea un nuovo nodo PIQuesta funzione restituisce una nuova istanza della classe DomCData. Il contenuto della PI viene passato tramite il parametro.Questo nodo non sarà presente nel documento fino a quando non viene inserito con funzioni tipo domnode_append_child().
La funzione restituisce FALSE se si verifica un errore.
Vedere anche domnode_append_child(), domdocument_create_element(), domdocument_create_text(), domdocument_create_cdata_section(), domdocument_create_attribute(), domdocument_create_entity_reference() e domnode_insert_before().
(no version information, might be only in CVS)
DomDocument->create_text_node -- Crea un nodo di testoQuesta funzione restituisce una nuova istanza della classe DomText. Il testo del nodo viene passato tramite il parametro. Questo nodo non sarà presente nel documento fino a quando non viene inserito con funzioni tipo domnode_append_child().
La funzione restituisce FALSE se si verifica un errore.
Vedere anche domnode_append_child(), domdocument_create_element(), domdocument_create_comment(), domdocument_create_text(), domdocument_create_attribute(), domdocument_create_processing_instruction(), domdocument_create_entity_reference() e domnode_insert_before().
(no version information, might be only in CVS)
DomDocument->doctype -- Restituisce il tipo di documentoQuesta funzione restituisce una nuova istanza della classe DomDocumentType. Nelle versioni di PHP antecedenti al 4.3 questa classe era chiamata Dtd, ma lo standard DOM non riconosce tale classe.
Vedere anche i metodi della classe DomDocumentType.
(no version information, might be only in CVS)
DomDocument->document_element -- Restituisce il nodo radiceQuesta funzione restituisce il nodo radice di un documento.
Nell'esempio seguente la funzione restituisce l'elemento con nome CHAPTER. L'altro nodo -- the comment -- non viene restituito.
Esempio 1. Recupero dell'elemento radice
Il precedente esempio visualizzerà:
|
(no version information, might be only in CVS)
DomDocument->dump_file -- Scarica in un file l'albero XML internoLa funzione crea un documento XML dalla rappresentazione DOM. Solitamente questa funzione viene richiamata dopo avere creato da zero un nuovo documento XML, come nell'esempio seguente. Il parametro formato specifica se l'output debba essere ben formattato o meno. Il primo parametro specifica il nome del file ed il secondo se debba essere compresso o meno.
Esempio 1. Creazione dell'intestazione di un documento HTML
|
Vedere anche domdocument_dump_mem() e domdocument_html_dump_mem().
(no version information, might be only in CVS)
DomDocument->dump_mem -- Scarica in una stringa la struttura XML internaAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
La funzione crea un docuemnto XML dalla rappresentazione DOM. Solitamente si richiama questa funzione dopo avere creato un nuovo documento DOM da zero, come nell'esempio seguente. Il parametro formato specifica se l'output debba essere ben formattato o meno.
Esempio 1. Creazione dell'intestazione di un documento HTML
|
Nota: Il primo parametro è stato inserito nella versione 4.3.0 di PHP.
Vedere anche domdocument_dump_file() e domdocument_html_dump_mem().
(no version information, might be only in CVS)
DomDocument->get_element_by_id -- Ricerca di un elemento per idQuesta funzione è simile a domdocument_get_elements_by_tagname() ma ricerca un elemento per un dato id. In accordo con lo standard DOM, è richiesto un DTD che definisca l'attributo ID essere di tipo ID, sebbene l'implementazione corrente ricerchi semplicemente il testo "//*[@ID = '%s']". Ciò non è aderente allo standard DOM che richiede di restituire null se non è noto quale sia l'attributo di tipo id. Questo comportamento sta per essere corretto, pertanto non basarsi sull'implementazione odierna.
Vedere anche domdocument_get_elements_by_tagname()
(no version information, might be only in CVS)
DomDocument->get_elements_by_tagname -- Restituisce un elemento dato il tag
Vedere anche domdocument_add_root()
(no version information, might be only in CVS)
DomDocument->html_dump_mem -- Scarica la struttura XML interna in una stringa come HTMLLa funzione crea un documento HTML dalla rappresentazione DOM. Solitamente si richiama questa funzione dopo avere costruito un nuovo documento DOM da zero, come nell'esempio seguente.
Esempio 1. Creazione dell'intestazione di un documento HTML
Il precedente esempio visualizzerà:
|
Vedere anche domdocument_dump_file() e domdocument_html_dump_mem().
(no version information, might be only in CVS)
DomDocument->xinclude -- Sostituisce gli XIncludes in un oggetto DomDocumentAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Questa funzione sostituisce gli XIncludes in un oggetto DomDocument.
Esempio 1. Sostituzione di Xinclude
Il precedente esempio visualizzerà:
Se include.xml non esiste si avrà::
|
(no version information, might be only in CVS)
DomDocumentType->entities -- Restituisce l'elenco delle entità
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
DomDocumentType->internal_subset -- Restituisce un subset interno
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
DomDocumentType->name -- Restituisce il nome del tipo documentoQuesta funzione restituisce il nome del tipo documento.
(no version information, might be only in CVS)
DomDocumentType->notations -- Restituisce la lista delle notazioni
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
DomDocumentType->public_id -- Restituisce l'identificatore pubblico del tipo documentoQuesta funzione restituisce l'identificatore pubblico del tipo documento.
Il seguente esempio non visualizza niente.
(no version information, might be only in CVS)
DomDocumentType->system_id -- Restituisce l'identificativo di sistema del tipo documentoRestituisce l'identificativo di sistema del tipo documento.
Esempio 1. Recupero dell'identificativo di sistema
Il precedente esempio visualizzerà:
|
(no version information, might be only in CVS)
DomElement->get_attribute_node -- Restituisce il nodo dell'attributo datoRestituisce il nodo dell'attributo indicato da name nell'elemento corrente. Il parametro name distingue tra minuscole e maiuscole.
Se non si trova alcun attributo con il nome dato, la funzione restituisce FALSE
Esempio 1. Ottenere un nodo attributo
|
(no version information, might be only in CVS)
DomElement->get_attribute -- Restituisce il valore di un attributoLa funzione restituisce l'attributo chiamato nome del nodo corrente.
(PHP >= 4.3 solo) Se non si trova alcun attributo con il nome dato, la funzione restituisce una stringa vuota.
Vedere anche domelement_set_attribute()
(no version information, might be only in CVS)
DomElement->get_elements_by_tagname -- Restituisce l'elemento con il tag datoQuesta funzione restituisce un array con tutti gli elementi che hanno come nome del tag nome. Ogni elemento dell'array è un oggetto DomElement.
Esempio 1. Ottenere il contenuto
|
(no version information, might be only in CVS)
DomElement->has_attribute -- Verifica l'esistenza dell'attributo
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Imposta l'attributo chiamato nome al valore fornito. Se l'attributo non esiste lo crea.
Vedere anche domelement_get_attribute()
(no version information, might be only in CVS)
DomElement->tagname -- Restituisce il nome dell'elemento correnteReturns the name of the current node. Chiamare questa funzione è come accedere alla proprietà tagname del nodo corrente, o chiamare DomElement->node_name().
(no version information, might be only in CVS)
DomNode->add_namespace -- Aggiunge la dichiarazione dello spazio dei nomi ad un nodo
Vedere anche domdocument_create_element_ns() e domnode_set_namespace()
Questa funzione accoda un nodo figlio ad un elenco pre-esistente di figli oppure crea una nuova lista di figli. Il nodo figlio può essere creato con funzioni tipo domdocument_create_element(), domdocument_create_text() ecc. oppure usando un qualsiasi altro nodo.
(PHP < 4.3) Prima che sia aggiunto un nuovo nodo questo viene duplicato. Quindi il nuovo nodo è una nuova copia che può essere modificata senza variare il nodo passato alla funzione. Se il nodo ha dei nodi figli, anche questi saranno duplicati, ciò rende facile duplicare grandi parti di un documento XML. Il valore restituito è il nodo figlio accodato. Se si prevede di fare ulteriori modifiche al nodo aggiunto, occorre usare il nodo restituito.
(PHP 4.3.0/4.3.1) Il nuovo nodo figlio nuovo_nodo viene prima rimosso dal contesto esistente, se ne è già un figlio di DomNode. Quindi viene mosso e non più copiato.
(PHP >= 4.3.2) Il nuovo nodo figlio nuovo_nodo viene prima rimosso dal contesto esistente, se ne esiste uno nel documento. Quindi viene mosso e non più copiato. Questo comportamento si attiene alle specifiche W3C. Se si desidera duplicare una grande parte di un documento XML, occorre utilizzare DomNode->clone_node() prima di accodare il nodo.
Nel seguente esempio si accoderà un nuovo nodo ad un documento e si imposterà l'attributo "align" a "left".
Esempio 3. Aggiunta di un nodo figlio
|
Vedere anche domnode_insert_before() e domnode_clone_node().
Questa funzione aggiunge un nodo di pari livello rispetto ad un nodo esistente. Il nodo figlio può essere creato con funzioni del tipo domdocument_create_element(), domdocument_create_text() ecc. oppure utilizzando un'altro nodo.
Prima dell'aggiunta come nuovo nodo fratello, il nodo viene duplicato. Quindi il nuovo nodo figlio è una nuova copia dell'originale e pertanto, può essere modificato senza modificare il nodo di partenza passato alla funzione. Se il nodo fornito, a sua volta, ha dei nodi figli, pure questi saranno duplicati, in questo modo è abbastanza semplice duplicare grandi parti di un documento XML. La funzione restituisce il nodo aggiunto. Se in seguito occorre modificare il nodo fratello che si è aggiunto, occorre utilizzare il nodo restituito.
Questa funzione è stata aggiunta per replicare il comportamento di domnode_append_child() che si ha fino alla versione 4.2 di PHP.
Vedere anche domnode_append_before().
(no version information, might be only in CVS)
DomNode->attributes -- Restituisce la lista degli attributiQuesta funzione restituisce la lista degli attributi se il nodo è di tipo XML_ELEMENT_NODE.
(PHP >= 4.3 solo) Se non si trovano attributi, la funzione restituisce NULL.
(no version information, might be only in CVS)
DomNode->child_nodes -- Restituisce i figli di un nodoRestituisce tutti i nodi figlio del nodo.
Vedere anche domnode_next_sibling() e domnode_previous_sibling().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Vedere anche domdocument_dump_mem().
(no version information, might be only in CVS)
DomNode->first_child -- Restituisce il primo nodo figlioRestituisce il primo nodo figlio.
(PHP >= 4.3 solo) Se non si trova il primo figlio, si restituisce NULL.
Vedere anche domnode_last_child(), domnode_next_sibling() e domnode_previous_sibling().
(no version information, might be only in CVS)
DomNode->get_content -- Restituisce il contenuto del nodoQuesta funzione restituisce il contenuto del nodo
Esempio 1. Ottenere il contenuto di un nodo
|
(no version information, might be only in CVS)
DomNode->has_attributes -- Verifica se il nodo ha attributiQuesta funzione verifica se il nodo ha attributi.
Vedere anche domnode_has_child_nodes().
(no version information, might be only in CVS)
DomNode->has_child_nodes -- Verifica se esistono nodi figlioQuesta funzione verifica se il nodo ha nodi figlio.
Vedere anche domnode_child_nodes().
(no version information, might be only in CVS)
DomNode->insert_before -- Inserisce un nuovo nodo come figlioQuesta funzione inserisce il nuovo_nodo a destra rispetto al nodo_riferimento. La funzione restituisce il nodo inserito. Occorre utilizzare questo valore se si intende apportare nuove modifiche al nodo appena accodato.
(PHP >= 4.3 solo) Se nuovo_nodo è già parte del documento, prima questo verrà scollegato dal contesto esistente. Se nodo_riferimento vale NULL, allora nuovo_nodo sarà inserito alla fine della lista dei nodi figlio.
La funzione domnode_insert_before() è molto simile a domnode_append_child() come illustrato nel seguente esempio nel quale si ha lo stesso comportamento visto nell'esempio di domnode_append_child().
Esempio 1. Aggiunta di un nodo figlio
|
Vedere anche domnode_append_child().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
DomNode->last_child -- Restituisce l'ultimo nodo figlio del nodoRestituisce l'ultimo nodo figlio del nodo.
(PHP >= 4.3 solo) Se non si trova l'ultimo figlio, si restituisce NULL.
Vedere anche domnode_first_child(), domnode_next_sibling() e domnode_previous_sibling().
(no version information, might be only in CVS)
DomNode->next_sibling -- Restituisce il successivo fratello del nodoRestituisce il nodo di pari livello successivo al nodo corrente. Se non ci sono nodi successivi la funzione restituisce FALSE (< 4.3) oppure null (>= 4.3). Si può utilizzare questa funzione per passare in rassegna tutti i figli di un nodo, come illustrato nell'esempio.
Esempio 1. Rassegna dei nodi figlio
|
Vedere anche domnode_previous_sibling().
Restituisce il nome del nodo. Il nome ha diversi significati per i differenti tipi di nodi, come sarà illustrato nella tabella seguente.
Tabella 1. Significato dei valori
Tipo | Significato |
---|---|
DomAttribute | valori di attributo |
DomAttribute | |
DomCDataSection | #cdata-section |
DomComment | #comment |
DomDocument | #document |
DomDocumentType | nome del tipo documento |
DomElement | nome tag |
DomEntity | nome di entittà |
DomEntityReference | nome di entità di riferimento |
DomNotation | nome della notazione |
DomProcessingInstruction | target |
DomText | #text |
La funzione restituisce il tipo di nodo. L'elenco di tutti i tipi possibili sono elencati in una tabella nell'introduzione.
Esempio 1.
Il precedente esempio visualizzerà:
|
(no version information, might be only in CVS)
DomNode->node_value -- Restituisce il valore di un nodoLa funzione restituisce il valore di un nodo. Il valore ha diversi significati per i diversi tipi di nodi, come illustrato nella seguente tabella.
Tabella 1. Significato dei valori
Tipo | Significato |
---|---|
DomAttribute | valori di un attributo |
DomAttribute | |
DomCDataSection | contenuto |
DomComment | contenuto del commento |
DomDocument | null |
DomDocumentType | null |
DomElement | null |
DomEntity | null |
DomEntityReference | null |
DomNotation | null |
DomProcessingInstruction | l'intero contenuto senza destinatario |
DomText | contenuto del testo |
(no version information, might be only in CVS)
DomNode->owner_document -- Restituisce il documento a cui appartiene questo nodoQuesta funzione restituisce il documento a cui appartiene questo nodo.
L'esempio seguente produce due liste uguali di nodi figli.
Vedere anche domnode_insert_before().
(no version information, might be only in CVS)
DomNode->parent_node -- Restituisce il genitore del nodoQuesta funzione restituisce il genitore del nodo.
(PHP >= 4.3 solo) Se non si trova il nodo genitore, si restituisce NULL.
L'esempio seguente visualizza due liste simili di nodi figli.
(no version information, might be only in CVS)
DomNode->prefix -- Restituisce lo spazio dei nomi prefisso al nodo(no version information, might be only in CVS)
DomNode->previous_sibling -- Restituisce il nodo fratello precedenteQuesta funzione restituisce il nodo fratello precedente rispetto al nodo corrente. Se non vi sono nodi precedenti la funzione restituisce FALSE (< 4.3) oppure null (>= 4.3). Si può utilizzare questa funzione per attraversare tutti i nodi figli come illustrato nell'esempio.
Vedere anche domnode_next_sibling().
(no version information, might be only in CVS)
DomNode->remove_child -- Rimuove un nodo figlio dalla lista dei figliQuesta funzione rimuove un nodo figlio dalla lista dei figli. Se il nodo non può essere rimosso, oppure non è un nodo figlio la funzione restituisce FALSE. Se il nodo figlio può essere rimosso la funzione restituisce il vecchio nodo.
Esempio 1. Rimozione di un nodo figlio
|
Vedere anche domnode_append_child().
(PHP 4.2) Questa funzione sostituisce il nodo vecchio_nodo con il parametro nuovo_nodo. Se il nuovo nodo è già un figlio questo non verrà aggiunto una seconda volta. Se la funzione non riesce a trovare il vecchio nodo, restituisce FALSE. Se, invece, la sostituzione riesce, la funzione restituisce il vecchio nodo.
(PHP 4.3) Questa funzione sostituisce il nodo figlio vecchio_nodo con il parametro nuovo_nodo, anche se il nuovo nodo è già un figlio di DomNode. Se nuovo_nodo era già presente nel documento, prima questo viene rimosso dal contesto esistente. Se la funzione non riesce a trovare il vecchio nodo, restituisce FALSE. Se la sostituzione riesce, la funzione restituisce il vecchio nodo. (Questo comportamento rispecchia le specifiche W3C).
Vedere anche domnode_append_child()
(PHP 4.2) Questa funzione sostituisce il nodo esistente con il nodo passato nel parametro nuovo_nodo. Qualora nuovo_nodo abbia un genitore, il nodo viene copiato in modo da non inserire nel documento due volte un nodo già presente. In questo modo si costringe a fare tutte le modifiche al nodo prima della sostituzione o di riprendere il nodo inserito in una fase successiva con funzioni tipo domnode_first_child(), domnode_child_nodes() ecc..
(PHP 4.3) Questa funzione sostituisce il nodo con il nuovo nodo passato. Questo non viene più copiato. Se nuovo_nodo è già inserito nel documento, prima viene rimosso dal contesto esistente. Se la sostituzione riesce, la funzione restituisce il vecchio nodo.
Vedere anche domnode_append_child()
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Imposta il nome del nodo.
Vedere anche domnode_node_name().
(no version information, might be only in CVS)
DomNode->set_namespace -- Imposta lo spazio dei nomi del nodoImposta lo spazio dei nomi del nodo a uri. Se esiste già uno spazio dei nomi impostato con il medesimo uri in uno dei nodi genitore, si utilizza il prefisso di questo, altrimenti si utilizza il prefisso passato con il parametro opzionale prefix, oppure se ne genera uno casuale.
Vedere anche domdocument_create_element_ns() e domnode_add_namespace()
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
DomProcessingInstruction->data -- Restituisce i dati di un nodo PI
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
DomProcessingInstruction->target -- Restituisce il target di un nodo PI
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
DomXsltStylesheet->process -- Applica una trasformazione XSLT ad un oggetto DomDocumentAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Vedere anche domxml_xslt_stylesheet(), domxml_xslt_stylesheet_file() e domxml_xslt_stylesheet_doc().
(no version information, might be only in CVS)
DomXsltStylesheet->result_dump_file -- Scarica il risultato di una trasformazione XSLT in un fileAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Questa funzione è disponibile solo a partire dalla versione 4.3 di PHP.
Poichè DomXsltStylesheet->process() restituisce sempre un documento XML ben formato, a prescindere da quale metodo di output sia specificato in <xsl:output> od in attributi/elementi simili, questa non è di grande utilità se si desidera ottenere in output un testo normale o HTML. Al contrario questa funzione rispetta <xsl:output method="html|text"> e le altre direttive di output. Vedere l'esempio per dettagli su come usare la funzione.
Vedere anche domxml_xslt_result_dump_mem() e domxml_xslt_process()
(no version information, might be only in CVS)
DomXsltStylesheet->result_dump_mem -- Scarica il risultato di una trasformazione XSLT in una stringaAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Questa funzione è disponibile solo a partire dalla versione 4.3 di PHP.
Poichè DomXsltStylesheet->process() restituisce sempre un documento XML ben formato, a prescindere da quale metodo di output sia specificato in <xsl:output> od in attributi/elementi simili, questa non è di grande utilità se si desidera ottenere in output un testo normale o HTML. Al contrario questa funzione rispetta <xsl:output method="html|text"> e le altre direttive di output. Vedere l'esempio per dettagli su come usare la funzione.
Vedere anche domxml_xslt_result_dump_file() e domxml_xslt_process()
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Crea da zero un nuovo documento DOM e lo restituisce.
Vedere anche domdocument_add_root()
Questa funzione analizza il documento XML presente nel file nome_file e restituisce un oggetto della classe "Dom document", con le proprietà indicate. Il file viene aperto in modalità di sola lettura.
Il parametro facoltativo mode può essere utilizzato per modificrea il comportamento della funzione. E' stato aggiunto in PHP 4.3.0. Esso può assumere una delle seguenti costanti: DOMXML_LOAD_PARSING (default), DOMXML_LOAD_VALIDATING oppure DOMXML_LOAD_RECOVERING. Inoltre si possono agguiungere DOMXML_LOAD_DONT_KEEP_BLANKS, DOMXML_LOAD_SUBSTITUTE_ENTITIES e DOMXML_LOAD_COMPLETE_ATTRS tramite l'operazione or.
Se si utilizza il parametro error, questo ocnterrà l'eventuale messaggio di errore. error deve essere passato per riferimento. Il parametro è stato aggiunto in PHP 4.3.0.
Vedere anche domxml_open_mem() e domxml_new_doc().
La funzione analizza il documento XML contenuto in str e restituisce un oggetto della classe "Dom document", avente le proprietà elencate. Queste funzioni, domxml_open_file() e domxml_new_doc(), devono essere richiamate prima di ogni altra funzione.
Il parametro facoltativo mode può essere utilizzato per modificare il comportamento di questa funzione. E' stato aggiunto in PHP 4.3.0. Vedere domxml_open_file() per i valori ammessi.
Se si utilizza il parametro error, questo ocnterrà l'eventuale messaggio di errore. error deve essere passato per riferimento. Il parametro è stato aggiunto in PHP 4.3.0.
Vedere anche domxml_open_file() e domxml_new_doc().
Questa funzione restituisce la versione della libreria XML attualmente utilizzata.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Questa funzione analizza il documento XML contenuto nella stringa str e restituisce il documento analizzato come un albero di oggetti PHP. Questa funzione è isolata rispetto alle altre, ciò significa che non si può accedere all'albero utilizzando le altre funzioni. Modificare l'albero, ad esempio aggiungendovi un nodo, non ha senso poichè al momento non vi è modo di salvare il documento in un file XML. Tuttavia questa funzione può essere utile se si desidera leggere un file ed analizzarne il contenuto.
(PHP 4 >= 4.2.0, PECL)
domxml_xslt_stylesheet_doc -- Crea un oggetto DomXsltStylesheet da un oggetto DomDocument.Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Vedere anche domxsltstylesheet->process(), domxml_xslt_stylesheet() e domxml_xslt_stylesheet_file()
(PHP 4 >= 4.2.0, PECL)
domxml_xslt_stylesheet_file -- Crea un oggetto DomXsltStylesheet da un file con un documento XSLAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Vedere anche domxsltstylesheet->process(), domxml_xslt_stylesheet() e domxml_xslt_stylesheet_doc().
(PHP 4 >= 4.2.0, PECL)
domxml_xslt_stylesheet -- Crea un oggetto DomXsltStylesheet da un documento XML contenuto in una stringaAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Vedere anche domxsltstylesheet->process(), domxml_xslt_stylesheet_file() e domxml_xslt_stylesheet_doc()
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Vedere anche xpath_eval().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Si può specificare il parametro opzionale contextnode per eseguire delle query XPath relative.
Vedere anche xpath_new_context().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Vedere anche xpath_eval().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Le seguenti sono le funzioni per la gestione degli errori ed il logging. Esse permettono di definire regole personalizzate per la gestione degli errori, e anche di modificarne la modalità della gestione stessa. Ciò permette di cambiare ed integrare i messaggi di errore adattandoli alle vostre esigenze.
Grazie alle funzioni di logging, è possibile inviare messaggi direttamente ad altre macchine, alla posta elettronica (o ad un gateway pager o di posta elettronica!), ai log di sistema, ecc., in modo da effettuare il log e controllare selettivamente le parti più importanti delle vostre applicazioni e siti web.
Le funzioni di restituzione dell'errore consentono la personalizzazione del livello e del tipo di errore, dal semplice avviso sino a funzioni personalizzate restituite durante gli errori.
Non è necessaria nessuna installazione per usare queste funzioni, esse fanno parte del core di PHP.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. Parametri di configurazione per la gestione degli errori e dei log
Nome | Default | Modificabile |
---|---|---|
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_ALL |
track_errors | "0" | PHP_INI_ALL |
html_errors | "1" | PHP_INI_ALL |
docref_root | "" | PHP_INI_ALL |
docref_ext | "" | 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?? |
Breve descrizione dei parametri di configurazione.
Imposta il livello di errore da visualizzare. Il parametro è sia un intero rappresentante un campo di bit, o una costante nominale. I livelli ri report degli errori e le costanti previste sono descritte in Costanti Predefinite, e in php.ini. Per impostare il livello in fase di esecuzione utilizzare la funzione error_reporting(). Vedere anche il parametro display_errors.
In PHP 4 e PHP 5 il valore di default è E_ALL & ~E_NOTICE. Questa impostazione non visualizza gli errori di livello E_NOTICE. Tuttavia può essere comodo visualizzare questi messaggi in fase di sviluppo.
Nota: Abilitare E_NOTICE durante la fase di sviluppo ha dei benefici. Ad esempio per scopi di debug: i messaggi di tipo NOTICE avvisano su possibili bug nel codice. L'uso di variabili non assegnate, ad esempio, viene rilevato con questo livello di errore. Particolare che è molto utile per trovare errori di battitura e risparmiare tempo in fase di debug. I messaggi di tipo NOTICE segnalano il codice scritto con un cattivo stile. Ad esempio, $arr[item] è meglio che sia scritto come $arr['item'] poichè il PHP tenta di trattare "item" come costante. Se non esiste una simile costante, il PHP presume che si tratti dell'indice di una matrice.
Nota: Nel PHP 5 è stato introdotto un nuovo livello di errore E_STRICT. Come E_STRICT non viene incluso nel E_ALL e, pertanto, occorre abilitarlo in modo esplicito. Abilitare E_STRICT durante la fase di sviluppo porta alcuni benefici. Questa casistica di messaggi servono ad aiutare le più recenti, e consigliate, metodologie di programamzione, avvisando, ad esempio, sull'uso di funzioni deprecate.
In PHP 3 l'impostazione di default è (E_ERROR | E_WARNING | E_PARSE), che significa la medesima cosa. Occorre rilevare, tuttavia, che le costanti non sono supportate nel php3.ini del PHP 3, e pertanto occorre utilizzare la codifica numerica, che corrisponde a 7.
Questo parametro determina se gli errori devono essere visualizzati sullo schermo come parte dell'output o se devono essere nascosti all'utente.
Nota: Questa opzione è di supporto allo sviluppo, e non deve mai essere utilizzata nei sistemi di produzione (ad esempio collegati ad Internet).
Anche quando è abilitata la visualizzazione degli errori, gli errori che avvengono durante l'avvio del PHP non sono visualizzati. Si raccomanda di mantenere display_startup_errors impostato a off, tranne che nelle fasi di sviluppo.
Indica se i messaggi di errore debbano essere registrati nell'errorlog del server o in error_log. Questo opzione dipende dal server.
Nota: Sui siti di produzione si raccomanda di utilizzare la registrazione degli errori piuttosto che visualizzarli.
Imposta la massima lunghezza del log degli errori in byte. Nell'errorlog error_log viene indicata anche la fonte del messaggio. Il valore di default è 1024 e 0 indica di non applicare alcuna limitazione. Questa dimensione viene applicata agli errori registrati, agli errori visualizzati e anche a $php_errormsg.
When an integer is used, the value is measured in bytes. You may also use shorthand notation as described in this FAQ.
Non registra i messaggi ripetuti. Gli errori ripetutti sono gli errori che si verificano nel medesimo file nella linea, e vengono riportati sino a quando ignore_repeated_source non viene impostato a true.
Ignora la fonte del messaggio quando si ignora i messaggi ripetuti. Quando questa impostazione è a On non saranno registrati messaggi ripetutida differenti linee del codice.
Se questo parametro è impostato a Off, non saranno evidenziate carenze di memoria (o nello stdout o nel log). Questa impostazione ha effetto solo nella compila in modalità di debug, e se error_reporting include E_WARNING nell'elenco degli errori abilitati.
Se abilitato, l'ultimo messaggio di errore sarà sempre presente nella variabile $php_errormsg.
Disabilita i tag HTML nei messaggi di errore. Il nuovo formato per i messaggi in HTML produce un testo cliccabile che dirige l'utente alla pagina che descrive l'errore o la funzione che generato l'errore. Questi riferimenti sono influenzati da docref_root e docref_ext.
Nel nuovo formato degli errori è previsto un riferimento alla pagina che descrive l'errore o alla funzione che ha generato l'errore. Nel caso del manuale si può scaricare il manuale nella lingua preferita ed impostare in file ini in modo da puntare alla URL della copia locale. Se la copia locale è raggiungibile tramite '/manual/' si può utilizzare docref_root=/manual/. In aggiunta si può impostare docref_ext a riconoscere l'estensione dei file nella copia, es. docref_ext=.html. E' possibile utilizzare riferimenti esterni. Ad esempio, si può utilizzare docref_root=http://manual/en/ oppure docref_root="http://landonize.it/?how=url&theme=classic&filter=Landon &url=http%3A%2F%2Fwww.php.net%2F"
Il più delle volte si imposta docref_root ad un valore che termina con value to end with a slash '/'. But see the second example above which does not have nor need it.
Nota: Questa caratteristica è utile nello sviluppo poichè rende facile la ricerca della descrzione delle funzioni. Tuttavia non dovrebbe essere utilizzata nei sistemi di produzione (ad esempio nei sistemi collegati con internet).
Vedere docref_root.
Nota: Il valore di docref_ext deve cominciare con un punto '.'.
Testo da visualizzare prima del messaggio di errore.
Testo da visualizzare dopo il messaggio di errore.
Nome del file in cui gli errori devono essere registrati. Se si indica il nome speciale syslog, gli errori saranno inviati al log di sistema. Sui sistemi Unix, ciò significa syslog(3) e sui sistemi Windows NT indica l'event log. Il log di sistema non è supportato in Windows 95. Vedere anche: syslog().
Se abilitata, questa opzione indica al PHP di visualizzare un warning quando si utilizza il segno (+) nelle stringhe. Questo rende più facile trovare gli script che richiedono di essere modificati nelle operazioni di concatenazione delle stringhe utilizzando (.).
Le costanti qui elencate sono sempre disponibili in quanto parte del core di PHP.
Nota: Si possono utilizzare queste constanti in php.ini ma non all'esterno del PHP, tipo in in httpd.conf, dove occorre utilizzare in valori.
Tabella 2. Errori e log
Valore | Costante | Descrizione | Note |
---|---|---|---|
1 | E_ERROR (integer) | Errori fatali di esecuzione. Questi indicano errori che non si possono ignorare, come, ad esempio, errori di allocazione della memoria. L'esecuzione dello script è bloccata. | |
2 | E_WARNING (integer) | Warning di esecuzione (errori non fatali). L'esecuzione dello script non viene bloccata. | |
4 | E_PARSE (integer) | Errore di parsing in fase di compila. Essendo errori di parsing sono generati dal parser del codice PHP. | |
8 | E_NOTICE (integer) | Informazioni di esecuzione. Questo messaggio indica che lo script ha incontrato qualcosa che potrebbe indicare un errore, ma è una sitauzione che può accadere durante una normale esecuzione di uno script. | |
16 | E_CORE_ERROR (integer) | Errori fatali che accadono durante la fase di inizializzazione del PHP. Questo è come un E_ERROR, tranne che viene generato dall'interno del PHP. | dal PHP 4 |
32 | E_CORE_WARNING (integer) | Warning (errore non fatale) che accade durante la fase di inizializzazione del PHP. Questo è come un E_WARNING, tranne che viene generato dall'interno del PHP. | dal PHP 4 |
64 | E_COMPILE_ERROR (integer) | Errore fatale di compila. Questo è come E_ERROR, tranne che viene generato dal motore Zend. | dal PHP 4 |
128 | E_COMPILE_WARNING (integer) | Warning di compila (errore non fatale). Questo è come E_WARNING, tranne che viene generato dal motore Zend. | dal PHP 4 |
256 | E_USER_ERROR (integer) | Messaggio di errore generato dall'utente. Questo è come E_ERROR, tranne che viene generato dal codice PHP tramite la funzione trigger_error(). | dal PHP 4 |
512 | E_USER_WARNING (integer) | Messaggio di warning generato dall'utente. Questo è come E_WARNING,tranne che viene generato dal codice PHP tramite la funzione trigger_error(). | dal PHP 4 |
1024 | E_USER_NOTICE (integer) | Messaggio di informazione generato dall'utente. Questo è come E_NOTICE, tranne che viene generato dal codice PHP tramite la funzione trigger_error(). | dal PHP 4 |
2047 | E_ALL (integer) | Tutti gli errori ed i warning supportati tranne quelli di livello E_STRICT. | |
2048 | E_STRICT (integer) | Informazione di esecuzione. Abilitare questo messaggio per avere dal PHP suggerimenti sulle modifiche da apportare al codice per avere la migliore interoperabilità e compatibilità del codice. | dal PHP 5 |
I valori precedenti (sia numerici, sia simbolici) possono essere utilizzati per costruire delle maschere di bit che indichino quali errori visualizzare. Si può utilizzare gli operatori sui bit per combinare questi valori o per mascherare certi tipi di errori. Fare attenzione che soltanto '|', '~', '!', '^' e '&' sono compresi dal php.ini, e che nessun operatore sui bit è gestito dal php3.ini.
Di seguito sarà illustrato un esempio di utilizzo delle procedure di gestione dell'errore in PHP. Qui si definisce una funzione di gestione dell'errore che registra le informazioni in un file (in formato XML) e invia tramite e-mail allo sviluppare dei messaggi in caso di errori critici.
Esempio 1. Esempio dell'utilizzo di della gestione degli erorri in uno script
|
debug_backtrace() genera una backtrace PHP e restituisce questa informazione sotto forma di array associativo. Gli elementi che possono venire restituiti sono elencati nella seguente tabella:
Tabella 1. Elementi restituibili dalla funzione debug_backtrace()
Nome | Tipo | Descrizione |
---|---|---|
funzione | string | Il nome della funzione corrente. Vedere anche __FUNCTION__. |
riga | integer | Il numero della linea corrente. Vedere anche __LINE__. |
file | string | Il nome del file corrente. Vedere anche __FILE__. |
classe | string | Il nome della class corrente. Vedere anche __CLASS__ |
tipo | string | Il tipo di chiamata corrente. Se chiamata di metodo, viene restituito "->" is returned. Se chiamata di metodo statico, viene restituito "::". Se chiamata di funzione, non viene restituito niente. |
args | array | Se all'interno di una funzione, elenca gli argomenti della funzione. Se all'interno di un file incluso, elenca i nomi del file incluso. |
Di seguito un semplice esempio.
Esempio 1. debug_backtrace() example
Risultati durante l'esecuzione di /tmp/b.php:
|
Vedere anche trigger_error() and debug_print_backtrace().
debug_print_backtrace() stampa una backtrace PHP. Stampa le chiamate di funzione, i file included/required e tutto cio' che viene valutato dalla funzione eval().
Esempio 1. Esempio di funzione debug_print_backtrace()
Il precedente esempio visualizzerà qualcosa simile a:
|
Invia un messaggio di errore la log del server web, ad una porta TCP o ad un file. Il primo parametro, messaggio, è il messaggio di errore che deve essere registrato. Il secondo parametro, tipo_messaggio indica la destinazione del messaggio:
Tabella 1. error_log() tipi di log
0 | messaggio è inviato al log di sistema di PHP, utilizzando il sistema di log del Sistema Operativo o un file, a seconda di come sia impostata la direttiva di configurazione error_log. |
1 | messaggio è inviato via posta elettronica all'indirizzo indicato nel parametro destinazione parameter. Questo è l'unico tipo di messaggio nel quale viene usato il quarto parametro, headers_extra. Questo tipo di messaggio utilizza la stessa funzione interna di mail(). |
2 | messaggio viene inviato attraverso la connessione di debug di PHP. Questa opzione è disponibile solo nel caso che il debug remoto sia stato abilitato. In questo caso, il parametro destinazione specifica il nome dell'host o l'indirizzo IP e opzionalmente, numero di porta, del socket che riceverà l'informazione di debug. |
3 | messaggio è aggiunto al file destinazione. |
Avvertimento |
Il debug remoto via TCP/IP è una caratteristica di PHP 3 non disponibile in PHP 4. |
Esempio 1. error_log() esempi
|
Definisce il livello di restituzione di errore di PHP e ritorna il vecchio livello. Il livello di restituzione dell'errore può essere una maschera di bit o una costante named. L'utilizzo delle costanti named è caldamente consigliato per assicurare la compatibilità con versioni future. All'aggiungere di livelli di errore, la gamma degli interi viene incrementata, perciò vecchi livelli di errore basati sull'intero non si comporteranno sempre come ci si aspetta.
Esempio 1. Error Integer changes
|
Tabella 1. error_reporting() valori dei bit
valore | costante |
---|---|
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 |
Esempio 2. esempi error_reporting()
|
(PHP 4 >= 4.0.1, PHP 5)
restore_error_handler -- Ripristina la precedente funzione di gestione dell'erroreUtilizzata dopo la modifica della funzione di gestione degli errori con set_error_handler(), per ripristinare la precedente modalità di gestione (che può essere quella di configurazione o una definita dall'utente).
Vedere anche error_reporting(), set_error_handler(), trigger_error(), user_error()
(PHP 5)
restore_exception_handler -- Ripristina la funzione di gestione delle eccezioni definita in precedenzaUtilizzata, dopo aver cambiato la funzione di gestione delle eccezioni con il comando set_exception_handler(), per tornare al gestore delle eccezioni precedente (che potrebbe essere la funzione incorporata o una funzione definita dall'utente). Questa funzione restituisce sempre TRUE.
Vedere anche set_exception_handler(), set_error_handler(), restore_error_handler() error_reporting()
(PHP 4 >= 4.0.1, PHP 5)
set_error_handler -- Configura una funzione di gestione dell'errore definita dall'utente.Configura una funzione utente (error_handler per gestire gli errori in uno script. Restituisce, se esistente, il precedente gestore degli errori, o FALSE in caso di errore. Questa funzione può essere utilizzata per definire un sistema personalizzato di gestione degli errori durante l'esecuzione, per esempio in applicazioni dove sia necessario svuotare dati o file in caso di un determinato errore critico, o quando sia necessario, in determinate condizioni, attivare un errore (con trigger_error())
La funzione utente richiede 2 parametri: il codice errore e una stringa descrittiva dell'errore. Da PHP 4.0.2, è possibile opzionalmente fornire altri 3 parametri aggiuntivi: il nome del file, il numero di riga e il contesto dove è avvenuto l'errore (un array che punto alla tabella dei simboli attiva nel punto in cui è avvenuto l'errore).
L'esempio sottostante mostra la gestione delle eccezioni interne attivando gli errori e gestendoli tramite una funzione definita dall'utente:
Esempio 1. Gestione errori con set_error_handler() e 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> |
E' importante ricordare che il gestore degli errori standard di PHP viene completamente saltato. La configurazione di error_reporting() non avrà effetto e il vostro gestore di errore sarà richiamato senza considerarla - in ogni caso sarà possibile leggere il valore corrente di error_reporting() ed agire di conseguenza. E' di particolare rilevanza il fatto che questo valore sarà 0 se la riga che causa l'errore viene precedura dall' operatore di controllo errore @.
Notare anche che è vostra responsabilità definire die() se necessario. Se la funzione di gestione dell'errore ritorna, lo script continerà l'esecuzione con la riga seguente a quella che ha causato l'errore.
Vedere anche error_reporting(), restore_error_handler(), trigger_error(), user_error()
(PHP 5)
set_exception_handler -- Imposta una funzione di gestione delle eccezioni definita dall'utenteImposta la funzione predefinita per la gestione delle eccezioni se un'eccezione non viene individuata all'interno di un blocco try/catch. L'esecuzione sara' terminata dopo la chiamata della funzione exception_handler.
La funzione exception_handler deve essere definita prima di invocare
la funzione set_exception_handler(). A quest'ultima funzione deve essere passato
un solo parametro, che consiste nell'eccezione individuata.
exception_handler ( object exception )
Nome della funzione da invocare in caso di eccezione non individuata.
Nome della funzione da invocare in caso di eccezione non individuata.
Restituisce la funzione di gestione delle eccezioni definita in precedenza, oppure FALSE in caso di errore. Se non era stata definita in precedenza nessuna funzione di gestione delle eccezioni, viene restituita una stringa vuota.
restore_exception_handler(), restore_error_handler(), error_reporting(), information about the callback type, e PHP 5 Exceptions.
(PHP 4 >= 4.0.1, PHP 5)
trigger_error -- Genera un messaggio a livello utente di errore/avviso/avvertimento messageUtilizzata per attivare una condizione di errore utente, può essere usata in congiunzione con il gestore di errore interno, o con una funzione definita dall'utente che sia configurata per essere il nuovo gestore di errore con (set_error_handler()). Funziona soltanto con la famiglia di costanti E_USER, e punta alla predefinita E_USER_NOTICE.
Questa funzione è utile quando sia necessario generare una particolare risposta ad un'eccezione durante l'esecuzione. Per esempio:
Nota: Vedere set_error_handler() per un esempio più esplicativo.
Vedere anche error_reporting(), set_error_handler(), restore_error_handler(), user_error()
Questo è un alias per la funzione trigger_error().
Vedere anche error_reporting(), set_error_handler(), restore_error_handler() e trigger_error()
With the exif extension you are able to work with image meta data. For example, you may use exif functions to read meta data of pictures taken from digital cameras by working with information stored in the headers of the JPEG and TIFF images.
Your PHP must be compiled in with --enable-exif. PHP does not require any additional library for the exif module. Windows users must also have the mbstring extension enabled.
To enable exif-support configure PHP with --enable-exif
Windows users must enable both the php_mbstring.dll and php_exif.dll DLL's in php.ini. The php_mbstring.dll DLL must be loaded before the php_exif.dll DLL so adjust your php.ini accordingly.
Il comportamento di queste funzioni è influenzato dalle impostazioni di 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.
Tabella 1. Exif configuration options
Name | Default | Changeable | Changelog |
---|---|---|---|
exif.encode_unicode | "ISO-8859-15" | PHP_INI_ALL | Available since PHP 4.3.0. |
exif.decode_unicode_motorola | "UCS-2BE" | PHP_INI_ALL | Available since PHP 4.3.0. |
exif.decode_unicode_intel | "UCS-2LE" | PHP_INI_ALL | Available since PHP 4.3.0. |
exif.encode_jis | "" | PHP_INI_ALL | Available since PHP 4.3.0. |
exif.decode_jis_motorola | "JIS" | PHP_INI_ALL | Available since PHP 4.3.0. |
exif.decode_jis_intel | "JIS" | PHP_INI_ALL | Available since PHP 4.3.0. |
Breve descrizione dei parametri di configurazione.
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.
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
The exif_imagetype() lists several related built-in constants.
exif_imagetype() reads the first bytes of an image and checks its signature.
exif_imagetype() 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 the browser.
When a correct signature is found, the appropriate constant value will be returned otherwise the return value is FALSE. The return value is the same value that getimagesize() returns in index 2 but exif_imagetype() is much faster.
The following constants are defined, and represent possible exif_imagetype() return values:
Tabella 1. Imagetype Constants
Value | Constant |
---|---|
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_JB2 |
13 | IMAGETYPE_SWC |
14 | IMAGETYPE_IFF |
15 | IMAGETYPE_WBMP |
16 | IMAGETYPE_XBM |
exif_read_data() reads the EXIF headers from a JPEG or TIFF image file. This way you can read meta data generated by digital cameras.
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.
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.
When an Exif header contains a Copyright note, this itself can contain two values. As the solution is inconsistent 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 also contain the entry Copyright which is either the original copyright string, or a comma separated list of the photo and editor copyright.
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.
exif_read_data() also validates EXIF data tags according to the EXIF specification (http://exif.org/Exif2-2.PDF, page 20).
Nota: Windows ME/XP can both wipe the Exif headers when connecting to a camera. More information available at http://www.canon.co.jp/Imaging/NOTICE/011214-e.html.
The name of the image file being read. This cannot be an URL.
Is a comma separated list of sections that need to be present in file to produce a result array. If none of the requested sections could be found the return value is FALSE.
FILE | FileName, FileSize, FileDateTime, SectionsFound |
COMPUTED | html, Width, Height, IsColor, and more if available. 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. |
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. |
Specifies whether or not each section becomes an array. The sections COMPUTED, THUMBNAIL, and COMMENT always become arrays as they may contain values whose names conflict with other sections.
When set to TRUE the thumbnail itself is read. Otherwise, only the tagged data is read.
It returns an associative array where the array indexes are the header names and the array values are the values associated with those headers. If no data can be returned, exif_read_data() will return FALSE.
Versione | Descrizione |
---|---|
4.3.0 | Can read all embedded IFD data including arrays (returned as such). Also the size of an embedded thumbnail is returned in a THUMBNAIL subarray, and can return thumbnails in TIFF format. Also, there is no longer a maximum length for returned values (not until the memory limit has been reached) |
4.3.0 | If PHP has mbstring support, the user comment can automatically change encoding. Also, if the user comment uses Unicode or JIS encoding this encoding will automatically be changed according to the exif ini settings in php.ini |
4.3.0 | 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. Also, COMPUTED and UserComment no longer only contain the first copyright entry if the datatype was wrong. |
Esempio 1. exif_read_data() example
The first call fails because the image has no header information. Il precedente esempio visualizzerà qualcosa simile a:
|
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
exif_thumbnail() reads the embedded thumbnail of a TIFF or JPEG image.
If you want to deliver thumbnails through this function, you should send the mimetype information using the header() function.
It is possible that exif_thumbnail() cannot create an image but can determine its size. In this case, the return value is FALSE but width and height are set.
The name of the image file being read. This image contains an embedded thumbnail.
The return width of the returned thumbnail.
The returned height of the returned thumbnail.
The returned image type of the returned thumbnail. This is either TIFF or JPEG.
Esempio 1. exif_thumbnail() example
|
This extension allows to interact with processes through PTY. You may consider using the expect:// wrapper with the filesystem functions which provide a simpler and more intuitive interface.
This module uses the functions of the expect library. You need libexpect version >= 5.43.0.
This PECL extension is not bundled with PHP. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: http://pecl.php.net/package/expect.
In PHP 4 this PECL extensions source can be found in the ext/ directory within the PHP source or at the PECL link above. In order to use these functions you must compile PHP with expect support by using the --with-expect[=DIR] configure option.
Windows users will enable php_expect.dll inside of php.ini in order to use these functions. In PHP 4 this DLL resides in the extensions/ directory within the PHP Windows binaries download. You may download this PECL extension DLL from the PHP Downloads page or at http://snaps.php.net/.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
In order to configure expect extension, there are configuration options in the configuration file php.ini.
Tabella 1. Expect Opioni di configurazione
Nome | Default | Modificabile | Changelog |
---|---|---|---|
expect.timeout | "10" | PHP_INI_ALL | |
expect.loguser | "On" | PHP_INI_ALL | |
expect.logfile | "" | PHP_INI_ALL |
Breve descrizione dei parametri di configurazione.
The timeout period for waiting for the data, when using the expect_expectl() function.
A value of "-1" disables a timeout from occurring.
Nota: A value of "0" causes the expect_expectl() function to return immediately.
Whether expect should send any output from the spawned process to stdout. Since interactive programs typically echo their input, this usually suffices to show both sides of the conversation.
Name of the file, where the output from the spawned process will be written. If this file doesn't exist, it will be created.
Nota: If this configuration is not empty, the output is written regardless of the value of expect.loguser.
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Indicates that the pattern is a glob-style string pattern.
Indicates that the pattern is an exact string.
Indicates that the pattern is a regexp-style string pattern.
Value, returned by expect_expectl(), when EOF is reached.
Value, returned by expect_expectl() upon timeout of seconds, specified in value of expect.timeout
Value, returned by expect_expectl() if no pattern have been matched.
This example connects to the remote host via SSH, and prints the remote uptime.
Esempio 1. Expect Usage Example
|
(no version information, might be only in CVS)
expect_expectl -- Waits until the output from a process matches one of the patterns, a specified time period has passed, or an EOF is seenWaits until the output from a process matches one of the patterns, a specified time period has passed, or an EOF is seen.
An Expect stream, previously opened with expect_popen().
An array of expect cases. Each expect case is an indexed array, as described in the following table:
Tabella 1. Expect Case Array
Index Key | Value Type | Description | Is Mandatory | Default Value |
---|---|---|---|---|
0 | string | pattern, that will be matched against the output from the stream | yes | |
1 | mixed | value, that will be returned by this function, if the pattern matches | yes | |
2 | integer | pattern type, one of: EXP_GLOB, EXP_EXACT or EXP_REGEXP | no | EXP_GLOB |
Returns value associated with the pattern that was matched.
On failure this function returns: EXP_EOF, EXP_TIMEOUT or EXP_FULLBUFFER
Esempio 1. expect_expectl() example
|
(no version information, might be only in CVS)
expect_popen -- Exectute command via Bourne shell, and open the PTY stream to the processExecute command via Bourne shell, and open the PTY stream to the process.
Returns an open PTY stream to the process'es stdio, stdout and stderr.
On failure this function returns FALSE.
FAM monitors files and directories, notifying interested applications of changes. More information about FAM is available at http://oss.sgi.com/projects/fam/.
A PHP script may specify a list of files for FAM to monitor using the functions provided by this extension.
The FAM process is started when the first connection from any application to it is opened. It exits after all connections to it have been closed.
Nota: Questo modulo è stato spostato nel repository PECL e non sarà più rilascio con il PHP dalla versione 5.1.0.
Nota: Questo modulo non è disponibile su piattaforme Windows.
This extension uses the functions of the FAM library, developed by SGI. Therefore you have to download and install the FAM library.
To use PHP's FAM support you must compile PHP --with-fam[=DIR] where DIR is the location of the directory containing the lib and include directories.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Tabella 1. FAM event constants
Constant | Description |
---|---|
FAMChanged (integer) | Some value which can be obtained with fstat(1) changed for a file or directory. |
FAMDeleted (integer) | A file or directory was deleted or renamed. |
FAMStartExecuting (integer) | An executable file started executing. |
FAMStopExecuting (integer) | An executable file that was running finished. |
FAMCreated (integer) | A file was created in a directory. |
FAMMoved (integer) | This event never occurs. |
FAMAcknowledge (integer) | An event in response to fam_cancel_monitor(). |
FAMExists (integer) | An event upon request to monitor a file or directory. When a directory is monitored, an event for that directory and every file contained in that directory is issued. |
FAMEndExist (integer) | Event after the last FAMEExists event. |
fam_cancel_monitor() terminates monitoring on a resource previously requested using one of the fam_monitor_ functions. In addition an FAMAcknowledge event occurs.
See also fam_monitor_file(), fam_monitor_directory(), fam_monitor_collection(), and fam_suspend_monitor()
fam_close() closes a connection to the FAM service previously opened using fam_open().
fam_monitor_collection() requests monitoring for a collection of files within a directory. The actual files to be monitored are specified by a directory path in dirname, the maximum search depth starting from this directory and a shell pattern mask restricting the file names to look for.
A FAM event will be generated whenever the status of the files change. The possible event codes are described in detail in the constants part of this section.
See also fam_monitor_file(), fam_monitor_directory(), fam_cancel_monitor(), fam_suspend_monitor(), and fam_resume_monitor().
fam_monitor_directory() requests monitoring for a directory and all contained files. A FAM event will be generated whenever the status of the directory (i.e. the result of function stat() on that directory) or its content (i.e. the results of readdir()) change.
The possible event codes are described in detail in the constants part of this section.
See also fam_monitor_file(), fam_monitor_collection(), fam_cancel_monitor(), fam_suspend_monitor(), and fam_resume_monitor().
fam_monitor_file() requests monitoring for a single file. A FAM event will be generated whenever the file status (i.e. the result of function stat() on that file) changes.
The possible event codes are described in detail in the constants part of this section.
See also fam_monitor_directory(), fam_monitor_collection(), fam_cancel_monitor(), fam_suspend_monitor(), and fam_resume_monitor().
fam_next_event() returns the next pending FAM event. The function will block until an event is available which can be checked for using fam_pending().
fam_next_event() will return an array that contains a FAM event code in element 'code', the path of the file this event applies to in element 'filename' and optionally a hostname in element 'hostname'.
The possible event codes are described in detail in the constants part of this section.
See also fam_pending().
fam_open() opens a connection to the FAM service daemon. The optional parameter appname should be set to a string identifying the application for logging reasons.
See also fam_close().
fam_pending() returns non-zero if events are available to be fetched using fam_next_event().
See also fam_next_event().
fam_resume_monitor() resumes monitoring of a resource previously suspend using fam_suspend_monitor().
See also fam_suspend_monitor().
fam_suspend_monitor() temporarily suspend monitoring of a resource previously requested using one of the fam_monitor_ functions. Monitoring can later be continued using fam_resume_monitor() without the need of requesting a complete new monitor.
See also fam_resume_monitor(), and fam_cancel_monitor().
Il Forms Data Format (FDF) è un formato per la gestione di form all'interno di documenti PDF. Si dovrebbe leggere la documentazione al link http://partners.adobe.com/asn/acrobat/forms.jsp per avere maggiori informazioni su cosa sia FDF e su come usarlo in generale.
L'idea di base è che FDF sia simile ai form HTML. Fondamentalmente la differenza consiste nel formato con cui i dati sono inviati al server quando viene premuto il bottone di sottomissione del form (che, ovviamente, è in Form Data Format) e il formato del form stesso (che è il Portable Document Format, PDF). L'elaborazione dei dati FDF è una delle caratteristiche delle funzioni fdf.Ma ve ne sono altre. Una di queste consiste nel prendere un form PDF e compilarne i campi senza modificare il form . In questo caso si dovrebbe creare il documento FDF (fdf_create()) impostare i valori per ciascun campo (fdf_set_value()) e associarlo al form PDF (fdf_set_file()). Infine viene inviato al browser browser con MimeType application/vnd.fdf. Acrobat Reader riconosce il MimeType, legge il form PDF associato e completa i campi con i dati dal documento FDF.
Se si apre un documento FDF con un editor di testo si troveranno degli oggetti con nome FDF. Tali oggetti possono contenere diversi campi tipo Fields, F, Status etc.. I campi più comuni sono Fields che puntano alla lista dei campi di input, e F che contiene il nome del file PDF a cui appartengono questi dati. Questi campi sono definiti dalla documentazione FDF come chiave /F (/F-Key) e chiave /Status (/Status-Key) Le modifiche a questi chiavi posso essere svolte con funzioni tipo fdf_set_file() e fdf_set_status(). I campi sono modificati dalle funzioni fdf_set_value(), fdf_set_opt() etc..
Occorre avere disponibile il toolkit FDF SDK, scaricabile da http://partners.adobe.com/asn/acrobat/forms.jsp. Dal PHP 4.3 occorre avere almeno l'SDK versione 5.0. Le librerie FDF sono disponibili in formato binario solo per le piattaforme supportate da Adobe quali Win32, Linux, Solaris e AIX.
Occorre compilare il PHP con --with-fdftk[=DIR].
Nota: Se si hanno problemi nella configurazione del PHP con supporto fdftk, verificare che i file fdftk.h e libfdftk.so siano nel posto corretto. Lo script di configurazione supporta sia la struttura delle directory della distribuzione FDFSDK, sia l'usuale struttura DIR/include / DIR/lib, pertanto si può puntare o direttamente alla directory della distribuzione decompressa o posizionare il file con l'header e la libreria appropriata per la piattaforma, ad es. /usr/local/include e /usr/local/lib ed eseguire configure con --with-fdftk=/usr/local.
Nota per gli utenti Win32: Per potere abilitare questo modulo sui sistemi Windows, occorre copiare fdftk.dll dalla cartella DLL del rilascio PHP7Win32 alla cartella SYSTEM32 della macchina Windows. (Es. C:\WINNT\SYSTEM32 oppure C:\WINDOWS\SYSTEM32).
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
La maggior parte delle funzioni richiedono una risorsa fdf come primo parametro. La risorsa fdf è un puntatore al file fdf aperto. Le risorse fdf possono essere ottenute dalle funzioni fdf_create(), fdf_open() e fdf_open_string().
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Il seguente esempio illustra l'elaborazione dei dati di un form.
Esempio 1. Elaborazione di un documento FDF
|
Aggiunge degli script al documento FDF, che in seguito Acrobat aggiungerà agli script del documento una volta che l'FDF è importato. Su consiglia di utilizzare '\r' come separatore di riga nel script_code.
Esempio 1. Aggiunta di codice JavaScript ad un documento FDF
Sarà creato un documento come il seguente:
|
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
La funzione fdf_close() chiude un documento FDF.
Vedere anche fdf_open().
La funzione fdf_create() crea un nuovo documento FDF. Questa funzione è necessaria se si desidera compilare dei campi di input di un documento PDF.
Esempio 1. Compila di un documento PDF
|
Vedere anche fdf_close(), fdf_save() e fdf_open().
(PHP 4 >= 4.3.0, PHP 5)
fdf_enum_values -- Richiama una funzione definita dall'utente per ciascun valore del documento
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
La funzione fdf_errno() il codice di erore impostato dall'ultima funzione FDF eseguita. Questo può valere zero se è stata eseguita con successo, o diverso da zero in caso di errore. Una descrizione testuale dell'errore può essere ottenuta usando la funzione fdf_error().
Vedere anche fdf_error().
fdf_error() restituisce la descrizione testuale per il codice di errore passato in error_code. Qualora non si fornisca error_code, la funzione utilizzerà il codice di errore interno impostato dall'ultima operazione, in questo modo fdf_error() si presenta come una scorciatoia per fdf_error(fdf_errno()).
Vedere anche fdf_errno().
La funzione fdf_get_ap() ottiene informazioni sul campo field (per es. il valore della chiave /AP) e le memorizza in un file. I possibili valori per face sono FDFNormalAP, FDFRolloverAP e FDFDownAP. Il formato è memorizzato in nel file filename.
La funzione estrae un file indicato dal "selettore di file" fieldname e lo memorizza in savepath. Il parametro savepath può essere il nome di file o una directory esistente nella quale verrà creato il file con il suo nome originale. Eventuali file con il medesimo nome saranno sovrascritti.
Nota: Sembra che non ci sia altro metodo per risalire al nome originale del file se non quello di scaricare il file nella directory indicata da savepath e rilevare il nome con cui viene scritto.
La matrice restituita contiene i seguenti indici:
path - percorso in cui viene archiviato il file
size - dimensione del file in bytes
type - mimetype se dato nel FDF
La funzione fdf_get_encoding() restituisce il valore della chiave /Encoding. Resituisce una stringa vuota se non viene utilizzato lo schema PDFDocEncoding/Unicode.
Vedere anche fdf_set_encoding().
La funzione fdf_set_file() restituisce il valore della chiave /F.
Vedere anche fdf_set_file().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
La funzione fdf_get_status() restituisce il valore per la chiave /STATUS.
Vedere anche fdf_set_status().
La funzione fdf_get_value() restituisce il valore per il campo fieldname richiesto.
Gli elementi di una matrice di campi possono essere recuperati passando il parametro opzionale which, iniziando da zero. Per i campi non matrice il parametro which viene ignorato.
Nota: Il supporto delle matrici ed il campo opzionale which sono stati aggiunti in PHP 4.3.
Vedere anche fdf_set_value().
(PHP 4 >= 4.3.0, PHP 5)
fdf_get_version -- Restituisce il numero di versione per le API FDF o un fileQuesta funzione restituisce il numero i versione FDF per il dato documento fdf_document, o il numero di versione per il toolkit API, se il parametro viene omesso.
Per il corrente toolkit FDF 5.0 il numero di versione delle API è il '5.0' e il numero di versione del documento può essere '1.2', '1.3' oppure '1.4'.
Vedere anche fdf_set_version().
Questa è una funzione di comodità per impostare le intestazioni HTTP per inviare documenti FDF. La funzione imposta il campo Content-type: a application/vnd.fdf.
La funzione fdf_next_field_name() restituisce il nome del campo successivo al campo indicato in fieldname o il nome del primo campo se è impostato a NULL.
Vedere anche fdf_enum_fields() e fdf_get_value().
La funzione fdf_open_string() ricava i dati di un form da un stringa. Il parametro fdf_data deve contenere dati restituiti da un form PDF o creati dalle funzioni fdf_create() e fdf_save_string().
Si può usare fdf_open_string() insieme a $HTTP_FDF_DATA per elaborare input in un form fdf da un client remoto.
Vedere anche fdf_open(), fdf_close(), fdf_create() e fdf_save_string().
La funzione fdf_open() apre un documento con i dati del form. Il file deve contenere i dati restituiti da un form PDF o creati tramite le funzioni fdf_create() e fdf_save().
Si può processare i risultati del POST di un form PDF scrivento i dati ricevuti da $HTTP_FDF_DATA in un file e aprendolo con fdf_open(). A partire da PHP 4.3 si può anche utilizzare la funzione fdf_open_string(), la quale utilizza un file temporaneo (che poi viene rimosso).
Vedere anche fdf_open_string(), fdf_close(), fdf_create() e fdf_save().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
La funzione fdf_save_string() restituisce il documento FDF come una stringa.
Esempio 1. Recupero di un documento FDF come stringa
Visualizzerà qualcosa tipo
|
Vedere anche: fdf_save(), fdf_open_string(), fdf_create() e fdf_close().
La funzione fdf_save() salva un documento FDF. Il risultante documento FDF sarà scritto in filename. Se si omette il parametro filename, la funzione fdf_save() scriverà il documento FDF nel default output di PHP.
Vedere anche: fdf_save_string(), fdf_create() e fdf_close().
La funzione fdf_set_ap() imposta l'apparire di un campo (per es. il valore della chiave /AP). I possibili valori per face sono FDFNormalAP, FDFRolloverAP e FDFDownAP.
La funzione fdf_set_encoding() imposta la codifica dei caratteri per il documento FDF fdf_document. Il parametro encoding deve essere il nome di un codifica valida. I valori attualmente ammessi sono: "Shift-JIS", "UHC", "GBK","BigFive". Una stringa vuota re-imposta la codifica al valore di default PDFDocEncoding/Unicode.
(PHP 3 >= 3.0.6, PHP 4, PHP 5)
fdf_set_file -- Imposta un documento PDF per visualizzare i dati FDF presentiLa funzione fdf_set_file() selezione un differente documento PDF nel quale visualizzare i dati di un form originati da un'altro. Il parametro url deve essere un URL assoluto.
Il frame nel quale visualizzare il documento può essere impostato tramite il parametro target_frame o tramite la funzione fdf_set_target_frame().
Esempio 1. Passaggio di dati FDF a un secondo form
|
Vedere anche fdf_get_file() e fdf_set_target_frame().
La funzione fdf_set_flags() imposta i flag del campo fieldname passato
Vedere anche fdf_set_opt().
La funzione fdf_set_javascript_action() imposta una azione javascript per il campo fieldname passato.
Vedere anche fdf_set_submit_form_action().
(PHP 4 >= 4.3.0, PHP 5)
fdf_set_on_import_javascript -- Adds javascript code to be executed when Acrobat opens the FDFAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
See also fdf_add_doc_javascript() e fdf_set_javascript_action().
La funzione fdf_set_opt() imposta le opzioni del campo fieldname dato.
Vedere anche fdf_set_flags().
La funzione fdf_set_status() imposta il valore per la chiave /STATUS. Quando un client riceve un documento FDF con lo 'status' impostato, ne visualizzerà il valore in una finestra.
Vedere anche fdf_get_status().
(PHP 4 >= 4.0.2, PHP 5)
fdf_set_submit_form_action -- Imposta un'azione per un campo nell'invio di un formLa funzione fdf_set_submit_form_action() imposta un'azione da eseguire nell'invio del form per il campo fieldname.
Vedere anche fdf_set_javascript_action().
Imposta il frame in cui visualizzare il PDF risultante da fdf_save_file().
Vedere anche fdf_save_file().
La funzione fdf_set_value() imposta il campo fieldname al valore value. Il parametro value sarà memorizzato come stringa a meno che non si tratti di una matrice. In questo caso tutti gli elementi della matrice saranno memorizzati in una matrice di valori.
Nota: Nella vecchia versione del toolkit fdf l'ultimo parametro determinava se il valore del campo doveva essere convertito in un PDF Name (isName = 1) o in una stringa PDF (isName = 0). Questo campo non viene più utilizzato con l'attuale versione 5.0. Per motivi di compatibilità è ancora supportato come parametro opzionale a partire da PHP 4.3, ma viene ignorato.
Il supporto per value come matrice è stato aggiunto in PHP 4.3.
Vedere anche fdf_get_value() e fdf_remove_item().
Questa funzione imposta il numero di versione del file FDF fdf_document a version. Alcune caratteristiche supportate da questo modulo sono soltatnto disponibili nelle più recenti versioni di fdf. L'attuale toolkit FDF (5.0) accetta come versione i valori '1.2', '1.3' or '1.4'.
Vedere anche fdf_get_version().
Queste funzioni permettono l'accesso in sola lettura dei dati del database filePro.
filePro è un marchio registrato della tecnologia fP Technologies, Inc. Per maggiori informazioni su filePro: http://www.fptech.com/.
Il supporto a filePro in PHP non è abilitato per default. Per abilitare la funzioni di sola lettura di filePro occorre impostare il parametro di configurazione --enable-filepro durante la compila del PHP.
Restituisce il numero di campi (colonne) di un database filePro aperto.
Vedere anche filepro().
Restituisce il nome del campo riferito all'indice inserito come parametro field_number.
Restituisce il tipo del campo riferito all'indice inserito come parametro field_number.
Restituisce la lunghezza del campo riferito all'indice inserito come parametro field_number.
Restituisce dei dati da una locazione specificata nel database. Il parametro row_number deve essere tra zero ed il numero complessivo delle righe meno uno (0..filepro_rowcount() - 1). In modo analogo il parametro field_number accetta valori compresi tra 0 ed il numero complessivo dei campi meno uno (0..filepro_fieldcount() - 1)
Nota: Quando safe-mode è abilitato, PHP controlla che i file o le directory sulle quali si sta andando a lavorare, abbiano lo stesso UID dello script che è in esecuzione.
Restituisce il numero di righe presenti in un database filePro.
Nota: Quando safe-mode è abilitato, PHP controlla che i file o le directory sulle quali si sta andando a lavorare, abbiano lo stesso UID dello script che è in esecuzione.
Vedede anche filepro().
Questa funzione legge e verifica la mappa del file, immagazzinando l'indice del campo e le informazioni.
Non viene eseguito nessun locking, si dovrebbe evitare di modificare il database filePro mentre quest'ultimo potrebbe venire aperto in PHP.
Nota: Quando safe-mode è abilitato, PHP controlla che i file o le directory sulle quali si sta andando a lavorare, abbiano lo stesso UID dello script che è in esecuzione.
Non sono richieste librerie esterne per compilare questo modulo, ma se si desidera avere il supporto per LFS (file di grandi dimensioni) su Linux, occorre avere una versione recente di glibc e occorre compilare il PHP con i seguenti parametri: -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64.
Non è necessaria nessuna installazione per usare queste funzioni, esse fanno parte del core di PHP.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. Opzioni di configurazione per Filesystem e Streams
Nome | Default | Modificabile |
---|---|---|
allow_url_fopen | "1" | PHP_INI_SYSTEM |
user_agent | NULL | PHP_INI_ALL |
default_socket_timeout | "60" | PHP_INI_ALL |
from | NULL | ?? |
auto_detect_line_endings | "Off" | PHP_INI_ALL |
Breve descrizione dei parametri di configurazione.
Questa opzione abilita i wrapper URL per fopen, in modo da potere accedere ad oggetti URL come file. Per default sono forniti wrapper per accedere a file remoti usando il protocollo ftp o http, alcune estensioni, tipo zlib, possono registrarne altri.
Nota: Questa impostazione può essere impostata solamente nel php.ini per motivi di sicurezza.
Nota: Questa opzione è stata aggiunta subito dopo il rilascio di PHP 4.0.3. Per le versioni fino a 4.0.3 compresa si può disabilitare questa opzione solo al momento della compila utilizzando il parametro di configurazione --disable-url-fopen-wrapper.
Avvertimento |
Nelle versioni precedenti alla 4.3.0 per i sistemi Windows, le suguenti funzioni non supportano l'accesso a file remoti: include(), include_once(), require(), require_once() e le funzioni imagecreatefromXXX nel modulo Riferimento LVI, Funzioni per le immagini. |
Definisce un agente utente il PHP.
Timeout di default (in secondi) per gli stream sui socket.
Nota: Questa opzione di configurazione è stata inserita in PHP 4.3.0
Imposta la password per l'ftp anonimo (il tuo indirizzo di posta elettronica).
Quando è attivato, il PHP esamina i dati letti da fgets() e file() per vedere se si sta utilizzando le convezioni di Unix, MS-Dos o Macintosh.
Questo permette al PHP di operare con sistemi Macintosh, ma, per default, l'opzione è impostata a Off, poichè vi è una piccola penalizzazione di velocità nel cercare di individuare il tipo di EOL per la prima riga; e anche perchè in alcuni casi si è sperimentato che l'utilizzo del carriage-returns come separatore nei sistemi Unix ha generato comportamenti non compatibili con il passato.
Nota: Questa opzione è stata introdotta in PHP 4.3.0
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Vedere anche le sezioni Directory e Esecuzione di programmi.
Per avere un elenco e le spiegazioni sui vari wrapper URL che possono essere utilizzati sui file remoti, vedere Appendice M.
Data una stringa contenente il percorso di un file, questa funzione restituisce il nome del file. Se il nome del file finisce in suffix quest'ultimo verrà tagliato.
Su Windows, sia gli slash (/) che i backslash (\) vengono utilizzati come carattere di separazione delle directory. In altri ambienti, si usa solo lo slash semplice (/).
Nota: Il parametro suffix è stato aggiunto in PHP 4.1.0.
Vedere anche dirname()
Tenta di cambiare il gruppo del file filename in group (specificato per nome o numero). Solo l'amministratore può cambiare arbitrariamente il gruppo di un file; gli altri utenti possono cambiare il gruppo dei file solo fra gruppi di cui sono membri.
Restituisce TRUE se ha successo; FALSE altrimenti.
Nota: Questa funzione non è eseguibile con file remoti, ma con file accessibili attraverso il filesystem del server.
Nota: Quando safe-mode è abilitato, PHP controlla che i file o le directory sulle quali si sta andando a lavorare, abbiano lo stesso UID dello script che è in esecuzione.
Tenta di cambiare le impostazioni del file filename in quelle date in mode.
Si osservi che mode non viene automaticamente assunto come valore ottale, per cui le stringhe (come "g+w") non verranno elaborate correttamente. Per ottenere l'operazione desiderata, è necessario far precedere mode da uno zero (0):
<?php chmod("/somedir/somefile", 755); // decimale; probabilmente errato chmod("/somedir/somefile", "u+rwx,go+rx"); // stringa; errato chmod("/somedir/somefile", 0755); // ottale; valore corretto di mode (preceduto da uno 0) ?> |
Il parametro mode consiste in tre numeri ottali costituenti le restrizioni dell'accesso per il proprietario, il gruppo utente a cui appartiene il proprietario, e gli altri utenti, nell'ordine dato. Ciascun numero può essere calcolato aggiungendo i permessi al valore base per l'utente. Il numero 1 indica che si abilita all'esecuzione del file, con il numero 2 si assegnano i diritti di scrittura, con il numero 4 si assegna il permesso di lettura del file. Aggiungere questi numeri per ottenere i diritti richiesti. Si possono avere maggiori dettagli sui permessi dei sistemi Unix usando il comando 'man 1 chmod' e 'man 2 chmod'.
<?php // Lettura e scrittura per il proprietario, e nessun permesso per gli altri chmod("/somedir/somefile", 0600); // Lettura e scrittura per il proprietario, e lettura per gli altri chmod("/somedir/somefile", 0644); // Accesso completo per il proprietario, e lettura ed esecuzione per gli altri chmod("/somedir/somefile", 0755); // Accesso completo per il proprietario, e lettura ed esecuzione per il gruppo del proprietario chmod("/somedir/somefile", 0750); ?> |
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: L'utente corrente è l'utente con il quale viene eseguito il PHP. Probabilmente non è il medesimo utente che si usa da shell o dall'accesso FTP.
Nota: Questa funzione non è eseguibile con file remoti, ma con file accessibili attraverso il filesystem del server.
Nota: Quando modalità sicura viene abilitato, PHP controlla se i files o le directory su cui si sta operando, hanno il medesimo UID (proprietario) dello script che sta per essere eseguito. In aggiunta, non si può impostare il SUID, SGID e sticky bit.
Tenta di cambiare il proprietario di un file filename in user (specificato per nome o numero). Solo l'amministratore può cambiare il proprietario di un file.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: Questa funzione non è eseguibile con file remoti, ma con file accessibili attraverso il filesystem del server.
Nota: Quando safe-mode è abilitato, PHP controlla che i file o le directory sulle quali si sta andando a lavorare, abbiano lo stesso UID dello script che è in esecuzione.
Vedere anche chown() e chmod().
Quando si eseguono le funzioni di sistema stat o lstat o una delle funzioni elencate nella lista delle funzioni coinvolte (vedi sotto), il PHP memorizza le informazioni restituite da queste funzioni in modo da fornire migliori performance. Esistono, tuttavia, casi in cui si desidera rimuovere le informazioni memorizzate. Ad esempio, nel caso in cui un file venga controllato più volte nel medesimo script ed il file si trova in situazioni in cui possa venire rimosso o possa essere variato durante l'esecuzione dello script; in questi casi si può volere cancellare le informazioni memorizzate. Per queste situazioni si può utilizzare la funzione clearstatcache() che cancella le informazioni memorizzate dal PHP sullo stato di un file.
Occorre notare che il PHP non memorizza informazioni su file inesistenti. Pertanto se si esegue la funzione file_exists() su un file che non esiste, questa restituisce FALSE fino a quando il file non viene creato. Un volta ccreato il file, la funzione restituisce TRUE anche se il file viene cancellato.
Nota: Queste funzioni memorizzano informazioni su specifici file, pertanto basta eseguire clearstatcache() nel caso di molteplici operazioni sul medesimo file oppure nel caso sia necessario non memorizzare informazioni su un dato file.
Tale valore viene memorizzato solo per la durata di una singola richiesta.
Le funzioni coinvolte sono 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().
Copia il file source in dest. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: Come da PHP 4.3.0, sia source che dest potrebbero essere URL se "fopen wrappers" è stato abilitato. Vedere fopen() per ulteriori dettagli. Se il parametro dest punta ad un URL, l'operazione di copia potrebbe fallire se il wrapper non supporta la sovrascrittura di file esistenti.
Avvertimento |
Se il file di destinazione già esiste, esso verrà sovrascritto. |
Nota: Nota di compatibilità con Windows: se viene copiato un file vuoto, copy() restituisce falso, ma il file sarà copiato correttamente.
Vedere anche move_uploaded_file(), rename(), e la sezione del manuale riguardo handling file uploads.
Questa funzione non esiste, la sua presenza nel manuale vuole essere utile a coloro che cercano nel posto sbagliato le funzioni unlink() o unset().
Vedere anche unlink() per cancellare file, unset() per eliminare variabili.
Data una stringa contenente il percorso di un file, questa funzione restituirà il nome della directory.
Su windows sia gli slash (/) che i backslash (\) vengono utilizzati come caratteri di separazione nei percorsi. In altri ambienti, c'è solo lo slash in avanti (/).
Nota: In PHP 4.0.3, la funzione dirname() è stata modificata per essere conforme alle specifiche POSIX. Essenzialmente ciò significa che non ci sono slash nel parametro path , viene restituito un punto ('.') per indicare la directory corrente. In altro modo, la stringa restituita è path senza alcun /component. Occorre notare che ciò implica che spesso dalla funzione dirname() si ottiene uno slash od un punto nei casi in cui la vecchia versione avrebbe restituito una stringa vuota.
dirname() ha modificato il suo comportamento dal PHP 4.3.0. Controllare l'esempio:
<?php //prima del PHP 4.3.0 dirname('c:/'); // restituisce '.' //dopo il PHP 4.3.0 dirname('c:/'); // restituisce 'c:' ?> |
dirname() è sicura con i dati binari dal PHP 5.0.0
Vedere anche: basename(), pathinfo() e realpath().
Data una stringa contenente una directory, questa funzione restituirà il numero di byte disponibili nel corrispondente filesystem o nella partizione corrispondente.
Nota: Questa funzione non è eseguibile con file remoti, ma con file accessibili attraverso il filesystem del server.
Vedere anche disk_total_space()
Data una stringa contenente una directory, questa funzione restituirà il numero totale di byte del filesystem o della partizione corrispondente.
Nota: Questa funzione non è eseguibile con file remoti, ma con file accessibili attraverso il filesystem del server.
Vedere anche disk_free_space()
Chiude il file puntato da handle.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Il puntatore al file deve essere valido e deve puntare ad un file aperto correttamente da fopen() o da fsockopen().
Restituisce TRUE se il puntatore al file ha raggiunto la fine del file (EOF) o si è verificato un errore (anche in caso di timeout del socket); altrimenti restituisce FALSE.
Avvertimento |
Se una connessione aperta da fsockopen() non è stata chiusa dal server, feof() attenderà finchè un timeout non sia stato raggiunto e restituisce TRUE. Il valore di timeout di default è 60 secondi. Si può usare stream_set_timeout() per cambiare questo valore. |
The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen().
Questa funzione forza la scrittura di tutto l'output bufferizzato sulla risorsa puntata dal puntatore handle. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Il puntatore al file deve essere valido e deve puntare ad un file correttamente aperto da fopen(), popen() o fsockopen().
The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen().
Restituisce una stringa contenente un singolo carattere letto dal file puntato da handle. Restituisce FALSE alla fine del file (EOF).
The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen().
Avvertimento |
Questa funzione può restituire il Booleano FALSE, ma può anche restituire un valore non-Booleano valutato come FALSE, come ad esempio 0 o "". Per favore fare riferimento alla sezione Booleans per maggiori informazioni. Usare l'operatore === per controllare il valore restituito da questa funzione. |
Nota: Questa funzione è binary-safe (gestisce correttamente i file binari)
Vedere anche fread(), fopen(), popen(), fsockopen() e fgets().
(PHP 3 >= 3.0.8, PHP 4, PHP 5)
fgetcsv -- Prende una riga da un puntatore a file e l'analizza in cerca di campi CSV
Un puntatore valido a un file che punta a un file aperto con successo da fopen(), popen(), o fsockopen().
Deve essere più grande della linea più lunga (in caratteri) per essere trovato nel file CSV (permettendo di trascinare il carattere di fine linea). E' diventato opzionale in PHP 5.
Setta il delimitatore di campo (un solo carattere). Virgola per default.
Setta il carattere di inclusione nel campo (un solo carattere). Doppie virgolette per default. Aggiunto in PHP 4.3.0.
Simile a fgets() eccetto per il fatto che fgetcsv() analizza le righe lette alla ricerca di campi in formato CSV e restituisce un vettore contenente i campi letti.
Nota: Il parametro enclosure è stato aggiunto in PHP 4.3.0.
Handle deve essere un puntatore valido ad un file correttamente aperto da fopen(), popen() o fsockopen().
Lunghezza deve essere maggiore della linea più lunga trovata nel file CSV (compresi i caratteri di fine riga).
fgetcsv() restituisce FALSE in caso d'errore e al raggiungimento della fine del file.
Nota: Una riga vuota in un file CVS verrà riportata come un vettore contenente un solo campo vuoto (null) e non verrà trattata come un errore.
Esempio 1. Legge e scrive l'intero contenuto di un file CSV.
|
fgetcsv() è diventata binary safe dal PHP 4.3.5
Nota: Se il PHP ha dei problemi a riconoscere la fine riga nella lettura di file su o creati da computer Macintosh, si può abilitare il parametro di configurazione auto_detect_line_endings.
Restituisce una stringa di length - 1 byte letti dal file puntato da handle. La lettura termina quando sono stati letti length - 1 byte, oppure si incontra il carattere di newline (che viene incluso nel valore restituito), oppure alla fine del file (EOF) qualora giunga prima. Se non si specifica length, si assume come default 1k, o 1024 byte.
Se si verifica un errore, la funzione restituisce FALSE.
Errori comuni:
Le persone abituate alla semantica 'C' di fgets notino la differenza nel trattamento dell'EOF.
The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen().
Segue un semplice esempio:
Nota: Il parametro length è diventato opzionale a partire da PHP 4.2.0, se omesso, si assume come lunghezza della linea 1024. A partire dalla versione 4.3, l'omissione del parametro length comporta la lettura del flusso d'ingresso sino al raggiungimento della fine della linea. Se la maggior parte delle righe lette dal file hanno dimensione superiore a 8KB, è più efficiente specificare la lunghezza massima della linea.
Nota: A partire da PHP 4.3 questa funzione è 'binary safe'. Le versioni precedenti non lo sono.
Nota: Se il PHP ha dei problemi a riconoscere la fine riga nella lettura di file su o creati da computer Macintosh, si può abilitare il parametro di configurazione auto_detect_line_endings.
Vedere anche fread(), fgetc(), stream_get_line(), fopen(), popen(), fsockopen() e stream_set_timeout().
Identica a fgets(), eccetto per il fatto che fgetss tenta di eliminare tutti i tag HTML e PHP dal testo che legge.
Puoi utilizzare il terzo parametro (opzionale) per specificare quali tag non devono essere eliminati.
Nota: Il parametro allowable_tags è stato aggiunto in PHP 3.0.13, PHP 4.0.0.
Il parametro length è facoltativo dal PHP 5.
Nota: Se il PHP ha dei problemi a riconoscere la fine riga nella lettura di file su o creati da computer Macintosh, si può abilitare il parametro di configurazione auto_detect_line_endings.
Vedere anche fgets(), fopen(), fsockopen(), popen() e strip_tags().
Restituisce TRUE se il file o la directory specificata da filename esiste; FALSE altrimenti.
Sui sistemi Windows utlizzare //computername/share/filename oppure \\computername\share\filename per verificare file su dischi condivisi.
Nota: I risultati di questa funzione saranno memorizzati. Vedere clearstatcache() per maggiori dettagli.
Suggerimento: A partire da PHP 5.0.0, questa funzione può essere utilizzata con alcuni URL wrappers. Fare riferimento a Appendice M per la lista di quali wrappers supportano le funzioni della famiglia stat().
Vedere anche is_readable(), is_writable(), is_file() e file().
Simile alla funzione file(), tranne che file_get_contents() restituisce il file in una stringa, iniziando allo specificato offset. Se si verifica un errore file_get_contents() restituirà FALSE
Nota: Il parametrooffset è stato aggiunto nel PHP 5.1.0.
Nota: Se si sta aprendo un URI con caratteri speciali, spazi ad esempio, si ha bisogno di decodificare l' URI con urlencode().
Nota: Questa funzione è binary-safe (gestisce correttamente i file binari)
Suggerimento: È possibile utilizzare una URL come un nome di file con questa funzione se fopen wrappers è stata abilitata. Per maggiori informazioni su come specificare i nomi di file vedere fopen() e Appendice M per avere la lista dei protocolli URL supportati.
Nota: Il supporto per il contesto è stato aggiunto in PHP 5.0.0. Per la descrizione del contesto, fare riferimento a Riferimento CXLIV, Stream Functions.
Avvertimento |
When using SSL, Microsoft IIS will violate the protocol by closing the connection without sending a close_notify indicator. PHP will report this as "SSL: Fatal Protocol Error" when you reach the end of the data. To workaround this, you should lower your error_reporting level not to include warnings. PHP 4.3.7 and higher can detect buggy IIS server software when you open the stream using the https:// wrapper and will suppress the warning for you. If you are using fsockopen() to create an ssl:// socket, you are responsible for detecting and suppressing the warning yourself. |
Vedere anche fgets(), file(), fread(), include(), readfile() e file_put_contents().
Identical to calling fopen(), fwrite(), and fclose() successively.
You can also specify the data parameter as an array (not multi-dimension arrays). This is equivalent to file_put_contents($filename, join('', $array)).
As of PHP 5.1.0, you may also pass a stream resource to the data parameter. In result, the remaining buffer of that stream will be copied to the specified file. This is similar with using stream_copy_to_stream().
The file name where to write the data
The data to write. Can be either a string, an array or a stream resource (explained above).
flags can take FILE_USE_INCLUDE_PATH, FILE_APPEND and/or LOCK_EX (acquire an exclusive lock), however the FILE_USE_INCLUDE_PATH option should be used with caution.
A context resource
Nota: Questa funzione è binary-safe (gestisce correttamente i file binari)
Nota: Il supporto per il contesto è stato aggiunto in PHP 5.0.0. Per la descrizione del contesto, fare riferimento a Riferimento CXLIV, Stream Functions.
Suggerimento: È possibile utilizzare una URL come un nome di file con questa funzione se fopen wrappers è stata abilitata. Per maggiori informazioni su come specificare i nomi di file vedere fopen() e Appendice M per avere la lista dei protocolli URL supportati.
Identica a readfile(), eccetto per il fatto che file() restituisce il file in un vettore. Ogni elemento del vettore corrisponde ad una riga del file, con il carattere di newline ancora inserito. Se la funzione non riesce restituisce FALSE.
Puoi impostare il secondo parametro, use_include_path, (opzionale) ad "1", se vuoi cercare il file nel include_path.
<?php // inserisce una pagina web in un array e la stampa. In questo esempio useremo il protocollo // HTTP per ottenere il sorgente di un URL $lines = file('http://www.example.com/'); // Ciclo attraverso l'array, si visualizzerà il sorgente come html ed i numeri di linea foreach($lines as $line_num => $line) { echo "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br />\n"; } // Un'altro esempio, inserisce la pagina web in una stringa. Vedere anche file_get_contents(). $html = implode('', file ('http://www.example.com/')); ?> |
Suggerimento: È possibile utilizzare una URL come un nome di file con questa funzione se fopen wrappers è stata abilitata. Per maggiori informazioni su come specificare i nomi di file vedere fopen() e Appendice M per avere la lista dei protocolli URL supportati.
Nota: Ciascuna riga dell'array restituito conterrà il carattere di fine riga, occorre, pertanto, utilizzare rtrim() se si desidera rimuovere il carattere di fine riga.
Nota: Se il PHP ha dei problemi a riconoscere la fine riga nella lettura di file su o creati da computer Macintosh, si può abilitare il parametro di configurazione auto_detect_line_endings.
Nota: A partire da PHP 4.3.0 si può utilizzare file_get_contents() per memorizzare il contenuto di un file in una stringa in formato binario.
Nota: Il supporto per il contesto è stato aggiunto in PHP 5.0.0. Per la descrizione del contesto, fare riferimento a Riferimento CXLIV, Stream Functions.
Avvertimento |
When using SSL, Microsoft IIS will violate the protocol by closing the connection without sending a close_notify indicator. PHP will report this as "SSL: Fatal Protocol Error" when you reach the end of the data. To workaround this, you should lower your error_reporting level not to include warnings. PHP 4.3.7 and higher can detect buggy IIS server software when you open the stream using the https:// wrapper and will suppress the warning for you. If you are using fsockopen() to create an ssl:// socket, you are responsible for detecting and suppressing the warning yourself. |
Vedere anche readfile(), fopen(), fsockopen(), popen(), file_get_contents() e include().
Restituisce l'ora in cui il file ha ricevuto l'ultimo accesso, o FALSE in caso di errore. L'ora viene restituita come un timestamp Unix.
N.B.: Si suppone che l'atime di un file cambi ogni volta che i blocchi di dati del file vengono letti. Ciò può risultare costoso per le performance quando una applicazione accede con regolarità ad un numero elevato di file o directory. Alcuni filesystem Unix possono essere montati con l'aggiornamento dell'atime disabilitato per aumentare le performance di tali applicazioni; Gli spool delle news USENET costituiscono un esempio frequente. In tali filesystem queste funzioni sono inutili.
Nota: I risultati di questa funzione saranno memorizzati. Vedere clearstatcache() per maggiori dettagli.
Suggerimento: A partire da PHP 5.0.0, questa funzione può essere utilizzata con alcuni URL wrappers. Fare riferimento a Appendice M per la lista di quali wrappers supportano le funzioni della famiglia stat().
Vedere anche filemtime(), fileinode() e date().
Restituisce l'ora in cui il file è stato cambiato l'ultima volta o FALSE in caso d'errore. L'ora viene restituita come un timestamp di Unix.
Nota: In molti filesystem Unix, si considera un file modificato, quando il suo inode viene cambiato; cioè quando i permessi, il proprietario, il gruppo o altri metadata dell'inode vengono aggiornati. Vedere anche filemtime() (che è ciò che ti serve se vuoi inserire la scritta "Ultima modifica: " nel piede delle tue pagine web) e fileatime().
Sappi anche che in alcuni testi su Unix si fa riferimento al ctime di un file come l'ora di creazione dello stesso. E' sbagliato. Nella maggioranza dei filesystem Unix non esiste un oa di creazione.
Nota: I risultati di questa funzione saranno memorizzati. Vedere clearstatcache() per maggiori dettagli.
Suggerimento: A partire da PHP 5.0.0, questa funzione può essere utilizzata con alcuni URL wrappers. Fare riferimento a Appendice M per la lista di quali wrappers supportano le funzioni della famiglia stat().
Esempio 1. Esempio di uso di fileatime()
|
Vedere anche filemtime().
Restituisce il l'ID del gruppo del file, o FALSE in caso d'errore. L'ID del gruppo viene restituito in formato numerico: usa posix_getgrgid() per trasformarlo nel nome del gruppo. In caso di errore la funzione restituisce FALSE accompagnato da un errore di di livello E_WARNING.
Nota: I risultati di questa funzione saranno memorizzati. Vedere clearstatcache() per maggiori dettagli.
Suggerimento: A partire da PHP 5.0.0, questa funzione può essere utilizzata con alcuni URL wrappers. Fare riferimento a Appendice M per la lista di quali wrappers supportano le funzioni della famiglia stat().
Vedere anche: fileowner() e safe_mode_gid.
Restituisce il numero di inode del file, o FALSE in caso d'errore.
Nota: I risultati di questa funzione saranno memorizzati. Vedere clearstatcache() per maggiori dettagli.
Suggerimento: A partire da PHP 5.0.0, questa funzione può essere utilizzata con alcuni URL wrappers. Fare riferimento a Appendice M per la lista di quali wrappers supportano le funzioni della famiglia stat().
Vedere anche stat().
Restituisce l'ora dell'ultima modifica al file o FALSE in caso d'errore. L'ora viene restituita come un timestamp di Unix.
Nota: I risultati di questa funzione saranno memorizzati. Vedere clearstatcache() per maggiori dettagli.
Suggerimento: A partire da PHP 5.0.0, questa funzione può essere utilizzata con alcuni URL wrappers. Fare riferimento a Appendice M per la lista di quali wrappers supportano le funzioni della famiglia stat().
Nota: Questa funzione restituisce l'ora in cui i blocchi di dati di un file vengono scritti, cioè l'ora in cui il contenuto del file è cambiato.
Vedere anche filectime(), stat(), touch() e getlastmod().
Restituisce l'ID dell'utente proprietario del file, o FALSE in caso di errore. L'ID dell'utente viene restituito in formato numerico, usa posix_getpwuid() per trasformarlo nel nome dell'utente stesso.
Nota: I risultati di questa funzione saranno memorizzati. Vedere clearstatcache() per maggiori dettagli.
Suggerimento: A partire da PHP 5.0.0, questa funzione può essere utilizzata con alcuni URL wrappers. Fare riferimento a Appendice M per la lista di quali wrappers supportano le funzioni della famiglia stat().
Vedere anche stat()
Restituisce i permessi sui file, or FALSE in caso di errore.
Nota: I risultati di questa funzione saranno memorizzati. Vedere clearstatcache() per maggiori dettagli.
Suggerimento: A partire da PHP 5.0.0, questa funzione può essere utilizzata con alcuni URL wrappers. Fare riferimento a Appendice M per la lista di quali wrappers supportano le funzioni della famiglia stat().
Esempio 2. Mostra gli interi permessi
Ciò produrrà il seguente output:
|
Vedi anche is_readable(), e stat()
Restituisce la dimensione di un file, o FALSE in caso d'errore.
Nota: Poichè il PHP tratta i tipi interi con il segno e diverse piattaforme utilizzano interi a 32 bit, filesize() può restituire valori non attendibili con file di dimensioni maggiori di 2GB. Per file con dimensione tra 2GB e 4GB si può tentare di ovviare utilizzando sprintf("%u", filesize($file)).
Nota: I risultati di questa funzione saranno memorizzati. Vedere clearstatcache() per maggiori dettagli.
Suggerimento: A partire da PHP 5.0.0, questa funzione può essere utilizzata con alcuni URL wrappers. Fare riferimento a Appendice M per la lista di quali wrappers supportano le funzioni della famiglia stat().
Vedere anche file_exists()
Restituisce il tipo del file. Sono valori possibili fifo, char, dir, block, link, file e unknown.
Restituisce FALSE se si verifica un errore. Inoltre la funzione filetype() genera un errore di livello E_NOTICE se fallisce la chiamata a stat o se il tipo è sconosciuto.
Nota: I risultati di questa funzione saranno memorizzati. Vedere clearstatcache() per maggiori dettagli.
Suggerimento: A partire da PHP 5.0.0, questa funzione può essere utilizzata con alcuni URL wrappers. Fare riferimento a Appendice M per la lista di quali wrappers supportano le funzioni della famiglia stat().
Vedere anche: is_dir(), is_file(), is_link(), file_exists(), stat() e mime_content_type().
Il PHP supporta un tecnologia portabile per bloccare file completi in modalità advisory (tutti i programmi che vi accedono, devono usare lo stesso tipo di bloccaggio o non funzionerà).
Nota: flock()è obbligatorio sotto Windows.
flock() opera su handle che deve essere un puntatore ad un file aperto. operation può assumere uno dei valori seguenti:
Per acquisire una chiave condivisa (in lettura), imposta operation a LOCK_SH (usa 1 prima di PHP 4.0.1).
Per acquisire una chiave esclusiva (in scrittura), imposta operation a LOCK_EX (usa 2 prima di PHP 4.0.1).
Per rilasciare una chiave (condivisa o esclusiva), imposta operation a LOCK_UN (usa 3 prima PHP 4.0.1).
Se non vuoi che flock() blocchi mentre, imposta come LOCK_NB (4 prima di PHP 4.0.1) operation.
flock() ti permette di utilizzare un semplice modello di lettura/scrittura che in teoria può essere usato su qualsiasi piattaforma (inclusi molti sistemi Unix e anche Windows). Il terzo argomento (opzionale) può essere impostato a TRUE se la chiave puo bloccare (EWOULDBLOCK errno condition). Il blocco è realizzato anche da fclose() (che è anche richiamata automaticamente quando lo script termina).
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: Poiché flock() richiede il puntatore ad un file, può occorre utilizzare un speciale file di lock per proteggere l'accesso a eventuali file che si desidera azzerare attraverso l'apertura in modalità di scrittura (usando "w" o "w+" come argomento di fopen()).
Avvertimento |
La funzione flock() non funzione con NFS e con diversi altri file system di rete. Verificare sulla documentazione del proprio sistema operativo. Su molti sistemi operativi flock() è implementato a livello di processo. Usando un server API multithread quale ISAPI non potrai basarti su flock() per proteggere i file da altri script PHP che girino in thread paralleli della stessa istanza del server! La funzione flock() non è supportata su file system antiquati tipo FAT e i suoi derivati e pertanto in tali ambienti restituirà sempre FALSE (questo è vero soprattutto per gli utenti di Windows 98). |
fnmatch() checks if the passed string would match the given shell wildcard pattern.
This is especially useful for filenames, but may also be used on regular strings. The average user may be used to shell patterns or at least in their simplest form to '?' and '*' wildcards so using fnmatch() instead of ereg() or preg_match() for frontend search expression input may be way more convenient for non-programming users.
Avvertimento |
For now this function is not available on Windows or other non-POSIX compliant systems. |
See also glob(), ereg(), preg_match() and the Unix manpage on fnmatch(3) for flag names (as long as they are not documented here ).
La funzione fopen() apre un collegamneto tra una risorsa, indicata dal parametro filename, ed un flusso. Se il parametro filename è del tipo "scheme://...", si assume essere un URL ed il PHP cercherà il modulo di gestione del protocollo (detto anche wrapper) per quello schema. Se non vi sono wrapper registrati per il protocollo richiesto, il PHP genererà un messaggio per aiutare a trovare potenziali problemi nello script e quindi procede considerando filename come un file regolare.
Se il PHP ha stabilito che filename indica un file locale, tenterà di aprire detto file come stream. Il file in oggetto dovrà esere accessibile dal PHP, occorre, pertanto, assicurasi che i permessi di accesso del file lo consentano. Se si è attivato il modalità sicura, oppure open_basedir si avranno ulteriori restrizioni.
Se il PHP ha stabilito che filename indica un protocollo registrato, e che tale protocollo è registrato come un URL di rete, il PHP verificherà che allow_url_fopen sia abilitato.Se fosse disabilitato, il PHP genererà un 'notice' e la funzione fallirà.
Nota: L'elenco dei protocolli supportati si trova in Appendice M. Alcuni protocolli (indicati anche come wrappers) supportano il context e/o le opzioni del php.ini Fare riferimento alle pagine specifiche del protocollo per avere l'elenco delle opzioni che possono essere utilizzate. (Ad esempio il parametro del php.ini user_agent è utilizzato dal wrapper http) Per una descrizione del contexts e del zcontext, fare riferimento a Riferimento CXLIV, Stream Functions.
Nota: Il supporto per il contesto è stato aggiunto in PHP 5.0.0. Per la descrizione del contesto, fare riferimento a Riferimento CXLIV, Stream Functions.
Nota: Come per PHP 4.3.2, la modalità di default è impostata a binarioper tutte le piattaforme che distinguono tra modalità binaria e testuale. Se si hanno problemi con i propri script dopo l'aggiornamento, provare a utilizzare il flag 't' come sostitutivo finchè si ha completato uno script maggiormente portabile come richiesto sopra.
Il parametro mode indica il tipo di accesso richiesto per il flusso. Esso può essere:
Tabella 1. Elenco dei possibili valori usati da fopen() per il parametro mode
mode | Descrizione |
---|---|
'r' | Apre in sola lettura; posiziona il puntatore all'inizio del file. |
'r+' | Apre in lettura e scrittura; posiziona il puntatore all'inizio del file. |
'w' | Apre il file in sola scrittura; posiziona il puntatore all'inizio del file e tronca il file alla lunghezza zero. Se il file non esiste, tenta di crearlo. |
'w+' | Apre in lettura e scrittura; posiziona il puntatore all'inizio del file e tronce il file alla lunghezza zero. Se il file non esiste, tenta di crearlo. |
'a' | Apre in sola scrittura; posiziona il puntatore alla fine del file. Se il file non esiste, tenta di crearlo. |
'a+' | Apre in lettura e scrittura; posiziona il puntatore alla fine del file. Se il file non esiste, tenta di crearlo. |
'x' | Crea ed apre il file in sola scrittura; posiziona il puntatore all'inizio del file. Se il file esiste già la chiamata a fopen() fallirà restituendo FALSE e verrà generato un errore di lievllo E_WARNING. Se il file non esiste si tenterà di crearlo. Questo equivale a specificare i flag O_EXCL|O_CREAT nella sottostante chiamata a open(2) . Questa opzione è supportata a partire dalla versione 4.3.2 di PHP, e funziona solo con i file locali. |
'x+' | Crea ed apre il file in lettura e scrittura; posiziona il puntatore all'inizio del file. Se il file esiste già la chiamata a fopen() fallirà restituendo FALSE e verrà generato un errore di lievllo E_WARNING. Se il file non esiste si tenterà di crearlo. Questo equivale a specificare i flag O_EXCL|O_CREAT nella sottostante chiamata a open(2) . Questa opzione è supportata a partire dalla versione 4.3.2 di PHP, e funziona solo con i file locali. |
Nota: Differenti famiglie di file system hanno differenti tipi di terminatori di riga. Quando si scrive un file di testo e si desidera inserire una interruzione di linea, occorre utilizzare il terminatore appropriato per il sistema operativo utilizzato. I sistemi basati su Unix utilizzano \n come terminatore di riga, i sistemi basati su Windows utilizzano \r\n mentre i sistemi Macintosh utilizzano \r.
Se si utilizza un errato terminatore di riga quando si scrivono i file, si può verificare che altre applicazioni accedendo a questi file abbiano comportamenti bizzarri.
Windows ha un flag di traduzione della modalità testo ('t') che in modo trasparente converte \n in \r\n mentre si lavora sul file. Ovviamente si ha anche il flag 'b' per forzare una modalità binaria, nella quale non si ha la conversione dei dati. Se si usano questi flag, 'b' oppure 't', devono essere posizionati come ultimo carattere del parametro mode.
La modalità di conversione di default dipende dalla SAPI e dalla versione di PHP che si sta utlizzando, pertanto si incoraggia l'uso dei flag appropriati per aumentare la portabilità degli script. Si dovrebbe utilizzare 't' se si lavora con dei file di testo, e si utilizza \n per indicare il fine linea, e ci si aspetta che che altre applicazioni, tipo notepad, leggano il file prodotto. In tutti gli altri casi si dovrebbe utilizzare 'b'
Se non si specifica il flag 'b' quando si lavora con file binari, si possono avere situazioni anomale nei dati, tipo immagini corrotte, e situazioni anomale con i caratteri \r\n.
Nota: Per la portabilità, si consiglia vivamente di usare sempre il flag 'b' quando si aprono files con fopen().
Nota: Inoltre, sempre per la portabilità, è anche fortemente raccomandato di aggiornare il codice che utilizza o che si avvale del mode 't' così da utilizzare il corretto terminatore di linea invece del 'b' mode.
Il terzo parametro opzionale use_include_path può essere impostato a '1' oppure a TRUE se si desidera cercare il file in include_path.
Se la open fallisce, la funzione restituisce FALSE e viene generato un errore di tipo E_WARNING. Si può utilizzare @ per sopprimere questo warning.
Se si dovessero manifestare dei problemi nella lettura o scrittura di file e si sta utilizzando la versione server di PHP, occorre verificare che i file e le directory utilizzate dallo script siano accessibili dal processo del server.
Sulla piattaforma Windows occorre prestare attenzione ai backslash nei percorsi dei file; questi devono essere preceduti dal caratteri di escape '\', oppure utilizzare lo slash '/'.
Avvertimento |
When using SSL, Microsoft IIS will violate the protocol by closing the connection without sending a close_notify indicator. PHP will report this as "SSL: Fatal Protocol Error" when you reach the end of the data. To workaround this, you should lower your error_reporting level not to include warnings. PHP 4.3.7 and higher can detect buggy IIS server software when you open the stream using the https:// wrapper and will suppress the warning for you. If you are using fsockopen() to create an ssl:// socket, you are responsible for detecting and suppressing the warning yourself. |
Nota: Quando safe-mode è abilitato, PHP controlla che la directory nella quale si sta lavorando, abbia lo stesso UID dello script che è in esecuzione.
Vedere anche Appendice M, fclose(), fgets(), fread(), fwrite(), fsockopen(), file(), file_exists(), is_readable(), stream_set_timeout() e popen().
Legge fino a EOF sul puntatore al file dato e scrive i risultati sul buffer di output.
Se si verifica un errore, fpassthru() restituisce FALSE. In caso positivo fpassthru() restituisce il numero di caratteri letti da handle scritti in output.
The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen().
Può essere necessario chiamarerewind() per resettare il puntatore al file all'inizio del file stesso nel caso si abbbia già scritto dai dati nel file. Il file viene chiuso quando si sia chiamata fpassthru() leggendolo (lasciandohandle inutilizzato).
Se desideri semplicemente inviare il contenuto di un file sul buffer di output, senza doverlo modificare o posizionarti in un particolare offset, potresti preferire readfile(), che ti salva la chiamata a fopen().
Nota: Quando si utilizza fpassthru() con file binari su sistemi Windows si dovrebbe essere certi di aprire il file in modalità binaria aggiungendo b alla modalità utilizzata nella chiamata a fopen().
Si incoraggia l'uso del flag b quando si trattano file binari, anche se il sistema non lo richiede; in questo modo si rendono gli script più trasportabili.
Esempio 1. Utilizzo di fpassthru() con file binari
|
Vedere anche readfile(), fopen(), popen() e fsockopen()
fputcsv() formats a line (passed as a fields array) as CSV and write it to the specified file handle. Returns the length of the written string, or FALSE on failure.
The optional delimiter parameter sets the field delimiter (one character only). Defaults as a comma: ,.
The optional enclosure parameter sets the field enclosure (one character only) and defaults to a double quotation mark: ".
Nota: Se il PHP ha dei problemi a riconoscere la fine riga nella lettura di file su o creati da computer Macintosh, si può abilitare il parametro di configurazione auto_detect_line_endings.
See also fgetcsv().
fread() legge fino a length byte dal puntatore al file indicato da handle. La lettura finisce quando sono stati letti length byte o è stata raggiunta EOF, o (nel caso di flussi via rete) quando un pacchetto divnta disponibile, in base a quale evento accada prima.
<?php // copia il contenuto di un file in una stringa $filename = "/usr/local/something.txt"; $handle = fopen($filename, "r"); $contents = fread($handle, filesize($filename)); fclose($handle); ?> |
Avvertimento |
Sui sistemi che differenziano fra file di testo e binari (ad esempio Windows) il file deve essere aperto con il parametro mode di fopen() impostato a 'b'. |
<?php $filename = "c:\\files\\somepic.gif"; $handle = fopen($filename, "rb"); $contents = fread($handle, filesize($filename)); fclose($handle); ?> |
Avvertimento |
Quando si ricevono dati via rete o pipe, tipo quelli ottenuti leggendo da file remoti o da popen() e fsockopen(), la lettura si fermerà dopo avere ricevuto il pacchetto disponibile. Questo significa che i dati sono ricevuti a blocchi che devono essere raggruppati, come illustrato nell'esempio seguente. |
<?php $handle = fopen("http://www.example.com/", "rb"); $contents = ''; while (!feof($handle)) { $contents .=fread($handle, 8192); } $contents .= $data; } while (true); fclose($handle); ?> |
Nota: Se si desidera ottenere il contenuto del file in una stringa, utilizzare la funzione file_get_contents() la quale è ancora più performante del codice precedente.
Vedere anche fwrite(), fopen(), fsockopen(), popen(), fgets(), fgetss(), fscanf(), file() e fpassthru().
La funzione fscanf() è simile a sscanf(), ma prende il proprio input da un file associato con handle e interpreta l'input in accordo con il parametro format, che viene descritto nella documentazione della funzione sprintf(). Se vengono passati solo due parametri a questa funzione, i valori esaminati verranno restituiti in un vettore. Altrimenti, se vengono passati i parametri opzionali, la funzione restituirà il numero dei valori assegnati. I parametri opzionali devono essere passati da reference.
Ogni spazio nella stringa di formato identifica uno spazio nel flusso di input. Questo significa che anche i tab \t presenti nella stringa di formato possono identiicare uno spazio nel flusso di input.
Nota: Nelle versioni di PHP precedenti alla 4.3.0, il numero massimo di caratteri letti da un file era di 512 (o fino al primo \n, dipende da quale si incontra prima). Dal PHP 4.3.0 si possono esaminare linee di lunghezza arbitraria.
Vedere anche fread(), fgets(), fgetss(), sscanf(), printf() e sprintf().
Imposta l'indicatore di posizione del file riferito da handle. La nuova posizione, misurata in byte dall'inizio del file, si ottiene aggiungendo offset alla posizione specificata da whence, i cui valori sono definiti come segue:
SEEK_SET - Imposta la posizione uguale a offset byte. |
SEEK_CUR - Imposta la posizione alla attuale più offset. |
SEEK_END - Imposta la posizione alla fine del file più offset. (To move to a position before the end-of-file, you need to pass a negative value in offset.) |
Se whence non viene specificato, viene assunto come SEEK_SET.
In caso di successo, restituisce 0; altrimenti, restituisce -1. Nota che spostarsi oltre EOF non è considerato un errore.
Non può essere usato su puntatori a file restituiti da fopen() se è in uso il formato "http://" o "ftp://". fseek() da anche risultati non definiti per stream in modalità append-only (aperti con il flag "a").
Nota: L'argomento whence è stato aggiunto dopo PHP 4.0.0.
(PHP 4, PHP 5)
fstat -- Restituisce le informazioni riguardanti un file attraverso un puntatore al file apertoRestituisce le statistiche del file aperto dal puntatore handle. Questa funzione è simile a stat() eccetto per il fatto che opera su un puntatore a file aperto invece che su un nome di file.
Restituisce un vettore con le statistiche del file con il formato del vettore è descritto nella pagina di stat().
Esempio 1. Esempio di uso di fstat()
l'esempio visualizzerà :
|
Nota: I risultati di questa funzione saranno memorizzati. Vedere clearstatcache() per maggiori dettagli.
Nota: Questa funzione non è eseguibile con file remoti, ma con file accessibili attraverso il filesystem del server.
Restituisce la posizione del puntatore al file indicato da handle; cioè, il suo offset all'interno del flusso del file.
Se si verifica un errore, restituisce FALSE.
Il puntatore al file deve essere valido e deve puntare ad un file aperto correttamente da fopen() o da popen(). ftell() da risultati non definiti per stream in modalità append-only (aperti col flag "a").
Prende il puntatore al file handle e tronca il file alla lunghezza indicata da size. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
fwrite() scrive il contenuto di string nel flusso del file puntato da handle. Se l'argomento length è specificato la scrittura si arresterà dopo aver scritto length byte o alla fine di string se si verificasse prima.
fwrite() returns the number of bytes written, or FALSE on error.
Nota che se il parametro length viene specificato, allora l'opzione di configurazione magic_quotes_runtime verrà ignorata e nessuno slash verrà skippato da string.
Nota: Su sistemi che differenzino fra file binari e di testo (come Windows) il file deve essere aperto includendo 'b' nel paramentro mode di fopen().
Esempio 1. Un semplice esempio di fwrite
|
Vedere anche fread(), fopen(), fsockopen(), popen() e file_put_contents().
The glob() function searches for all the pathnames matching pattern according to the rules used by the libc glob() function, which is similar to the rules used by common shells. No tilde expansion or parameter substitution is done.
Returns an array containing the matched files/directories or FALSE on error.
Valid flags:
GLOB_MARK - Adds a slash to each item returned
GLOB_NOSORT - Return files as they appear in the directory (no sorting)
GLOB_NOCHECK - Return the search pattern if no files matching it were found
GLOB_NOESCAPE - Backslashes do not quote metacharacters
GLOB_BRACE - Expands {a,b,c} to match 'a', 'b', or 'c'
GLOB_ONLYDIR - Return only directory entries which match the pattern
Nota: Before PHP 4.3.3 GLOB_ONLYDIR was not available on Windows and other systems not using the GNU C library.
GLOB_ERR - Stop on read errors (like unreadable directories), by default errors are ignored
Nota: GLOB_ERR was added in PHP 5.1
Esempio 1. Convenient way how glob() can replace opendir() and friends.
Output will look something like:
|
Nota: Questa funzione non è eseguibile con file remoti, ma con file accessibili attraverso il filesystem del server.
See also opendir(), readdir(), closedir(), and fnmatch().
Restituisce TRUE se il nome file esiste ed è una directory. Se filename è un nome file relativo, verrà controllato relativamente alla directory di lavoro in uso.
Nota: I risultati di questa funzione saranno memorizzati. Vedere clearstatcache() per maggiori dettagli.
Suggerimento: A partire da PHP 5.0.0, questa funzione può essere utilizzata con alcuni URL wrappers. Fare riferimento a Appendice M per la lista di quali wrappers supportano le funzioni della famiglia stat().
Vedere anche chdir(), dir, opendir(), is_file() e is_link().
Restituisce TRUE se il filename esiste ed è un eseguibile.
La funzione is_executable() sarà disponibile sui sistemi Windows a partire dalla versione 5.0.0 di PHP.
Nota: I risultati di questa funzione saranno memorizzati. Vedere clearstatcache() per maggiori dettagli.
Suggerimento: A partire da PHP 5.0.0, questa funzione può essere utilizzata con alcuni URL wrappers. Fare riferimento a Appendice M per la lista di quali wrappers supportano le funzioni della famiglia stat().
Restituisce TRUE se il filename esiste ed è un file regolare.
Nota: I risultati di questa funzione saranno memorizzati. Vedere clearstatcache() per maggiori dettagli.
Suggerimento: A partire da PHP 5.0.0, questa funzione può essere utilizzata con alcuni URL wrappers. Fare riferimento a Appendice M per la lista di quali wrappers supportano le funzioni della famiglia stat().
Restituisce TRUE se il filename esiste ed è un link simbolico.
Nota: I risultati di questa funzione saranno memorizzati. Vedere clearstatcache() per maggiori dettagli.
Suggerimento: A partire da PHP 5.0.0, questa funzione può essere utilizzata con alcuni URL wrappers. Fare riferimento a Appendice M per la lista di quali wrappers supportano le funzioni della famiglia stat().
Restituisce TRUE se filename esiste ed è leggibile.
Ricorda che PHP può accedere al file come l'utente che è rappresentato dal server (spesso 'nobody'). Non sono prese in conto limitazione di sicurezza.
Nota: I risultati di questa funzione saranno memorizzati. Vedere clearstatcache() per maggiori dettagli.
Suggerimento: A partire da PHP 5.0.0, questa funzione può essere utilizzata con alcuni URL wrappers. Fare riferimento a Appendice M per la lista di quali wrappers supportano le funzioni della famiglia stat().
Vedere anche is_writable(), file_exists() e fgets().
(PHP 3 >= 3.0.17, PHP 4 >= 4.0.3, PHP 5)
is_uploaded_file -- Dice se un file fù caricato via HTTP POST.Restituisce TRUE se il file chiamato per filename è stato spedito in upload col metodo HTTP POST. Ciò è utile per rendere sicuro il fatto da un utente malizioso non abbia cercato di forzare uno script ad agire sul file sul quale non dovrebbe essere svolto alcun lavoro--ad esempio, /etc/passwd.
Questo controllo è particolarmente importante in caso esista una qualunque possibilità che una qualunque cosa che viaggia durante l'upload del file, possa rivelarne il contenuto all'utente, o anche ad altri utenti che operano sullo stesso sistema.
is_uploaded_file() è disponibile solo nella versione PHP 3, dopo la 3.0.16, e nella versione 4 dopo la 4.0.2. Se hai delle perplessità nell'usare una versione più recente, puoi utilizzare una delle seguenti funzioni per proteggere te stesso:
Nota: L'esempio seguente not lavorerà con le versioni PHP 4 dopo la 4.0.2. Ciò dipende da funzionalità interne a PHP che sono variate dopo tale versione.
Esempio 1. is_uploaded_file() example
|
Vedi anche move_uploaded_file(), e la sezione Handling file uploads per un semplice esempio di utilizzo.
Restituisce TRUE se filename esiste ed è scrivibile. L'argomento filename può essere un nome di directory che ti permetta di verificare se una directory è scrivibile.
Tieni presente che PHP può accedere al file con lo user id del web server (spesso 'nobody'). Non sono prese in considerazioni limitazioni di sicurezza.
Nota: I risultati di questa funzione saranno memorizzati. Vedere clearstatcache() per maggiori dettagli.
Suggerimento: A partire da PHP 5.0.0, questa funzione può essere utilizzata con alcuni URL wrappers. Fare riferimento a Appendice M per la lista di quali wrappers supportano le funzioni della famiglia stat().
Vedere anche is_readable(), file_exists() e fwrite().
link() crea un hard link. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: Questa funzione non è eseguibile con file remoti, ma con file accessibili attraverso il filesystem del server.
Nota: Questa funzione non è implementata su piattaforme Windows
Vedere anche symlink() per creare soft link, e readlink() assieme a linkinfo().
linkinfo() restituisce il st_dev campo della struttura stat dello Unix C restituita dalla chiamata di sistema lstat. Questa funzione è usata per verificare se un link (puntato da path) esiste davvero (usando lo stesso metodo della macro S_ISLNK definita in stat.h). Restituisce 0 o FALSE in caso di errore.
Nota: Questa funzione non è implementata su piattaforme Windows
Vedere anche symlink(), link() e readlink().
Raccoglie le statistiche del file o del link simbolico chiamato filename.. Questa funzione è identica alla funzione stat() eccetto che se il paramametro filename è un link simbolico valido, viene restituito lo stato del link simbolico, non lo stato del file puntato dal link simbolico.
Nota: I risultati di questa funzione saranno memorizzati. Vedere clearstatcache() per maggiori dettagli.
Suggerimento: A partire da PHP 5.0.0, questa funzione può essere utilizzata con alcuni URL wrappers. Fare riferimento a Appendice M per la lista di quali wrappers supportano le funzioni della famiglia stat().
Vedere anche stat().
Tenta di creare la directory specificata da pathname.
Nota che probabilmente vuoi specificare mode come un ottale, per cui deve iniziare con uno zero. La modalità è anche modificata dall'umask corrente, che puoi cambiare con umask().
Nota: Il parametro mode è ignorato sui sistemi Windows, ed è opzionale dal PHP 4.2.0.
Il parametro mode viene impostato a 0777 per default; ciò significa dare i maggiori accessi possibili. Per maggiori dettagli sui valori di mode, leggere le pagine relative a chmod().
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: A partire da PHP 5.0.0 la funzione mkdir() può anche essere utilizzata con alcuni wrapper URL. Fare riferimento a Appendice M per avere l'elenco dei wrapper supportati da mkdir().
Nota: I parametri recursive e context sono stati aggiunti in PHP 5.0.0.
Nota: Quando safe-mode è abilitato, PHP controlla che la directory nella quale si sta lavorando, abbia lo stesso UID dello script che è in esecuzione.
Vedere anche rmdir().
Questa funzione verifica che il file indicato da filename è un file validamente caricato (nel senso che è stato caricato attraverso il meccanismo di caricamento HTTP POST di PHP). Se il file è valido, verrà spostato nel file dato da destination.
Se filename non è un file validamente caricato, allora non verrà compiuta alcuna azione e move_uploaded_file() restituirà FALSE.
Se filename è un file validamente caricato, ma non può essere mossi per qualche ragione, non verrà compiuto alcunchè e move_uploaded_file() restituirà FALSE. In più verrà visualizzato un avviso di pericolo.
Questo tipo di verifica è particolarmente importante se sussiste la possibilità che qualcosa fatto con i file caricati possa rivelare il loro contenuto agli utenti o ad altri utenti dello stesso sistema.
Nota: Quando safe-mode è abilitato, PHP controlla che i file o le directory sulle quali si sta andando a lavorare, abbiano lo stesso UID dello script che è in esecuzione.
Nota: move_uploaded_file() non è limitato dalle normali restrizioni del modalità sicura UID. QCiò non è insicuro poichè move_uploaded_file() operara solo sui file uplodati via PHP.
Avvertimento |
Se il file di destinazione esiste, sarà sovrascritto. |
Vedere anche is_uploaded_file() e la sessione Handling file uploads per un semplice esempio.
La funzione parse_ini_file() carica il file ini specificato da filename, e restituisce le impostazioni in un array associativo. Impostando process_sections a TRUE si ottiene una matrice multi-dimensionale con in nomi delle sezioni e le impostazioni ivi incluse. Per default process_sections è impostato a falso FALSE
Nota: Questa funzione non è collegata con il file php.ini. Questo è già elaborato al momento in cui gira lo script. Questa funzione può essere utilizzata per leggere i file ini propri dell'applicazione.
Nota: Se in un valore il file ini contiene caratteri non alfanumerici questi debbono essere delitimitati dai doppi apici (").
Nota: Dalla versione 4.2.1 di PHP questa funzione è limitata da by modalità sicura e da open_basedir.
Nota: Esistono parole riservate che non possono essere utilizzare come chiavi nei file ini. Queste includono: null, yes, no, true, and false.
La struttura del file ini è simile a quella del php.ini.
Le Costanti possono essere definite in un file ini, quindi se si definisce la costante come un valore da file ini prima di eseguire parse_ini_file(), la funzione integrerà nella costante il valore letto. Saranno considerati solo i valori ini. Ad esempio:
Esempio 2. Esempio di uso di parse_ini_file()
L'esempio produrrà:
|
La chiavi e le sezioni composte da numeri come considerate dal PHP come interi quindi i numeri che iniziano con 0 sono trattati come numeri ottali, e inumeri che iniziano con 0x sono considerati esadecimali.
pathinfo() restituisce un vettore associativo contenente informazioni riguardo path. Nel vettore vegono riportati i seguenti elementi: dirname, basename e extension.
Si può specificare quali elementi vengano restituiti con parametri opzionali options. E' composto da PATHINFO_DIRNAME, PATHINFO_BASENAME e PATHINFO_EXTENSION. Assume per defalut la restituzione di tutti gli elementi.
Nota: Per informazioni su come recuperare il path corrente, leggere la sezione su variabili riservate predefinite.
Vedere anche dirname(), basename(), parse_url() e realpath().
Chiude un puntatore ad una pipe aperto da popen().
Il puntatore deve essere valido e deve essere stato restituito da un chiamata a popen() terminata con successo.
Restituisce lo stato di terminazione del processo che stava girando.
Vedere anche popen().
Apre una pipe ad un processo eseguito forzando il comando dato da command.
Restituisce un puntatore a file identico a quello restituito da fopen(), eccetto che per il fatto che è unidirezionale (può solo essere usato per la lettura o la scrittura) e deve essere chiudo con pclose(). Questo puntatore può essere usato con fgets(), fgetss() e fwrite().
Se si verifica un errore, restituisce FALSE.
Nota: Se si sta cercando un supporto bi-direzionale (2 vie), utilizzare proc_open().
Se il comando che deve essere eseguito non è trovato, la funzione restituisce una risorsa valida. Questo sembra strano, ma ha un senso; esso permette di accedere ai messaggi di erore restituiti dalla shell:
<?php error_reporting(E_ALL); /* Aggiunge una redirezione, così possiamo ottenere stderr. */ $handle = popen('/path/to/spooge 2>&1', 'r'); echo "'$handle'; " . gettype($handle) . "\n"; $read = fread($handle, 2096); echo $read; pclose($handle); ?> |
Nota: Quando si abilita la modalità sicura, si può eseguire soltanto gli eseguibili presenti nella directory safe_mode_exec_dir. Per motivi pratici, attualmente, non ` permesso avere .. come componente del percorso di un eseguibile.
Avvertimento |
Con la modalità sicura attivata, tutte le parole che seguono il comando iniziale sono trattate come argomenti. Quindi, echo y | echo x diventa echo "y | echo x". |
Vedere anche pclose(), fopen() e proc_open().
Legge un file e lo scrive nello standard output.
Restituisce il numero di byte letti dal file. Se si verifica un errore viene restituito FALSE e se la funzione non è stata chiamata come @readfile(), un messaggio d'errore verra stampato.
Suggerimento: È possibile utilizzare una URL come un nome di file con questa funzione se fopen wrappers è stata abilitata. Per maggiori informazioni su come specificare i nomi di file vedere fopen() e Appendice M per avere la lista dei protocolli URL supportati.
Puoi settare il secondo parametro opzionale ad TRUE, se vuoi anche cercare il file nella include_path.
Vedere anche fpassthru(), file(), fopen(), include(), require() virtual(), file_get_contents() e Appendice M.
readlink() si comporta analogamente alla funzione readlink di C e restituisce i conenuti del link simbolico path oppure FALSE in caso d'errore.
Nota: Questa funzione non è implementata su piattaforme Windows
Vedere anche symlink(), readlink() e linkinfo().
realpath() espande tutti i link simbolici e risolve i riferimenti a '/./', '/../' ed altri caratteri '/' nell'input path e restituisce il percorso assoluto canonizzato. Il percorso risultante non avrà link simbolici, '/./' o '/../'.
realpath() restituisce FALSE in caso di fallimento, per esempio se il file non esiste.
Vedere anche basename(), dirname() e pathinfo().
Tenta di rinominare oldname in newname.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: Nelle versioni di PHP precedenti alla 4.3.3, la funzione rename() non può rinominare file attraverso partizioni nei sistemi *nix.
Nota: Dal PHP 5.0.0 rename() può anche essere utilizzata con qualche wrapper URL. Fare riferimento a Appendice M per avere l'elenco dei wrapper supportati da rename().
Nota: Il wrapper utilizzato per oldname DEVE essere il medesimo utilizzato per newname.
Nota: Il parametro context è stato aggiunto in PHP 5.0.0.
Vedere anche copy(), unlink() e move_uploaded_file().
Pone l'indicatore alla posizione del file per handle all'inizio del flusso del file.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Il puntatore al file deve essere valido e deve puntare ad un file aperto con successo da fopen().
Nota: If you have opened the file in append ("a") mode, any data you write to the file will always be appended, regardless of the file position.
Tenta di cancellare la directory indiata da pathname. La directory deve essere vuota e i permessi concessi devono permetterlo. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: Dal PHP 5.0.0 rmdir() può anche essere utilizzata con qualche wrapper URL. Fare riferimento a Appendice M per avere l'elenco dei wrapper supportati da rmdir().
Nota: Il parametro context è stato aggiunto in PHP 5.0.0.
Nota: Quando safe-mode è abilitato, PHP controlla che la directory nella quale si sta lavorando, abbia lo stesso UID dello script che è in esecuzione.
Restituisce una serie di informazioni a riguardo del file filename. Se il parametro filename è un link simbolico, le informazioni riguardano il file stesso, e non il file puntato dal link. La funzione lstat() è identica a stat() tranne che dovrebbe restituire il file puntato dal link.
In caso di errore stat() restituisce FALSE. Inoltre genera un warning.
La funzione restituisce un vettore con le informazioni sul file contenente i seguenti elementi. Il vettore parte dall'indice zero. Oltre agli indici numerici il vettore contiene indici associativi, come sarà indicato per ciascun parametro; questo è disponibile dal PHP versione 4.0.6.
Tabella 1. Formato del vettore restituito da stat() e fstat()
Indice numerico | Associativo (da PHP 4.0.6) | Descrizione |
---|---|---|
0 | dev | device |
1 | ino | inode |
2 | mode | modalità di protezione dell'inode |
3 | nlink | numero di link |
4 | uid | ID utente del proprietario |
5 | gid | ID del gruppo del proprietario |
6 | rdev | tipo di device con l'inode device * |
7 | size | dimensione in byte |
8 | atime | ora dell'ultimo accesso (Unix timestamp) |
9 | mtime | ora del'ultima modifica (Unix timestamp) |
10 | ctime | ora dell'ultimo cambiamento di inode(Unix timestamp) |
11 | blksize | dimensione del blocco per l'I/O di filesystem * |
12 | blocks | numero dei blocchi allocati |
Nota: I risultati di questa funzione saranno memorizzati. Vedere clearstatcache() per maggiori dettagli.
Suggerimento: A partire da PHP 5.0.0, questa funzione può essere utilizzata con alcuni URL wrappers. Fare riferimento a Appendice M per la lista di quali wrappers supportano le funzioni della famiglia stat().
Vedere anche lstat(), fstat(), filemtime() e filegroup().
symlink() crea un link simbolico dal target esistente con il nome specificato da link.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: Questa funzione non è implementata su piattaforme Windows
Vedere anche link() per creare hard link, e readlink() con linkinfo().
Crea un file con filename univoco nella directory specificata. Se la directory non esiste, tempnam() può generare un file in una directory temporanea di sistema, e restituire il nome di quest'ultima.
Precedentemente al PHP 4.0.6, il comportamento della funzione tempnam() dipendeva dal sistema. Su Windows il dispositivo di variabli TMP sovrascrive il dir parametro, su Linux la variabile TMPDIR ha la precedenza, mentre SVR4 utilizzerà sempre il parametro dir se la directory a cui punta, esiste. Consultare la vostra documentazione sulla funzione tempnam(3) in caso di dubbi.
Nota: Se PHP non può creare un file nello specificato dir parametro, ritorna al default di sistema.
Restituisce il nuovo nomefile temporaneo, o FALSE in caso di errore.
Nota: Il funzionamento di questa funzione è cambiato nella 4.0.3. Il file temporaneo è creato inoltre èer evitare un conflitto dove il file dovrebbe apparire nel filesystem tra la volta in cui la stringa viene generata e prima che lo script tenti di creare il file. Notare che se si necessita cancellare il file, se non servisse più, non viene fatto automaticamente.
Crea un file temporaneo con un nome univoco in modalità di lettura-scrittura (w+), restituendo un riferimento al file simile a quello tornato da fopen(). Il file viene automaticamente cancellato una volta chiuso (usando fclose()), o quando lo script termina.
Per dettagli, consulta la documentazione del tuo sistema sulla funzione tmpfile(3), così come il file haeader stdio.h.
Vedere anche tempnam().
Tenta di impostare l'ora di modifica del file indicato da filename. Se il parametro time non è passato, usa l'ora attuale. Ciò equivale a quello che fa utime (a volte indicato come utimes). Se è presente il terzo parametro opzionale atime è presente, viene utilizzato per impostare l'orario di accesso al file indicato. Occorre rilevare che l'orario di accesso è sempre modificato, indipendentemente dal numero dei parametri.
Se il file non esiste, viene creato.
umask() imposta l'umask di PHP a mask & 0777 e restituisce il vecchio umask. Quando PHP è utilizzato come modulo server, l'umask viene ripristinato quando ciascuna richiesta è finita.
umask() senza argomenti restituisce semplicemente l'umask corrente.
Cancella filename. Simile alla funzione C di Unix unlink(). Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: Dal PHP 5.0.0 unlink() potrà essere utilizzata anche con qualche wrapper URL. Fare riferimento a Appendice M per avere la lista di quali wrapper supportano unlink().
Nota: Il parametro context è stato aggiunto in PHP 5.0.0.
Restituisce 0 o FALSE in caso d'errore.
Vedere anche rmdir() per eliminare directory.
Firebird/InterBase è un database relazionale che offre diverse features ANSI SQL-92 che gira su sistemi Linux, Windows, e su diverse piattaforma Unix. Firebird/InterBase offre un'eccellente meccanismo di concorrenza, alte performance, ed un potente linguaggio a supporto per le stored procedure ed i trigger. E' attivo in sistemi di produzione, sotto diversi nomi, dal 1981.
InterBase è il nome della versione protetta di questo RDBMS che fu sviluppata da Borland/Inprise. Maggiori informazioni su InterBase sono disponibili al link http://www.borland.com/interbase/.
Firebird è un progetto commercialmente indipendente di programmatori C e C++, tecnici, supporter che hanno sviluppato e migliorato un database relazionale multi-piattaforma basato sul codice sorgente rilasciato da Inprise Corp (ora nota come Borland Software Corp) under the InterBase Public License v.1.0 on 25 July, 2000. More information about Firebird is available at http://www.firebirdsql.org/.
Nota: Questo modulo supporta la versione 5 e successive di InterBase e tutte le versioni di Firebird. Il supporto per la versione 5.x di InterBase sarà rimosso dalla versione 5 di PHP.
Questo database usa il carattere di singolo apice (') come carattere di escape, un comportamento simile al database Sybase, aggiungere al proprio file php.ini la seguente direttiva:
Per abilitare l'utilizzo di InterBase, configurare il PHP con --with-interbase[=DIR], dove DIR indica la directory di installazione di InterBase; il defualt è /usr/interbase.
Nota per gli utenti Win32: Per abilitare questo modulo nel mondo Windows, occorre copiare gds32.dll dalla cartella DLL della distribuzione PHP/Win32 alla cartella SYSTEM32 della machhina Windows. (Ad esempio: C:\WINNT\SYSTEM32 o C:\WINDOWS\SYSTEM32). Nel caso in cui il server InterBase sia sulla medesima macchina in cui gira il PHP, queste DLL sono già installate. Quindi non occorre copiare gds32.dll dalla cartella DLL.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. Parametri di configurazione di InterBase
Nome | Default | Modificabile |
---|---|---|
ibase.allow_persistent | "On" | PHP_INI_SYSTEM |
ibase.max_persistent | "-1" | PHP_INI_SYSTEM |
ibase.max_links | "-1" | PHP_INI_SYSTEM |
ibase.default_db | NULL | PHP_INI_SYSTEM |
ibase.default_user | NULL | PHP_INI_ALL |
ibase.default_password | NULL | PHP_INI_ALL |
ibase.default_charset | NULL | PHP_INI_ALL |
ibase.timestampformat | "%Y-%m-%d %H:%M:%S" | PHP_INI_ALL |
ibase.dateformat | "%Y-%m-%d" | PHP_INI_ALL |
ibase.timeformat | "%H:%M:%S" | PHP_INI_ALL |
Breve descrizione dei parametri di configurazione.
Stabilisce se permettere o meno le connessioni persistenti a Firebird/InterBase.
Indica il numero massimo di connessioni persistenti a Firebird/InterBase per processo. Le ulteriori connessioni create con ibase_pconnect() saranno non persistenti.
Indica il numero massimo di connessioni a Firebird/InterBase per processo, incluse le connessioni persistenti.
Il database di default a cui connettersi quando viene chiamata la funzione ibase_[p]connect() senza specifica del nome del database. Se questo valore è impostato ed è abilitata la modalità sicura SQL, non saranno permesse connessioni ad altri database.
Il nome utente da utilizzarsi per la connessione al database se non viene specificato.
La password da utilizzare per connettersi al database se non viene specificata in fase di connessione.
Il set di caratteri da utilizzare per la connessione al database se non ne viene specificato uno al momento della connessione.
Questo parametro è utilizzato per utilizzato per impostare il formato di data ed ora utilizzato per la restituzione di date ed ore dai set di risultati o per l'impostazione degli argomenti di data ed ora.
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Le seguenti costanti possono essere passate alle funzioni ibase_trans() per indicare il comportamento delle transazioni.
Tabella 2. Flag per le transazioni Firebird/InterBase
Costante | Descrizione |
---|---|
IBASE_DEFAULT | Sono utilizzate le impostazioni di default per la transazione. Quale default è determinato dalla libreria client, che, nella maggior parte dei casi, lo definisce come IBASE_WRITE|IBASE_CONCURRENCY|IBASE_WAIT. |
IBASE_READ | Inizia una transazione di sola lettura. |
IBASE_WRITE | Inizia una transazione di lettura/scrittura. |
IBASE_CONSISTENCY | Inizia una transazione con il livello di isolamento impostato a 'consistency', il quale indica che una transazione non leggere da tabelle che stanno per essere modificate da altre transazioni concorrenti. |
IBASE_CONCURRENCY | Inizia una transazione con il livello di isolamento impostato a 'concurrency' (o 'snapshot'), il quale indica che la transazione può accedere a tutte le tabelle, ma non può rilevare modifiche eseguite da altre transazioni dopo la partenza della transazione. |
IBASE_COMMITTED | Inizia una transazione con il livello di isolamento impostato a 'read committed'. Questo flag dovrebbe essere abbinato con IBASE_REC_VERSION oppure con IBASE_REC_NO_VERSION. Questo livello di isolamento permette l'accesso alle modifiche quando queste vengono eseguite dopo l'inizio della transazione. Se si indica IBASE_REC_NO_VERSION, si può accedere solo all'ultima versione della riga. Se si indica IBASE_REC_VERSION, una riga può essere letta anche se vi è una modifica pendente da parte di una transazione concorrente. |
IBASE_WAIT | Indica che la transazione deve attendere e riprovare in caso di conflitto. |
IBASE_NOWAIT | Indica che la transazione deve fallire immadiatamente in caso di conflitto di accesso. |
La seguenti costanti possono essere utilizzate con ibase_fetch_row(), ibase_fetch_assoc() o ibase_fetch_object() per indicare il comportamento nello scarico dei dati.
Tabella 3. Flag di scarico dati in Firebird/InterBase
Costante | Descrizione |
---|---|
IBASE_FETCH_BLOBS | Disponibile anche come IBASE_TEXT per compatibilità verso il passato. Forza lo scarico in linea dei contenuti BLOB, anzichè essere scaricati come indentificatori BLOB. |
IBASE_FETCH_ARRAYS | Forza lo scarico in linea delle matrici. Altrimenti le matrici sarebbero restituite come variabili. La matrici possono essere utilizzate come argomenti solo per le operazioni di INSERT, poichè, al momento, non vi sono funzioni che trattano le matrici. |
IBASE_UNIXTIME | Indica di restituire i dacmpi data e ora non come stringa, ma come UNIX timestamp (il numero dei secondi da una certa data, che è il 1-Gen-1970 0:00 UTC). Possono esserci problemi se utilizzato con date anteriori al 1970 su certi sistemi. |
Le seguenti costanti sono utilizzate per passare richieste ed opzioni alle (ibase_server_info(), ibase_db_info (), ibase_backup(), ibase_restore () e ibase_maintain_db()). Fare riferimento ai manuali di Firebird/InterBase per avere il significato di queste funzioni.
Options to ibase_backup()()
Options to ibase_restore()
Options to ibase_maintain_db()
Options to ibase_db_info()
Opzioni per ibase_server_info()
PHP 4 uses server, dba_user_name and dba_user_password instead of service_handle parameter.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
See also ibase_modify_user() and ibase_delete_user().
This function returns the number of rows that were affected by the previous query (INSERT, UPDATE or DELETE) that was executed from within the transaction context specified by link_identifier. If link_identifier is a connection resource, its default transaction is used.
See also ibase_query() and ibase_execute().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
ibase_blob_add() aggiunge dati ad un blob creato con ibase_blob_create().
Vedere anche ibase_blob_cancel(), ibase_blob_close(), ibase_blob_create() e ibase_blob_import().
Questa funzione cancella un BLOB creato da ibase_create_blob() se questo non è già stato chiuso da ibase_blob_close(). Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere anche ibase_blob_close(), ibase_blob_create() e ibase_blob_import().
Questa funzione chiude un BLOB aperto in lettura da ibase_open_blob() o aperto in scrittura da ibase_create_blob(). Se il BLOB è stato letto, questa funzione restituisce TRUE se riesce, se il BLOB è stato scritto, questa funzion restituisce la stringa contenente il BLOB id assegnato dal database. Se si verificano errori, questa funzione restituisce FALSE.
Vedere anche ibase_blob_cancel() e ibase_blob_open().
ibase_blob_create() crea un nuovo blob da riempire di dati. La funzione restituisce un puntatore al BLOB da utilizzare successivamente con ibase_blob_add() oppure FALSE se si verifica un errore.
Vedere anche ibase_blob_add(), ibase_blob_cancel(), ibase_blob_close() e ibase_blob_import().
Questa funzione apre un BLOB in lettura ed invia il suo contenuto direttamente allo standard output (prevalentemente il browser). Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere anche ibase_blob_open(), ibase_blob_close() e ibase_blob_get().
Questa funzine restituisce almeno len bytes da un BLOB che è stato aperto in lettura con ibase_blob_open(). Restituisce FALSE se si verifica un errore.
<?php $sql = "SELECT blob_value FROM table"; $result = ibase_query($sql); $data = ibase_fetch_object($result); $blob_data = ibase_blob_info($data->BLOB_VALUE); $blob_hndl = ibase_blob_open($data->BLOB_VALUE); echo ibase_blob_get($blob_hndl, $blob_data[0]); ?> |
Nota: Non è possibile leggere da un BLOB che è stato aperto in scrittura da ibase_blob_create().
Vedere anche ibase_blob_open(), ibase_blob_close() e ibase_blob_echo().
(PHP 3 >= 3.0.7, PHP 4, PHP 5)
ibase_blob_import -- Create un blob, copy il file al suo interno e lo chiudeQuesta funzione crea un BLOB e vi inserisce un file intero, lo chiude e restituisce l'id assegnato al BLOB. file_handle è un puntatore di file restituito da fopen(). La funzione restituisce FALSE se si verifica un errore.
Vedere anche ibase_blob_add(), ibase_blob_cancel(), ibase_blob_close() e ibase_blob_create().
(PHP 3 >= 3.0.7, PHP 4, PHP 5)
ibase_blob_info -- Restituisce la lunghezza del blob e altre informazioni utliliLa funzione restituisce un array contenente informazioni su un BLOB. Le informazioni restituite consistono nella lunghezza del BLOB, il numero di segmenti contenuti, la dimensione del segmento più grande, e se si tratta di un BLOB segmentato o a flusso.
ibase_blob_open() apre un BLOB esistente in lettura. Restituisce un puntatore al BLOB da usarsi successivamente con ibase_blob_get() oppure FALSE se si verifica un errore.
Vedere anche ibase_blob_close(), ibase_blob_echo() e ibase_blob_get().
Chiude il collegamento ad un database InterBase che è stato associato con un id di connessione restituito da ibase_connect(). Se l'id di connessione viene omesso, viene considerato l'ultimo collegamento che è stato aperto. La transazione predefinita sul collegamento viene "committed", le altre transazioni vengono "rolled back".
Vedere anche ibase_connect() e ibase_pconnect().
If called without an argument, this function commits the default transaction of the default link. If the argument is a connection identifier, the default transaction of the corresponding connection will be committed. If the argument is a transaction identifier, the corresponding transaction will be committed. The transaction context will be retained, so statements executed from within this transaction will not be invalidated. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Se chiamata senza parametri, la funzione esegue il commit della transazione di default, sul link di default. Se l'argomento identifica una transazione, verrà aseguito il commit della transazione di default su quella connessione. Se l'argomento identifica una transazione verrà eseguito il commit della transazione. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Stabilisce una connessione con un server InterBase. Il parametro database deve essere un percorso valido di un file di database sul server dove risiede. Se il server non fosse locale, bisogna aggiungere prima del percorso o 'hostname:' (TCP/IP), o '//hostname/' (NetBEUI) o 'hostname@' (IPX/SPX), in base al protocollo di connessione utilizzato. username e password possono venire specificati anche con le direttive di configurazione del PHP ibase.default_user e ibase.default_password. charset è il set di caratteri predefinito per un database. buffers è il numero di buffer di database da allocare per la cache dal lato server. Se è 0 o viene omesso, il server usa il suo valore predefinito. dialect seleziona il dialetto SQL predefinito per ogni operazione eseguita all'interno di una connessione, e il suo valore predefinito è il più alto supportato dalle librerie del client.
Nel caso di una seconda chiamata fatta con ibase_connect() con gli stessi parametri, non verrà creato alcun nuovo collegamento, bensì, l'identificatore del collegamento già aperto verrà restituito. Il collegamento al server verrà chiuso appena termina l'esecuzione dello script, a meno che non venga chiuso prima esplicitamente chiamando ibase_close().
Esempio 1. Esempio di ibase_connect()
|
Nota: Il parametro opzionale buffers è stato aggiunto in PHP 4.0.0.
Nota: dialect è stato aggiunto in PHP 4.0.0. E' funzionante solo con InterBase 6 e versioni successive.
Nota: role è stato aggiunto in PHP 4.0.0. E' funzionante solo con InterBase 5 e versioni successive.
Nota: Se si verificano degli errori tipo "arithmetic exception", "numeric overflow", oppure "string truncation. Cannot transliterate character between character sets" (questo capita quando si tenta di usare dei caratteri accentati) questa funzione o dopo la funzione ibase_query(), occorre impostare il set di caratteri (ad esempio ISO8859_1 oppure il set di caratteri corrente).
Vedere anche: ibase_pconnect() e ibase_close().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.2.0, PHP 5)
ibase_delete_user -- Delete a user from a security database (only for IB6 or later)PHP 4 uses server, dba_user_name and dba_user_password instead of service_handle parameter.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
See also ibase_add_user() and ibase_modify_user().
This functions drops a database that was opened by either ibase_connect() or ibase_pconnect(). The database is closed and deleted from the server. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also ibase_connect() and ibase_pconnect().
Returns the error code that resulted from the most recent InterBase function call. Returns FALSE if no error occurred.
See also ibase_errmsg().
Restituisce una stringa contenente un messaggio di errore dalla più recente funzione InterBse eseguita. La funzione restituisce FALSE se non vi sono errori.
Vedere anche ibase_errcode().
Esegue una query preparata da ibase_prepare(). Se la query genera un errore, la funzione restituisce FALSE. Se invece ha successo ed si ha un set di risultati (tipo un query SELECT), la funzione ne restituisce l'identificativo. Se la query ha successo e non vi sono risultati, restituisce TRUE
Ciò è molto più efficace che usare ibase_query() se state ripetendo uno stesso tipo di query molte volte cambiando solo alcuni parametri.
Esempio 1. Esempio di uso di ibase_execute()
|
Nota: In PHP 5.0.0 e successivi, questa funzione restituisce il numero di righe toccate dalla query (se >0 ed è applicabile al tipo di query). Una query che ha successo, ma che non modifica nessuna righa (ad esempio un UPDATE su record che non esistono) restituirà TRUE
Vedere anche ibase_query().
ibase_fetch_assoc() returns an associative array that corresponds to the fetched row. Subsequent calls will return the next row in the result set, or FALSE if there are no more rows.
ibase_fetch_assoc() fetches one row of data from the result. If two or more columns of the result have the same field names, the last column will take precedence. To access the other column(s) of the same name, you either need to access the result with numeric indices by using ibase_fetch_row() or use alias names in your query.
fetch_flag is a combination of the constants IBASE_TEXT and IBASE_UNIXTIME ORed together. Passing IBASE_TEXT will cause this function to return BLOB contents instead of BLOB ids. Passing IBASE_UNIXTIME will cause this function to return date/time values as Unix timestamps instead of as formatted strings.
See also ibase_fetch_row() and ibase_fetch_object().
Elabora una riga come un pseudo-oggetto da un result_id ottenuto o da ibase_query() o da ibase_execute().
<?php $dbh = ibase_connect($host, $username, $password); $stmt = 'SELECT * FROM tblname'; $sth = ibase_query($dbh, $stmt); while ($row = ibase_fetch_object($sth)) { echo $row->email . "\n"; } ibase_close($dbh); ?> |
Chiamate successive a ibase_fetch_object() restituiscono la successiva riga dai risultati della query o FALSE se non vi sono ulteriori righe.
Il parametro fetch_flag è una combinazione delle costanti IBASE_TEXT e IBASE_UNIXTIME con l'operatore OR. Passando IBASE_TEXT si forza questa funzione a resituire il contenuto del BLOB anzichè l'identificatore del BLOB. Passando IBASE_UNIXTIME si forza la funzione a restituire i valori di data/ora com Unix timestamp anzichè come stringa formattata.
Vedere anche ibase_fetch_row() e ibase_fetch_assoc().
Restituisce un array che corrisponde alla riga ottenuta o FALSE se non ci sono righe rimanenti.
ibase_fetch_row() prende una riga di dati dai risultati associati allo specificato result_identifier. La riga viene restituita come un array. Ogni colonna risultante viene immagazzinata in un offset dell'array, l'offset inizia da 0.
Chiamate successive a ibase_fetch_row() restituiscono la successiva riga dai risultati della query o FALSE se non vi sono ulteriori righe.
Restituisce un array con informazioni relative a un campo dopo che una query select è stata eseguita. L'array ha la forma name, alias, relation, length e 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"; } |
This function causes the registered event handler specified by event to be cancelled. The callback function will no longer be called for the events it was registered to handle. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also ibase_set_event_handler().
Libera un result set che è stato creato da ibase_query().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Returns new generator value as integer, or as string if the value is too big.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.2.0, PHP 5)
ibase_modify_user -- Modify a user to a security database (only for IB6 or later)PHP 4 uses server, dba_user_name and dba_user_password instead of service_handle parameter.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
See also ibase_add_user() and ibase_delete_user().
This function assigns a name to a result set. This name can be used later in UPDATE|DELETE ... WHERE CURRENT OF name statements. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
<?php $result = ibase_query("SELECT field1,field2 FROM table FOR UPDATE"); ibase_name_result($result, "my_cursor"); $updateqry = ibase_prepare("UPDATE table SET field2 = ? WHERE CURRENT OF my_cursor"); for ($i = 0; ibase_fetch_row($result); ++$i) { ibase_execute($updateqry, $i); } ?> |
See also ibase_prepare() and ibase_execute().
Restituisce un integer contenente il numero di campi in un 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 ("Nessun result è stato trovato per la tua query"); } ibase_close ($dbh); ?> |
Vedere anche: ibase_field_info().
This function returns the number of parameters in the prepared query specified by query. This is the number of binding arguments that must be present when calling ibase_execute().
See also ibase_prepare() and ibase_param_info().
Returns an array with information about a parameter after a query has been prepared. The array is in the form of name, alias, relation, length, type.
See also ibase_field_info() and ibase_num_params().
(PHP 3 >= 3.0.6, PHP 4, PHP 5)
ibase_pconnect -- Crea una connessione persistente ad un database Interbaseibase_pconnect() agisce in modo molto simile a ibase_connect() con due differenze principali. Innanzitutto, durante la connessione, la funzione cercherà prima di trovare un collegamento (persistente) che è già stato aperto con gli stessi parametri. Se viene trovato, il suo identificatore verrà restituito al posto di aprire una nuova connessione. In secondo luogo, la connessione al server InterBase non verrà chiusa al termine dell'esecuzione dello script. Invece, il collegamento resterà aperto per un uso futuro (ibase_close() non chiuderà i collegamenti stabiliti da ibase_pconnect()). Questo tipo di collegamento è perciò chiamato 'persistente'.
Nota: buffers è stato aggiunto in PHP4-RC2.
Nota: dialect è stato aggiunto in PHP4-RC2. Funziona soltanto con InterBase 6 e superiori.
Nota: role è stato aggiunto in PHP4-RC2. Funziona soltanto con InterBase 5 e superiori.
Vedere anche ibase_connect() per il significato dei parametri passati a questa funzione. Sono esattamente gli stessi.
(PHP 3 >= 3.0.6, PHP 4, PHP 5)
ibase_prepare -- Prepara una query per un successivo binding dei segnaposto dei parametri ed esecuzionePrepara una query per un successivo binding dei segnaposto dei parametri ed esecuzione (tramite ibase_execute()).
Esegue una query su di un database InterBase. Se la query non ha successo, restituisce FALSE. Se ha successo e vi sono riga di risultato (come si ha ad esempio con le query SELECT), restituisce un identificatore di risorsa. Se la query ha avuto successo, ma non ci sono risultati, restituisce TRUE. Restutuisce FALSE se la query fallisce.
Vedere anche ibase_errmsg(), ibase_fetch_row(), ibase_fetch_object() e ibase_free_result().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
If called without an argument, this function rolls back the default transaction of the default link. If the argument is a connection identifier, the default transaction of the corresponding connection will be rolled back. If the argument is a transaction identifier, the corresponding transaction will be rolled back. The transaction context will be retained, so statements executed from within this transaction will not be invalidated. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Rolls back transaction trans_number which was created with ibase_trans().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
This function registers a PHP user function as event handler for the specified events. The callback is called with the event name and the link resource as arguments whenever one of the specified events is posted by the database. The callback must return FALSE if the event handler should be canceled. Any other return value is ignored. This function accepts up to 15 event arguments.
<?php function event_handler($event_name, $link) { if ($event_name=="NEW ORDER") { // process new order ibase_query($link, "UPDATE orders SET status='handled'"); } else if ($event_name=="DB_SHUTDOWN") { // free event handler return false; } } ibase_set_event_handler($link, "event_handler", "NEW_ORDER", "DB_SHUTDOWN"); ?> |
The return value is an event resource. This resource can be used to free the event handler using ibase_free_event_handler().
See also ibase_free_event_handler() and ibase_wait_event().
(PHP 3 >= 3.0.6, PHP 4)
ibase_timefmt -- Imposta il formato delle colonne timestamp, date e time restituite dalle queryImposta il formato delle colonne di tipo timestamp, date o time restituite dalle query. Internamente, le colonne vengono formattate dalla funzione C strftime(), quindi fate riferimento alla sua documentazione riguardo al formato della stringa. columntype è una delle costanti IBASE_TIMESTAMP, IBASE_DATE e IBASE_TIME. Se omessa, è predefinita a IBASE_TIMESTAMP per motivi di compatibilità con il passato.
<?php // Le colonne di tipo TIME di InterBase vengono restituite nella // forma '05 hours 37 minutes'. ibase_timefmt("%H hours %M minutes", IBASE_TIME); ?> |
Potete impostare anche valori predefiniti per questi formati con la direttiva di configurazione ibase.timestampformat, ibase.dateformat e ibase.timeformat.
Nota: columntype è stata aggiunta in PHP 4.0. Ha significato solo con InterBase versione 6 e successive.
Nota: Un'incompatibilità con il passato si è avuta nel PHP 4.0 quando la direttiva di configurazione del PHP ibase.timeformat è stata rinominata in ibase.timestampformat e la direttiva ibase.dateformat e ibase.timeformat sono state aggiunte, così che i loro nomi fossero più simili alle loro funzionalità.
This function suspends execution of the script until one of the specified events is posted by the database. The name of the event that was posted is returned. This function accepts up to 15 event arguments.
See also ibase_set_event_handler() and ibase_free_event_handler().
Avvertimento |
Questo modulo è SPERIMENTALE. Ovvero, il comportamento di queste funzioni, i nomi di queste funzioni, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questo modulo è a vostro rischio. |
(no version information, might be only in CVS)
PDO_FIREBIRD DSN -- Connecting to Firebird and Interbase databasesThe PDO_FIREBIRD Data Source Name (DSN) is composed of the following elements:
The DSN prefix is firebird:.
The hostname on which the database server resides.
The port number for the server on which the database is running.
The name of the database.
The name of the user that will connect to the database.
The password for the user.
FriBiDi è un'implementazione free del Unicode Bidirectional Algorithm.
This PECL extension is not bundled with PHP. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: http://pecl.php.net/package/fribidi.
Per abilitare il supporto FriBiDi in PHP occorre compilare il PHP con l'opzione --with-fribidi[=DIR], dove DIR indica la directory di installazione di FriBiDi.
Gli utenti di Windows, per potere utilizzare queste funzioni, devono abilitare php_fribidi.dll dal php.ini. You may download this PECL extension DLL from the PHP Downloads page or at http://snaps.php.net/.
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Queste funzioni permettono di accedere ai servers del database FrontBase. Maggiori informazioni su FrontBase: http://www.frontbase.com/.
Documentazione su FrontBase : http://www.frontbase.com/cgi-bin/WebObjects/FrontBase.woa/wa/productsPage?currentPage=Documentation.
Il supporto Frontbase è stato aggiunto dal PHP 4.0.6.
Per potere utilizzare queste funzioni occorre installare o il server FrontBase o, al limite, le librerie fbsql client. Si può ottenere FrontBase da http://www.frontbase.com/.
Affinché queste funzioni siano disponibili è necessario compilare php con il supporto fbsql usando l' opzione --with-fbsql[=DIR].Se si usa questa opzione senza specificare il percorso a fbsql, php cercherà le librerie client di fbsql nella cartella di default specificata nell'istallazione di FrontBase, a seconda del sistema operativo. Se si installa FrontBase in una cartella non standard è necessario specificare sempre il percorso a fbsql: --with-fbsql=/path/to/fbsql. In questo modo si forzerà php ad usare le librerie client installate da FrontBase, evitando ogni conflitto.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. Opzioni di configurazione per FrontBase
Nome | Default | Modificabile |
---|---|---|
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 |
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
(PHP 4 >= 4.0.6, PHP 5)
fbsql_affected_rows -- Restituisce il numero di righe (tuple) interessate nella precedente operazione di FrontBasefbsql_affected_rows() restituisce il numero di righe interessate dall'ultima query INSERT, UPDATE or DELETE associata al parametro link_identifier. Se tale parametro non è stato specificato, sarà usata l'ultima connessione aperta da fbsql_connect().
Nota: Se si stanno usando le transazioni, è necessario chiamare la funzione fbsql_affected_rows() dopo una query INSERT, UPDATE, or DELETE, non dopo la chiusura della transazione (commit).
Se l'ultima query è un istruzione DELETE senza clausola WHERE, tutte le righe verranno cancellate dalla tabella e la funzione restituirà il valore 0 (zero).
Nota: Se si utilizza l'istruzione UPDATE, FrontBase non aggiornerà le colonne in cui il valore nuovo è uguale a quello vecchio. Quindi esiste la possibilità che fbsql_affected_rows() sia diverso dal numero di righe realmente interessate dalla query.
Se l'ultima query fallisce la funzione restituisce -1.
Vedere anche: fbsql_num_rows().
fbsql_autocommit() restituisce lo stato corrente di autocommit. Se è stato specificato il parametro opzionale OnOff, lo stato di autocommit verrà cambiato. Impostando il parametro OnOff su TRUE ogni istruzione verrà eseguita automaticamente, in caso di assenza di errori. Impostandolo su FALSE l'utente dovrà eseguire la transazione richiamando le funzioni fbsql_commit() o fbsql_rollback().
Vedere anche: fbsql_commit() e fbsql_rollback()
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
fbsql_change_user -- Cambia l'identità dell'utente connesso con una connessione attivafbsql_change_user() Cambia l'identità dell'utente connesso con una connessione attiva, o con la connessione specificata dal parametro opzionale link_identifier. Se è stato specificato un database, dopo che l'identità dell'utente sarà stata cambiata, questo diventerà il database attivo . Se l'autorizzazione del nuovo utente fallisce, rimarrà attiva l'identità dell'utente corrente.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Restituisce: TRUE in caso di successo, FALSE in caso di fallimento.
fbsql_close() chiude la connessione al server FrontBase associata ad uno specificato link identifier. Se il link_identifier non fosse specificato, verrebbe chiusa l'ultima connessione aperta.
Non è sempre necessario usare fbsql_close() nel caso di connessioni non permanenti, esse verranno chiuse automaticamente alla fine dell'esecuzione dello script.
Vedere anche: fbsql_connect() e fbsql_pconnect().
restituisce: TRUE in caso di successo, FALSE in caso di fallimento.
fbsql_commit() esegue la transazione corrente scrivendo tutti gli aggiornamenti pendenti, cancella il disco e sblocca tutte le righe della tabella bloccata dalla transazione. Questo comando è necessario solo nel caso in cui autocommit fosse impostato su false.
Vedere anche: fbsql_autocommit() e fbsql_rollback()
Restituisce un valore di link_identifier positivo in caso di successo, o un messaggio di errore in caso di fallimento.
fbsql_connect() Apre una connessione al Server FrontBase.Se i parametri opzionali non sono specificati verranno usati i valori seguenti come default: hostname = 'NULL', username = '_SYSTEM' e password = empty password.
Se si richiamasse, una seconda volta, la funzione fbsql_connect() con gli stessi argomenti, non si creerebbe una nuova connessione,ma verrebbe restituito il valore di link_identifier della connessione già aperta.
La connessione al server si chiuderà alla fine dello script, a meno che non venga chiusa in anticipo richiamando esplicitamente la funzione fbsql_close().
Vedere anche fbsql_pconnect() e fbsql_close().
Restituisce un handle al blob appena creato.
La funzione fbsql_create_blob() crea un campo blob a partire da blob_data. L'handle restituito può essere utilizzato con i comandi di inserimento e di aggiornamento dei blob nel database.
Esempio 1. Esempio di uso di fbsql_create_blob()
|
Vedere anche: fbsql_create_clob(), fbsql_read_blob(), fbsql_read_clob() e fbsql_set_lob_mode().
Restituisce un handle al CLOB appena creato.
La funzione fbsql_create_clob() crea un campo clob a partire da clob_data. L'handle restituito può essere utilizzato con i comandi di inserimento e di aggiornamento dei clob nel database.
Esempio 1. Esempio di uso di fbsql_create_clob()
|
Vedere anche: fbsql_create_blob(), fbsql_read_blob(), fbsql_read_clob() e fbsql_set_lob_mode().
fbsql_create_db() crea un nuovo database FrontBase sul server, identificato dal parametro link_identifier.
Vedere anche fbsql_drop_db().
Restituisce: TRUE in caso di successo, FALSE in caso di fallimento.
fbsql_data_seek() sposta il puntatore interno al risultato FrontBase associato con uno specificato indice in modo che punti ad un numero di riga specificata . La chiamata successiva alla funzionefbsql_fetch_row() restituirà la riga richiesta.
row_number comincia a contare da 0.
Esempio 1. fbsql_data_seek()
|
(PHP 4 >= 4.0.6, PHP 5)
fbsql_database_password -- Imposta o ricerca la password di un database FrontBase.Restituisce: La password del database identificato dal parametro link_identifier.
fbsql_database_password() imposta e ricerca la password del database corrente. Se il secondo parametro, opzionale (database_password), è stato specificato la funzione imposta, sul server, il valore del parametro come password del database identificato dal parametro link_identifier. Se il link_identifier non è specificato, verrà utilizzata l'ultima connessione aperta. Se nessuna connessione è aperta, la funzione tenterà di aprirne una come se la funzione fbsql_connect() fosse chiamata, e userà quella.
Questa funzione non modifica la password nel database e neppure è in grado ti recuperare la password di un database.
Esempio 1. Esempio di fbsql_create_clob()
|
Vedere anche: fbsql_connect(), fbsql_pconnect() e fbsql_select_db().
(PHP 4 >= 4.0.6, PHP 5)
fbsql_database -- Imposta oppure ottiene il nome del database usato per la connessione
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Restituisce: un indice FrontBase positivo come risultato della query, o FALSE in caso di errore.
fbsql_db_query() seleziona un database ed esegue la query su di esso.Se il parametro opzionale link_identifier non è stato specificato, la funzione ne cercherà una già aperta nel FrontBase server, in caso non ne trovasse alcuna aprirà una nuova connessione come se la funzione fbsql_connect() fosse chiamta senza argomenti.
Vedere anche: fbsql_connect().
Restituisce: un valore intero con lo stato corrente.
fbsql_db_status() richiede lo stato corrente del database specificato da database_name. Se il link_identifier viene omesso verrà usato quello in uso.
Il valore restituito potrà essere uno delle seguenti costanti:
FALSE - L'exec handler del host era invalido. Questo errore si presenta quando la connessione avviene direttamente al database, tramite il link_identifier, usando un numero di porta. FBExec può essere disponibile sul server ma nessuna connessione è stata creata.
FBSQL_UNKNOWN - Lo stato è sconosciuto.
FBSQL_STOPPED - Il database non è attivo. Usare fbsql_start_db() per attivare il database.
FBSQL_STARTING - Il database è in fase di attivazione.
FBSQL_RUNNING - Il database è attivo e può essere usato per eseguire operazioni SQL.
FBSQL_STOPPING - Il database é in fase di disattivazione.
FBSQL_NOEXEC - FBExec non è attivo sul server quindi non è possibile conoscere lo stato del database.
Vedere anche: fbsql_start_db() e fbsql_stop_db().
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
fbsql_drop_db() procede con l'eliminazione di un intero database dal server associato all'identificatore di link.
(PHP 4 >= 4.0.6, PHP 5)
fbsql_errno -- Ritorna il valore numerico del messaggio di errore emesso dalla precedente operazione FrontBase.Restituisce il numero di errore dell'ultima funzione fbsql, 0 (zero) se non ci sono stati errori.
Gli errori vengono restituiti dal database fbsql senza visualizzare i warnings. Usare fbsql_errno() per ricevere codice dell'errore. Da notare che questa funzione restituisce solamente il codice di errore proveniente dalla più recente esecuzione di una funzione fbsql (escludendo fbsql_error() e fbsql_errno()),così se si vuole usarla, assicurarsi di controllare il valore prima di richiamare un'altra funzione fbsql.
<?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>"; ?> |
Vedere anche: fbsql_error() e fbsql_warnings().
(PHP 4 >= 4.0.6, PHP 5)
fbsql_error -- Ritorna il testo del messaggio di errore emesso dalla precedente operazione FrontBase.Restituisce il testo del messaggio di errore dell'ultima funzione fbsql, o '' (una stringa vuota) se non ci sono stati errori.
Gli errori vengono restituiti dal database fbsql senza visualizzare i warnings. Usare fbsql_errno() per ricevere codice dell'errore. Da notare che questa funzione restituisce solamente il codice di errore proveniente dalla più recente esecuzione di una funzione fbsql (escludendo fbsql_error() e fbsql_errno()),così se si vuole usarla, assicurarsi di controllare il valore prima di richiamare un'altra funzione fbsql.
<?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>"; ?> |
Vedere anche: fbsql_errno() e fbsql_warnings().
(PHP 4 >= 4.0.6, PHP 5)
fbsql_fetch_array -- Restituisce una riga (tupla) di risultato in forma di Array associativo, Array enumerato o entrambiRestituisce un array che corrisponde alla riga di risultato, o FALSE se non ci sono righe successive.
fbsql_fetch_array() è una versione estesa di fbsql_fetch_row(). In aggiunta all'inserimento dei dati negli elementi dell'array con indice numerico, li inserisce anche in indici associativi, usando il nome dei campi come chiavi.
Se due o più colonne di risultato hanno lo stesso nome di campo , l'ultima colonna sovrascriverà la precedente con lo stesso nome. Per accedere alle altre colonne con lo stesso nome si deve usare l'indice numerico oppure fare un alias della colonna.
Una cosa importante da notare è che fbsql_fetch_array() NON è singnificativamente più lenta di fbsql_fetch_row(), mentre fornisce un significativo valore aggiunto.
Il secondo parametro opzionale, result_type in fbsql_fetch_array() è una costante che può assumere i seguenti valori: FBSQL_ASSOC, FBSQL_NUM, and FBSQL_BOTH.
Per ulteriori dettagli vedere anche fbsql_fetch_row() e fbsql_fetch_assoc().
Esempio 1. fbsql_fetch_array()
|
(PHP 4 >= 4.0.6, PHP 5)
fbsql_fetch_assoc -- Restituisce una riga (tupla) di risultato in forma di Array associativo.Restituisce un array associativo corrispondente alla riga di risultato, o FALSE se non ci sono righe successive.
fbsql_fetch_assoc() è equivalente ad una chiamata a fbsql_fetch_array() con FBSQL_ASSOC come parametro opzionale. Restituirà solo un array associativo. fbsql_fetch_array() originariamente lavora in questo modo. Se si vuole un indice numerico come pure quello associativo, usare fbsql_fetch_array().
Se due o più colonne di risultato hanno lo stesso nome di campo , l'ultima colonna sovrascriverà la precedente con lo stesso nome. Per accedere alle altre colonne con lo stesso nome si deve usare fbsql_fetch_array() che ritorna un indice numerico.
Una cosa importante da notare è che fbsql_fetch_assoc() NON è singnificativamente più lenta di fbsql_fetch_row(), mentre fornisce un significativo valore aggiunto.
Per maggiori dettagli, vedi anche fbsql_fetch_row() e fbsql_fetch_array().
(PHP 4 >= 4.0.6, PHP 5)
fbsql_fetch_field -- Ottiene informazioni su una colonna da un set di risultati come oggettoRestituisce un oggetto contenente le informazioni del campo.
La funzione fbsql_fetch_field() può essere utilizzata per ottenere informazioni sui campi da un set di risultati. Se non si specifica l'offset del campo, la funzione resituisce i le informazione sul campo successivo non ancora letto da fbsql_fetch_field().
Le proprietà dell'oggetto sono:
name - nome della colonna
table - nome della tabella da cui deriva la colonna
max_length - lunghezza massima della colonna
not_null - 1 se la colonna non può essere NULL
type - tipo di colonna
Esempio 1. Esempio di uso di fbsql_fetch_field()
|
Vedere anche fbsql_field_seek().
(PHP 4 >= 4.0.6, PHP 5)
fbsql_fetch_lengths -- Ottiene la lunghezza di ciascun output in un set di risultatiLa funzione restituisce un array contenente le lunghezze di ciascun campo nell'ultima riga letta da fbsql_fetch_row(), oppure FALSE se si verifica un errore.
fbsql_fetch_lengths() memorizza le lunghezze di ciascuna colonna dall'ultima riga letta da fbsql_fetch_row(), da fbsql_fetch_array() e da fbsql_fetch_object() in un vettore, partendo dall'offset 0.
Vedere anche fbsql_fetch_row().
La funzione restituisce un oggetto le cui properietà corrispondono lla riga letta, oppure FALSE se non vi sono più righe.
La funzione fbsql_fetch_object() è simile a fbsql_fetch_array(), con una differenza, resituisce un oggetto anzichè un array. Indirettamente ciò significa che si può accedere ai dati solo per nome dei campi e non per il loro offset (i numeri non sono nomi di proprietà validi).
Il parametro opzionale result_type è una costante e può assumere i seguenti valori: FBSQL_ASSOC, FBSQL_NUM, and FBSQL_BOTH.
Come performance la funzione è simile a fbsql_fetch_array(), e quasi veloce come fbsql_fetch_row() (le differenza è insignificante).
Vedere anche: fbsql_fetch_array() e fbsql_fetch_row().
Resituisce: una matrice corrispondente alla riga letta, oppure FALSE se non vi sono più righe.
La funzione fbsql_fetch_row() legge una riga del set di risultati indicato dal parametro result. La riga viene restituita come matrice. Ciascuna colonna è memorizzata in un indice della matrice. La matrice parte da 0.
Chiamate successive a fbsql_fetch_row() restituiscono la successiva riga dal set di risultati, oppure FALSE se non vi sono righe successive.
Vedere anche: fbsql_fetch_array(), fbsql_fetch_object(), fbsql_data_seek(), fbsql_fetch_lengths(), and fbsql_result().
La funzione fbsql_field_flags() restituisce i flag del campo indicato. I flag sono restituiti come parola singola per flag separata da spazi, in questo modo i valori restituiti possono essere suddivisi utilizzando explode().
La funzione fbsql_field_len() restituisce la lunghezza del campo indicato.
La funzione fbsql_field_name() restituisce il nome del campo indicato da field_index. Il parametro result deve essere un valido identificatore di un set di risultati e field_index l'indice del campo.
Nota: field_index parte da 0.
Esempio: l'indice del terzo campo sarà 2, l'indice del quarto sarà 3 e così via.
Esempio 1. Esempio di uso di fbsql_field_name()
L'esempio precedente visualizzerà:
|
(PHP 4 >= 4.0.6, PHP 5)
fbsql_field_seek -- Imposta il puntatore del set di risultati ad un specifico indice di campoSposta ad uno specifico indice di campo. Se la successiva chiamata a fbsql_fetch_field() non specifica alcun indice di campo, sarà restituito il campo il cui indice è impostato da fbsql_field_seek().
Vedere anche: fbsql_fetch_field().
Ottiene il nome della tabella in cui si trova il campo.
La funzione fbsql_field_type() è simile a fbsql_field_name(). Gli argomenti sono simili, ma restituisce il tipo di campo. I tipi restituiti saranno "int", "real", "string", "blob", e altri come specificato nella documentazione di FrontBase.
Esempio 1. Esempio di uso di fbsql_field_type()
|
La funzione fbsql_free_result() libera tutta la memoria associata al un set di risultati indicato da result.
Si dovrebbe richiamare la funzione fbsql_free_result() soltanto se si è preoccupati della quantità di memoria utilizzata per le query che restituiscono grosse quantità di dati. Tutta la memoria occupata dal set di risultati sarà liberata, in automatico, alla fine dell'esecuzione dello script.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.0.6, PHP 5)
fbsql_insert_id -- restituisce l'id generato dalla precedente operazione di INSERTLa funzione fbsql_insert_id() restituisce l'ID generato per una colonna definita come DEFAULT UNIQUE da una precedente query INSERT eseguita sulla connessione link_identifier. Se non si specifica link_identifier si assume l'ultimo link aperto.
fbsql_insert_id()restituisce 0 ise la precedente query non ha generato campo impostati a DEFAULT UNIQUE. Se si desidera salvare il valore per usi futuri, occorre essere sicuri di eseguire fbsql_insert_id() immediatamente dopo la query che genera il valore.
Nota: Il valore restituito dalla funzione fbsql_insert_id() di FrontBase SQL contiene sempre il più recente valore DEFAULT UNIQUE prodotto, e non viene azzerato tra le query.
La funzione fbsql_list_dbs() restituirà il puntatore ad un risultato contenente l'elenco dei databse disponibili dal corrente servizio fbsql. Utilizzare la funzione fbsql_tablename() per muoversi tra i risultati del puntatore
Nota: L'esempio precedente sarebbe semplice con fbsql_fetch_row() o altre funzioni simili.
fbsql_list_fields() recupera informazioni sulla tabella data. I parametri passati sono il nome del database ed il nome della tabella. La funzione resituisce un puntatore alle infomrazioni che può essere utilizzato con fbsql_field_flags(), fbsql_field_len(), fbsql_field_name() e fbsql_field_type().
Il valore restituito è un intero positivo. La funzione restituisce FALSE se si verifica un errore. In caso di errore, nel campo $phperrmsg si avrà un testo con la descrizione dell'errore, e, a meno che la funzione non sia richiamata come @fbsql() questo testo sarà visualizzato.
Esempio 1. Esempio di uso di fbsql_list_fields()
L'esempio precedente visualizzerà:
|
La funzione fbsql_list_tables() prende il nome del database e restituisce e restituisce un puntatore come la funzione fbsql_db_query(). A questo punto occorre utilizzare la funzione fbsql_tablename() per ottenere il nome delle tabelle dal puntatore ottenuto.
Quando si invia più di un comando SQL al server o si esegue una 'stored procedure' che generi più risultati, si spinge il server a generare più set di risultati. Questa funzione verifica la disponibilità di set aggiuntivi dal server. Se esiste un set di risultati aggiuntivo, la funzione libererà la memoria del set corrente e si prepare a scaricare il nuovo. La funzione restituisce TRUE se è disponibile un nuovo set di risultati, oppure FALSE se non ve ne sono.
Esempio 1. Esempio di uso di fbsql_next_result()
|
(PHP 4 >= 4.0.6, PHP 5)
fbsql_num_fields -- Ottiene il numero dei campi presenti in un set di risultatifbsql_num_fields() restituisce il numero dei campi in un set di risultati.
Vedere anche: fbsql_db_query(), fbsql_query(), fbsql_fetch_field() e fbsql_num_rows().
(PHP 4 >= 4.0.6, PHP 5)
fbsql_num_rows -- Restituisce il numero di righe presenti in un set di risultatifbsql_num_rows() restituisce il numero di righe presenti in un set di risultati. Questo comando vale solo per le SELECT. Per sapere il numero di righe coinvolte da un INSERT, UPDATE o DELETE, utilizzare fbsql_affected_rows().
Vedere anche: fbsql_affected_rows(), fbsql_connect(), fbsql_select_db() e fbsql_query().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Restituisce: un identificatore della connessione come numero positivo se la connessione riesce, oppure FALSE se la connessione non riesce.
La funzione fbsql_pconnect() stabilisce una connessione con un server FrontBase. I seguenti valori saranno usati come defualt per i parametri omessi: host = 'localhost', username = "_SYSTEM" e password = password vuota.
Per impostare il numero di porta del server FrontBase utilzzare fbsql_select_db().
fbsql_pconnect() agisce in modo simile a fbsql_connect() con due differenze.
Primo, durante la connessione la funzione prima tenta di trovare una connessione (persistente) per il medesimo server già aperta, con il medesimo utente e la medesima password. Se si trova una connessione verrà restituito l'identificatore di questa piuttosto che aprire una nuova connessione.
Secondo, la connessione al server SQL non verrà chiusa al termine dello script. Resterà, invece. aperta per usi futuri.
Questo tipo di connessione è, quindi, chiamata 'persistente'.
La funzione fbsql_query() invia una query al database al database attivo sul collegamento identificato da link_identifier. Se non si specifica link_identifier, si utilizzerà l'ultimo collegamento aperto. Se non vi sono collegamenti attivi la funzione tenta di stabilirne uno come se si chiamasse fbsql_connect() senza parametri.
Nota: Il testo della query deve terminare sempre con punto e virgola.
La funzione fbsql_query() restituisce TRUE (non-zero) oppure FALSE per indicare se la query ha avuto successo o meno. Un valore di ritorno pari a TRUE indica che la query è valida e può essere eseguita dal server. Il valore di ritorno non indica nulla su quante sono le righe coinvolte. Pertanto è possibile che una query abbia successo, ma non coinvolga alcuna riga.
La seguente query è errata, pertanto fbsql_query() fallirà e restituirà FALSE:
La seguente query è semanticamente errata se my_col non è una colonna della tabella my_tbl, pertanto fbsql_query() fallirà e restituirà FALSE:
Inoltre fbsql_query() fallirà e restituirà FALSE se non si hanno i permessi per accedere alle tabelle referenziate dalla query.
Quando la query ha successo, si può utilizzare fbsql_num_rows() per sapere quante righe saranno restituite da un'istruzione SELECT, oppure si può utilizzare fbsql_affected_rows() per sapere quante righe sono state toccate da un DELETE, INSERT, REPLACE o UPDATE.
Per i comandi SELECT, la funzione fbsql_query() restituisce l'identificatore ad un nuovo set dirsultati, che può essere passato a fbsql_result(). Quando si è completato il lavoro con un set di risultati, si può liberare le risorse occupate da questo chiamando fbsql_free_result(). Si ricorda, comunque, che la memoria verrà liberata automaticamente al termine dell'esecuzione dello script.
Vedere anche: fbsql_affected_rows(), fbsql_db_query(), fbsql_free_result(), fbsql_result(), fbsql_select_db() e fbsql_connect().
Restituisce: una stringa contenente il BLOB indicato da blob_handle.
La funzione fbsql_read_blob() legge un campo BLOB dal database. Se una istruzione select contiene colonne BLOB e/o CLOB FrontBase restituisce direttamente i dati quando è richiesta la riga. Questo è il comportamento di default, esso può essere variato tramite fbsql_set_lob_mode() in modo che le funzioni di lettura dei dati restituiscano un puntatore ai dati BLOB e CLOB. Se si ottiene il puntatore occorre eseguire fbsql_read_blob() per ottenere i dati BLOB dal database.
Esempio 1. Esempio di uso di fbsql_read_blob()
|
Vedere anche: fbsql_create_blob(), fbsql_read_blob(), fbsql_read_clob() e fbsql_set_lob_mode().
Restituisce: una stringa contenente il CLOB indicato da clob_handle.
La funzione fbsql_read_clob() legge un campo CLOB dal database. Se una istruzione select contiene colonne BLOB e/o CLOB FrontBase restituisce direttamente i dati quando è richiesta la riga. Questo è il comportamento di default, esso può essere variato tramite fbsql_set_lob_mode() in modo che le funzioni di lettura dei dati restituiscano un puntatore ai dati BLOB e CLOB. Se si ottiene il puntatore occorre eseguire fbsql_read_clob() per ottenere i dati CLOB dal database.
Esempio 1. Esempio di uso di fbsql_read_clob()
|
Vedere anche: fbsql_create_blob(), fbsql_read_blob(), fbsql_read_clob() e fbsql_set_lob_mode().
La funzione fbsql_result() restituisce il contenuto di una cella da un set di risultati di una query a FrontBase. L'argomento field può essere l'offset del campo, o il nome del campo, oppure nome della tabella del campo punto nome del campo (nometabella.nomecampo). Se il nome della colonna ha un alias ('select foo as bar from...'), usare l'alias al posto del nome della colonna.
Quando si lavora con grandi set di risultati, si può considerare l'utilizzo delle funzioni che restituiscono l'intera riga (elencate di seguito). Poichè queste restituiscono il contenuto di più celle con una singola chiamata, esse sono MOLTO più veloci che fbsql_result(). Occorre far notare, inoltre, che specificando l'offset numerico del campo si ottiene un'esecuzione più veloce rispetto alla specifica del nome del campo o di nometabella.nomecampo.
Le chiamate a fbsql_result() non dovrebbero essere mischiate con con chiamate ad altre funzioni che agiscano sul set di risultati.
Alternative più performanti raccomandate: fbsql_fetch_row(), fbsql_fetch_array() e fbsql_fetch_object().
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
La funzione fbsql_rollback() termina la transazione corrente eseguendo il rollback di tutte le istruzioni dall'ultimo commit. Questo comando è necessario solo se autocommit è impostato a false.
Vedere anche: fbsql_autocommit() e fbsql_commit()
La funzione fbsql_select_db() attiva il database corrente sul server associato alla connessione specificata da link_identifier Se non si passa link_identifier, si considera l'ultima connessione aperta. Se non vi sono connessioni aperte, la funzione tenta di stabilirne una come se fosse eseguita la funzione fbsql_connect().
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Il client contatta FBExec per ottenere il numero diporta per stabilire la connessione al database. Se database_name è un numero il sistema userà quel numero come porta e non chiederà un numero di porta a FBExec. Il server FrontBase può essere avviato come FRontBase -FBExec=No -port=<port number> <database name>.
Ogni chiamata successiva a fbsql_query() sarà eseguita sul database attivo.
Se il database è protetto con una password, l'utente deve eseguire fbsql_database_password() prima di selezionare il database.
Vedere anche: fbsql_connect(), fbsql_pconnect(), fbsql_database_password() e fbsql_query().
(PHP 4 >= 4.2.0, PHP 5)
fbsql_set_lob_mode -- Imposta la modalità LOB in un set di risultati FrontBaseRestituisce: TRUE se ha successo, FALSE se si verifica un errore.
La funzione fbsql_set_lob_mode() la modalità per il recupero dei dati LOB dal database. Quando i dati BLOB e CLOB sono memorizzati in FrontBase questi possono essere memorizzati direttamente o indirettamente. I dati LOB archiviati direttamente sono sempre recuperati a prescindere dell'impostazione della modalità LOB. Se i dati LOB sono meno di 512 byte saranno sempre archiviati direttamente.
FBSQL_LOB_DIRECT - I dati LOB sono recuperati direttamente. Quando i dati sono ottenuti dal database con fbsql_fetch_row(), o altre funzioni per il recupero dei dati, tutte le colonne BLOB saranno restituite come colonne ordinarie. Questo è il valore di default in un nuovo set di risultati.
FBSQL_LOB_HANDLE - I dati LOB sono recuperati come puntatori ai dati. Quando si recupera le informazioni da un database con fbsql_fetch_row (), o altre funzioni per il recupero dei dati, i dati LOB saranno restituiti come handle ai dati, se questi sono stati memorizzati indirettamente o saranno restituiti direttamente i dati se questi sono memorizzati in modo diretto. Se la funzione restituisce un handle, questo sarà una stringa di 27 byte con il formato tipo "@'000000000000000000000000'".
Vedere anche: fbsql_create_blob(), fbsql_create_clob(), fbsql_read_blob() e fbsql_read_clob().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
fbsql_start_db()
Vedere anche: fbsql_db_status() e fbsql_stop_db().
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
fbsql_stop_db()
Vedere anche: fbsql_db_status() e fbsql_start_db().
La funzione fbsql_tablename() utilizza il puntatore al risultato restituito da fbsql_list_tables() e restituisce il nome della tabella. Si può, inoltre, utilizzare la funzione fbsql_num_rows() per determinare il numero di tabelle presenti in un risultato.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Le funzioni in questa estensione implementano l'accesso client ad un file server utilizzando il File Transfer Protocol (FTP) come definito in http://www.faqs.org/rfcs/rfc959.html.
Usando il modulo FTP vengono definite le seguenti costanti: FTP_ASCII e FTP_BINARY.
Per l'utilizzo delle funzioni FTP con la vostra configurazione PHP, dovrete aggiungere l'opzione --enable-ftp durante l'installazione PHP 4, e --with-ftp nell'installazione di PHP 3.
Esempio 1. FTP
|
Sends an ALLO command to the remote FTP server to allocate space for a file to be uploaded.
Nota: Many FTP servers do not support this command. These servers may return a failure code (FALSE) indicating the command is not supported or a success code (TRUE) to indicate that pre-allocation is not necessary and the client should continue as though the operation were successful. Because of this, it may be best to reserve this function for servers which explicitly require preallocation.
The link identifier of the FTP connection.
The number of bytes to allocate.
A textual representation of the servers response will be returned by reference in result if a variable is provided.
Esempio 1. ftp_alloc() example
|
Passa alla directory superiore.
Esempio 1. ftp_cdup() example
|
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedi anche ftp_chdir().
Passa dalla directory corrente alla directory specificata.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Esempio 1. esempio ftp_chdir()
|
Vedi anche ftp_cdup().
Sets the permissions on the specified remote file to mode.
The link identifier of the FTP connection.
The new permissions, given as an octal value.
The remote file.
Esempio 1. ftp_chmod() example
|
ftp_close() chiude ftp_stream e rilascia la risorsa. Dopo aver chiamato questa funzione, non e' piu' possibile usare la connessione FTP ed e' necessario crearne una nuova con ftp_connect().
Esempio 1. esempio di funzione ftp_close()
|
Vedere anche ftp_connect()
Restituisce un flusso FTP stream in caso di successo, FALSE in caso di errore.
La funzione ftp_connect() apre una connessione FTP all' host specificato. host non deve essere seguito da barre e non deve essere precedeuto da ftp://. Il parametro port specifica una porta alternativa cui connettersi. Se e' omesso o impostato a zero verra' usata la porta 21, default di FTP.
Il parametro timeout specifica il timeout per tutte le successive operazioni di rete. Se omesso il valore predefinito e' di 90 secondi. Il timeout puo' essere modificato o interrogato in qualsiasi momento con ftp_set_option() e ftp_get_option().
Nota: Il parametro timeout e' disponibile a partire dalla release PHP 4.2.0.
Vedere anche ftp_close(), e ftp_ssl_connect().
ftp_delete() cancella il file specificato da path dal server FTP.
Esempio 1. Esempio di funzione ftp_delete()
|
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Invia una richiesta SITE EXEC command al server FTP. Restituisce TRUE se il comando viene eseguito correttamente (codice di risposta: 200 da parte del server); altrimenti restituisce FALSE.
Esempio 1. Esempio di funzione ftp_exec()
|
Vedere anche ftp_raw().
(PHP 3 >= 3.0.13, PHP 4, PHP 5)
ftp_fget -- Scarica un file dal server FTP e lo salva su un file apertoftp_fget() recupera remote_file dal server FTP, e lo scrive sul file specificato dal puntatore, handle. Il modo di trasferimento mode specificato deve essere FTP_ASCII oppure FTP_BINARY.
Esempio 1. Esempio di funzione ftp_fget()
|
Nota: Il parametro resumepos e' stato aggiunto in PHP 4.3.0.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere anche ftp_get(), ftp_nb_get() e ftp_nb_fget().
ftp_fput() carica i dati del file cui fa riferimento il puntatore handle fino a quando viene raggiunta la fine del file. I risultati sono salvati in remote_file sul server FTP. Il modo di trasferimento mode specificato deve essere FTP_ASCII oppure FTP_BINARY.
Esempio 1. Esempio di funzione ftp_fput()
|
Nota: Il parametro startpos e' stato aggiunto in PHP 4.3.0.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere anche ftp_put(), ftp_nb_fput(), e ftp_nb_put().
(PHP 4 >= 4.2.0, PHP 5)
ftp_get_option -- Recupera diversi comportamenti dello stream FTP durante l'esecuzioneRestituisce il valore in caso di successo oppure FALSE se l'opzione option data non e' supportata. In quest'ultimo caso, viene anche visualizzato un messaggio di avvertimento.
Questa funzione restituisce il valore dell'opzione option richiesta dallo stream FTP ftp_stream specificato. Attualmente sono riconosciute le seguenti opzioni:
Tabella 1. Opzioni di runtime FTP riconosciute
FTP_TIMEOUT_SEC | Restituisce il timeout corrente, usato in operazioni di rete. |
Vedere anche ftp_set_option().
ftp_get() recupera remote_file dal server FTP, e lo salva sul file locale local_file. Il modo di trasferimento mode specificato deve essere FTP_ASCII oppure FTP_BINARY.
Nota: Il parametro resumepos e' stato aggiunto in PHP 4.3.0.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Esempio 1. Esempio di funzione ftp_get()
|
Vedere anche ftp_fget(), ftp_nb_get() e ftp_nb_fget().
Esegue il log allo stream FTP richiesto.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Esempio 1. Esempio di funzione ftp_login()
|
(PHP 3 >= 3.0.13, PHP 4, PHP 5)
ftp_mdtm -- Restituisce l'orario dell'ultima modifica al file correnteLa funzione ftp_mdtm() controlla l'orario dell'ultima modifica ad un file, e lo restituisce in formato timestamp Unix. Se si verifica un errore, o il file non esiste, restituisce -1.
Restituisce un timestamp Unix in caso di successo, o -1 in caso di errore.
Esempio 1. Esempio di funzione ftp_mdtm()
|
Nota: Non tutti i server includono questa funzione!
Nota: La funzione ftp_mdtm() non funziona con le directories.
Crea la directory specificata sul server FTP.
Restituisce la directory appena creata in caso di successo o FALSE in caso di errore.
Esempio 1. Esempio di funzione ftp_mkdir()
|
Vedere anche ftp_rmdir().
(PHP 4 >= 4.3.0, PHP 5)
ftp_nb_continue -- Continua a ricevere/trasmettere un file in modalita' non bloccanteContinua a ricevere/trasmettere un file in modalita' non bloccante.
Esempio 1. Esempio di funzioneftp_nb_continue()
|
Restituisce FTP_FAILED oppure FTP_FINISHED oppure FTP_MOREDATA.
(PHP 4 >= 4.3.0, PHP 5)
ftp_nb_fget -- Recupera un file dal server FTP e lo scrive su un file aperto, in modalita' non bloccanteLa funzione ftp_nb_fget() recupera remote_file dal server FTP, e lo scrive nella posizione cui punta il puntatore a file handle. La modalita' di trasferimento, mode, specificata deve essere FTP_ASCII oppure FTP_BINARY. La differenza tra questa funzione e la funzione ftp_fget() e' che questa funzione recupera il file in modo asincrono, cosicche' il programma puo' eseguire altre operazioni mentre il file viene scaricato.
Esempio 1. Esempio di funzione ftp_nb_fget()
|
Restituisce FTP_FAILED, FTP_FINISHED, oppure FTP_MOREDATA.
Vedere anche ftp_nb_get(), ftp_nb_continue(), ftp_fget(), and ftp_get().
(PHP 4 >= 4.3.0, PHP 5)
ftp_nb_fput -- Salva il contenuto di un file aperto sul server FTP in modalita' non bloccanteLa funzione ftp_nb_fput() carica i dati dalla posizione puntata dal puntatore handle fino a quando non raggiunge la fine del file. Il risultato e' salvato in remote_file sul server FTP. La modalita' di trasferimento, mode specificata deve essere FTP_ASCII oppure FTP_BINARY. La differenza tra questa funzione e la funzione ftp_fput() e' che questa funzione trasferisce il file in modo asincrono, cosicche' il programma puo' eseguire altre operazioni mentre il file viene caricato.
Esempio 1. Esempio di funzione ftp_nb_fput()
|
Restituisce FTP_FAILED, FTP_FINISHED, oppure FTP_MOREDATA.
Vedere anche ftp_nb_put(), ftp_nb_continue(), ftp_put() e ftp_fput().
(PHP 4 >= 4.3.0, PHP 5)
ftp_nb_get -- Recupera un file dal server FTP e lo scrive su un file locale in modalita' non bloccanteLa funzione ftp_nb_get() recupera remote_file dal server FTP, e lo salva localmente su local_file. La modalita' di trasferimento, mode, specificata deve essere FTP_ASCII oppure FTP_BINARY. La differenza tra questa funzione e la funzione ftp_get() e' che questa funzione recupera il file in modo asincrono, cosicche' il programma puo' eseguire altre operazioni mentre il file viene scaricato.
Restituisce FTP_FAILED, FTP_FINISHED, oppure FTP_MOREDATA.
Esempio 1. Esempio di funzione ftp_nb_get()
|
Esempio 2. Ripresa di uno scaricamento con ftp_nb_get()
|
Esempio 3. Ripresa di uno scaricamento dalla posizione 100 su un nuovo file con ftp_nb_get()
|
Nell'esempio precedente, "newfile" e' 100 bytes piu' piccolo di "README" sul server FTP perche' la lettura e' iniziata dall'offset 100. Se FTP_AUTOSEEKnon fosse stata disabilitata, i primi 100 bytes di "newfile" sarebbero stati '\0'.
Vedere anche ftp_nb_fget(), ftp_nb_continue(), ftp_get(), e ftp_fget().
La funzione ftp_nb_put() salva local_file sul server FTP come remote_file. La modalita' di trasferimento, mode specificata deve essere FTP_ASCII oppure FTP_BINARY. La differenza tra questa funzione e la funzione ftp_put() e' che questa funzione trasferisce il file in modo asincrono, cosicche' il programma puo' eseguire altre operazioni durante il trasferimento.
Restituisce FTP_FAILED, FTP_FINISHED, oppure FTP_MOREDATA.
Esempio 1. Esempio di funzione ftp_nb_put()
|
Esempio 2. Ripresa di un trasferimento con ftp_nb_put()
|
Vedere anche ftp_nb_fput(), ftp_nb_continue(), ftp_put(), e ftp_fput().
Restituisce un array di nomi di file dalla directory specificata in caso di corretta esecuzione oppure FALSE in caso di errore.
Esempio 1. Esempio di funzione ftp_nlist()
L'esempio precedente visualizza qualcosa del tipo:
|
Vedere anche ftp_rawlist().
ftp_pasv() attiva il modo passivo se il parametro pasv e' TRUE. Disattiva il modo passivo se pasv e' FALSE. Nel modo passivo, le connessioni sono iniziate dal client piuttosto che dal server.
Esempio 1. Esempio di funzione ftp_pasv()
|
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
ftp_put() salva local_file sul server FTP come remote_file. Il modo di trasferimento mode specificato deve essere FTP_ASCII oppure FTP_BINARY.
Nota: Il parametro startpos e' stato aggiunto nella release PHP 4.3.0.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Esempio 1. Esempio di funzione ftp_put()
|
Vedere anche ftp_fput(), ftp_nb_fput(), e ftp_nb_put().
Restituisce la directory corrente oppure FALSE in caso di errore.
Esempio 1. Esempio di funzione ftp_pwd()
|
Invia un command di qualsiasi tipo al server FTP. Restituisce la risposta del server sotto forma di un array di stringhe. ftp_raw() non esegue il parsing della stringa di risposta, ne' controlla se il comando e' stato eseguito correttamente.
Vedi anche: ftp_exec()
(PHP 3 >= 3.0.13, PHP 4, PHP 5)
ftp_rawlist -- Restituisce un elenco dettagliato dei files nella directory in esameftp_rawlist() esegue il comando FTP LIST, e restituisce il risultato sotto forma di array. Ogni elemento dell'array corrisponde ad una linea di testo. Sull'output non viene eseguito parsing. L'identificatore di tipo di sistema restituito da ftp_systype() puo' essere utilizzato per interpretare il risultato.
Esempio 1. Esempio di funzione ftp_rawlist()
L'esempio precedente produrra' qualcosa di simile a:
|
Vedere anche ftp_nlist().
ftp_rename() rinomina il file o la directory il cui nome corrente e' from con il nome to, utilizzando lo stream FTP ftp_stream.
Esempio 1. Esempio di funzione ftp_rename()
|
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Elimina la directory specificata. directory deve essere un percorso assoluto o relativo ad una directory vuota.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Esempio 1. Esempio di funzione ftp_rmdir()
|
Vedere anche ftp_mkdir().
Restituisce TRUE se e'stato possibile impostare l'opzione; FALSE altrimenti. Se l'opzione option non e' supportata o il valore value del parametro passato alla funzione non corrisponde al valore atteso per l'opzione option scelta, viene generato un messaggio di errore.
Questa funzione controlla varie opzioni che hanno effetto durante l'esecuzione dello stream FTP specificato. Il parametro value dipende da quale parametro option viene scelto per essere modificato. Attualmente sono riconosciute le seguenti opzioni:
Tabella 1. Opzioni supportate per l'esecuzione di FTP
FTP_TIMEOUT_SEC | Modifica il timeout in secondi utilizzata per tutte le funzioni di rete. Il parametro value deve essere un intero maggiore di 0. Il timeout predefinito e' di 90 secondi. |
FTP_AUTOSEEK | Quando attivata, richieste GET or PUT con un parametro resumepos o startpos iniziano la ricerca dalla posizione richiesta all'interno del file. This is enabled Questa opzione e' attivata di default. |
Vedere anche ftp_get_option().
La funzione ftp_site() invia al server FTP il comando specificato dal parametro cmd. I comandi SITE non sono standardizzati e sono diversi da server a server. They are Sono utili per operare, ad esempio, sui permessi dei file o sull'appartenenza a gruppi.
Esempio 1. Invio di un comando SITE ad un server ftp
|
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere anche: ftp_raw()
La funzione ftp_size() restituisce le dimensioni del file remote_file in bytes. Se si verifica un errore, se il file specificato non esiste, o se e' una directory, viene restituito -1. Non tutti i server supportano questa caratteristica.
Restituisce le dimensioni del file in caso di successo, o -1 in caso di errore.
Esempio 1. Esempio di funzione ftp_size()
|
Vedere anche ftp_rawlist().
Restituisce uno stream SSL-FTP in caso di successo o FALSE in caso di errore.
La funzione ftp_ssl_connect() apre una connessione SSL-FTP verso il server host. Il parametro port specifica una porta alternativa a cui connettersi. Se omesso o impostato a zero allora viene usata la porta 21 standard.
Il parametro timeout specifica il timeout per tutte le operazioni di rete successive. Se omesso il valore predefinito e' di 90 secondi. Il timeout puo' essere interrogato o modificato in qualsiasi momento con le funzioni ftp_set_option() e ftp_get_option().
Esempio 1. Esempio di funzione ftp_ssl_connect()
|
Perche' questa funzione puo' non essere presente: La funzione ftp_ssl_connect() e' disponibile solo se il supporto OpenSSL e' abilitato nella versione corrente di PHP. Se non e' definito ed e' stato incluso il supporto a FTP durante la compilazione, questa e' la ragione per cui la funzione non e' presente.
Vedere anche ftp_connect().
(PHP 3 >= 3.0.13, PHP 4, PHP 5)
ftp_systype -- Restituisce l'identificatore di tipo del server FTP remotoRestituisce il tipo del sistema remoto, o FALSE in caso di errore.
Esempio 1. Esempio di funzioneftp_systype()
L'esempio precedente produrra' in uscita qualosa di simile a:
|
These functions all handle various operations involved in working with functions.
Non è necessaria nessuna installazione per usare queste funzioni, esse fanno parte del core di PHP.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
(PHP 4 >= 4.0.4, PHP 5)
call_user_func_array -- Call a user function given with an array of parametersCall a user defined function given by function, with the parameters in param_arr. For example:
Esempio 1. call_user_func_array() example
|
See also call_user_func(), and information about the callback type
Call a user defined function given by the function parameter. Take the following:
<?php function barber($type) { echo "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() { echo "Hello!\n"; } } $classname = "myclass"; call_user_func(array($classname, 'say_hello')); ?> |
Nota: Note that the parameters for call_user_func() are not passed by reference.
See also: is_callable(), call_user_func_array(), e information about the callback type.
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:
Esempio 1. Creating an anonymous function with create_function()
|
Or, perhaps to have general handler function that can apply a set of operations to a list of parameters:
Esempio 2. Making a general processing function with create_function()
and when you run the code above, the output will be:
|
But perhaps the most common use for of lambda-style (anonymous) functions is to create callback functions, for example when using array_walk() or usort()
Esempio 3. Using anonymous functions as callback functions
outputs:
an array of strings ordered from shorter to longer
outputs:
sort it from longer to shorter
outputs:
|
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. This function cannot be used directly as a function parameter. Instead, its result may be assigned to a variable, which can then be passed to the function.
If arg_num is greater than the number of arguments actually passed, a warning will be generated and func_get_arg() will return FALSE.
Nota: Because this function depends on the current scope to determine parameter details, it cannot be used as a function parameter. If you must pass this value, assign the results to a variable, and pass the variable.
<?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.
Returns an array in which each element is a copy of 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. This function cannot be used directly as a function parameter. Instead, its result may be assigned to a variable, which can then be passed to the function.
Nota: This function returns a copy of the passed arguments only, and does not account for default (non-passed) arguments.
Nota: Because this function depends on the current scope to determine parameter details, it cannot be used as a function parameter. If you must pass this value, assign the results to a variable, and pass the variable.
<?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.
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. This function cannot be used directly as a function parameter. Instead, its result may be assigned to a variable, which can then be passed to the function.
Nota: Because this function depends on the current scope to determine parameter details, it cannot be used as a function parameter. If you must pass this value, assign the results to a variable, and pass the variable.
<?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. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
<?php if (function_exists('imap_open')) { echo "IMAP functions are available.<br />\n"; } else { echo "IMAP functions are not available.<br />\n"; } ?> |
Note that a function name may exist even if the function itself is unusable due to configuration or compiling options (with the image functions being an example). Also note that function_exists() will return FALSE for constructs, such as include_once() and echo().
See also method_exists(), is_callable() 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).
<?php 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 function_exists(), get_defined_vars() and get_defined_constants().
(PHP 3 >= 3.0.4, PHP 4, PHP 5)
register_shutdown_function -- Register a function for execution on shutdownRegisters 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.
In PHP 4.0.6 and earlier under Apache, 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(). Since PHP 4.1, the shutdown functions are called as the part of the request so that it's possible to send the output from them. There is currently no way to process the data with output buffering functions in the shutdown function. Shutdown function is called after closing all opened output buffers thus, for example, its output will not be compressed if zlib.output_compression is enabled.
As of PHP 4, it is possible to pass parameters to the shutdown function by passing additional parameters to register_shutdown_function().
Nota: Typically undefined functions cause fatal errors in PHP, but when the function called with register_shutdown_function() is undefined, an error of level E_WARNING is generated instead. Also, for reasons internal to PHP, this error will refer to Unknown at line #0.
Nota: Working directory of the script can change inside the shutdown function under some web servers, e.g. Apache.
Nota: Shutdown function is called during the script shutdown so headers are always already sent.
See also auto_append_file, exit(), and the section on connection handling.
Registers the function named by func to be executed when a tick is called. Also, you may pass an array consisting of an object and a method as the func.
Avvertimento |
register_tick_function() should not be used with threaded webserver modules. Ticks are not working in ZTS mode and may crash your webserver. |
See also declare and unregister_tick_function().
(PHP 4 >= 4.0.3, PHP 5)
unregister_tick_function -- De-register a function for execution on each tickDe-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/software/gettext/manual/gettext.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.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
(PHP 4 >= 4.2.0, PHP 5)
bind_textdomain_codeset -- Specify the character encoding in which the messages from the DOMAIN message catalog will be returnedWith bind_textdomain_codeset(), you can set in which encoding will be messages from domain returned by gettext() and similar functions.
The bindtextdomain() function sets the path for a domain. It returns the full pathname for the domain currently being set.
This function allows you to override the current domain for a single message lookup. It also allows you to specify a category.
See also gettext().
This function allows you to override the current domain for a single plural message lookup. It also allows you to specify a category.
See also ngettext().
The dgettext() function allows you to override the current domain for a single message lookup.
See also gettext().
The dngettext() function allows you to override the current domain for a single plural message lookup.
See also ngettext().
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.
Esempio 1. gettext()-check
|
See also setlocale().
ngettext() returns correct plural form of message identified by msgid1 and msgid2 for count n. Some languages have more than one form for plural messages dependent on the count.
This function sets the domain to search within when calls are made to gettext(), usually the named after an application.
Queste funzioni permettono di lavorare con numeri interi di lunghezza arbitraria usando le librerie GNU MP.
Queste funzioni sono state aggiunte in PHP 4.0.4.
Nota: Molte funzioni accettano argomenti numerici GMP, definiti come risorsepiù in basso. Comunque, molte di queste funzioni accetteranno anche normali argomenti numerici e stringhe, considerato ciò è quindi possibile convertire queste ultime in numero. Inoltre, se c'è una funzione che può operare velocemente su argomenti interi, questa potrebbe essere usata al posto della più lenta quando l'argomento fornito è un intero. Questo è fatto con chiarezza, così la logica vuole che tu possa utilizzare numeri interi in ogni funzione che richieda un numero GMP. Vedere anche la funzione gmp_init().
Avvertimento |
Se desideri specificare un "large integer" come costante, scrivilo tra virgolette come stringa. Se non lo fai, PHP interpreterà l'"integer literal" immediatamente, con una possibile perdita di precisione, ancora prima che la libreria GMP venga richiamata. |
Nota: Questo modulo non è disponibile su piattaforme Windows.
Puoi scaricare la libreria GMP dal sito http://www.swox.com/gmp/. Dove è possibile anche scaricare il manuale GMP.
Per usare queste funzioni è necessaria la versione 2 o superiore delle librerie GMP.
Per potere utilizzare queste funzioni, occorre compilare il PHP con il supporto GMP utilizzando il parametro --with-gmp.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Ulteriori funzioni matematiche sono elencate nelle sezioni BCMath Funzione Matematiche a Precisione Arbitraria e Funzioni Matematiche.
Somma due numeri GMP. Il risultato, sarà un numero GMP che rappresenta la somma degli argomenti.
Ripulisce (imposta a 0) il bit index in a.
Restituisce un valore positivo se a > b, zero se a = b e negativo se a < b.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Divide a per b e restituisce un numero intero. L'arrotondamento del risultato, è definito dal round, che può avere i seguenti valori:
GMP_ROUND_ZERO: Il risultato è troncato verso 0.
GMP_ROUND_PLUSINF: Il risultato è arrotondato verso +infinito.
GMP_ROUND_MINUSINF: Il risultato è arrotondato verso -infinito.
Questa funzione può anche essere richiamata come gmp_div().
Vedere anche gmp_div_r(), gmp_div_qr()
Questa funzione, esegue la divisione tra n e d , restituendo un array, il primo elemento è, [n/d] (il risultato intero della divisione) il secondo è (n - [n/d] * d) (cioè il resto della divisone).
Vedere la funzione gmp_div_q() per la descrizione dell'argomento round.
Vedere anche gmp_div_q(), gmp_div_r().
Calcola il resto di una divisione intera fra n e d. Se non è zero, il resto ha il segno dell'argomento n.
Vedi la funzione gmp_div_q() per la descrizione dell'argomento round.
Vedere anche gmp_div_q(), gmp_div_qr()
Divide n per d, usando un algoritmo di "esatta divisione". Questa funzione, restituisce un valore corretto solo quando è noto a priori che d divide n.
Calcola il massimo comune divisore (MCD) di a e b. Il risultato è sempre positivo, anche se uno o entrambi gli operatori sono negativi.
Calcola g, s e t, in questo modo a*s + b*t = g = gcd(a,b), dove MCD è il massimo comune divisore. Restituisce un array con i rispettivi argomenti, cioè, g, s e t.
Restituisce la distanza di hamming tra a e b. Entrambe gli operandi dovrebbero essere non-negativi.
Crea un numero GMP partendo da un intero o da una stringa. La stringa può essere decimale o esadecimale. Nell'ultimo caso, la stringa dovrebbe iniziare con 0x.
Nota: Non è necessario chiamare uesta funzione se si vogliono usare interi o stringhe al posto di numeri GMP nelle funzioni GMP, come gmp_add(). Se se questa conversione è possibile e necessaria, gli argomenti delle funzioni vengono automaticamente convertiti in numeri GMP, usando le stesse regole di gmp_init().
Questa funzione converte un numero GMP in un intero.
Avvertimento |
Questa funzione restituisce un risultato utile, solo se il numero attualmente fornito al PHP è un intero (per esempio, un tipo signed long). Se desideri solo stampare il numero GMP, usa gmp_strval(). |
Calcola l'inverso di a modulo b. Restituisce un valore FALSE se l'inversione non esiste.
Calcola il simbolo di Jacobi di a e p. p p potrebbe essere dispari e deve essere positivo.
Calcolo del Legendre symbol di a e p. p potrebbe essere dispari e deve essere positivo.
Calcola il modulo di n rispetto a d. Il risultato è sempre non-negativo, il segno di d viene ignorato.
Moltiplica a per b e restituisce il risultato.
Restituisce un valore vero TRUE se a è un quadrato perfetto,falso FALSE se non lo è.
Vedere anche: gmp_sqrt(), gmp_sqrtrm().
Eleva la base base ad una potenza exp. Nel caso di 0^0 il risultato sarà 1. L'argomento exp non può essere negativo.
Calcola il (base elevato a potenza exp) modulo mod. Se exp è negativo, il risultato sarà indefinito.
Se questa funzione da come risultato 0, a non è primo. Se sarà 1, allora a è "probabilmente" primo. Invece se il risultato è 2, allora a sarà sicuramente primo. I valori "attendibili" di reps possono variare da 5 a 10 (di default 10); un valore più alto fa diminuire la probabilità che un numero non primo passi come "probabile" primo.
La funzione usa il test probabilistico di Miller-Rabin.
Genera un numero casuale. Il numero, sarà lungo un numero di WORD (2 byte) non superiore all'argomento limiter. Se l'argomento limiter è negativo, il numero generato sarà anch'esso negativo.
Cerca in a, partendo dal bit startverso i bit più significativi, fermandosi sul primo bit nullo, di cui restituisce l'indice.
Cerca in a, partendo dal bit start, verso i bit più significativi, fermandosi sul primo bit nullo, di cui restituisce l'indice.
Sets bit index in a. set_clear definisce se il bit è settato su 0 o su 1. Di default il bit è settato a 1.
Restituisce il segno di a : 1 se a è positivo e -1 se è negativo.
Restituisce un array con due valori, il primo è la radice quadrata (fornita come intero) di a (vedere anche gmp_sqrt()), e il secondo è il resto (cioè, la differenza tra a e il primo elemento al quadrato).
Converte un numero GMP in una stringa rappresentato in base base. La base di default è 10. Le basi consentite variano dal 2 al 36.
The gopher protocol, as defined by RFC 1436, is generally considered the ancestor of the modern HTTP protocol. However, gopher was also intended to provide references to non-gopher resources including telnet, wais, nntp, and even http. This extension adds gopher support to PHP's URL Wrappers, and provides a helper function gopher_parsedir() to make sense of gopher formatted directory listings.
Net_Gopher is installed through the usual PECL package installation process.
Prerequisite: PHP 4.3.0.
$ pear install Net_Gopher |
Copy the resulting gopher.so to an appropriate location and add extension=gopher.so to your php.ini file or load it dynamically in your PHP script using dl("gopher.so");
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
While gopher returns text/plain documents for actual document requests. A request to a directory (such as /) will return specially encoded series of lines with each line being one directory entry or information line.
Esempio 1. Hypothetical output from gopher://gopher.example.com/
|
In the example above, the root directory at gopher.example.com knows about one DOCUMENT identified by 0 located at gopher://gopher.example.com:70/allabout.txt. It also knows about two other directory (which have their own listing files) at gopher://gopher.exmaple.com:70/stories and at gopher://gopher.ejemplo.co.es:70/. In addition there is a binary file, a link to an HTTP url, and several informative lines.
By passing each line of the directory listing into gopher_parsedir(), an associative array is formed containing a parsed out version of the data.
Esempio 2. Using gopher_parsedir()
|
The values given by type are associated with the following constants.
Tabella 1. Gopher Constants
Constant | Definition |
---|---|
GOPHER_DOCUMENT | Standard text/plain document. |
GOPHER_DIRECTORY | A resource containing a gopher formatted directory listing. |
GOPHER_BINHEX | A BinHex encoded binary file. |
GOPHER_DOSBINARY | A DOS formatted binary archive. |
GOPHER_UUENCODED | A UUEncoded file. |
GOPHER_BINARY | A generic binary file. |
GOPHER_INFO | An Informational entry |
GOPHER_HTTP | A reference to an HTTP resource. |
GOPHER_UNKNOWN | An unrecognized entry, the line will be returned in data. |
Queste funzioni permettono di modificare l'output inviato verso un browser attraverso manipolazioni a livello di protocollo HTTP.
Non è necessaria nessuna installazione per usare queste funzioni, esse fanno parte del core di PHP.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
header() si utilizza per inviare header HTTP. Per maggiorni informazioni riguardanti gli header HTTP si veda la risorsa HTTP 1.1 specification.
L'argomento opzionale replace indica se l'header inviato deve sostituirne uno simile spedito precedentemente, o accodarsi al primo dello stesso tipo. Per default la funzione sostituisce l'header precedente, ma se viene passato FALSE come secondo argomento vengono forzate intestazioni multiple. Per esempio:
Ci sono due casi speciali di chiamate di header. Il primo è "Location". Location non trasmette solo un header al browser, ma anche un REDIRECT con codice di stato (302).
header("Location: http://www.php.net/"); /* Ridireziona il browser al sito di PHP */ exit; /* Assicura che il codice sottostante non sia eseguito dopo il redirezionamento. */ |
Nota: HTTP/1.1 richiede un URI assoluto come argomento di Location: composto da schema, hostname, e path assoluto, ma alcuni clients possono accettare anche URIs relativi. E' possibile usare $HTTP_SERVER_VARS['HTTP_HOST'], $HTTP_SERVER_VARS['PHP_SELF'] e dirname() per creare URI assoluti da URI relativi in modo automatico:
Il secondo caso speciale è esemplificato dalle intestazioni che iniziano con la stringa, "HTTP/" (le maiuscole non sono discriminanti), che è usato per inviare codici di stato HTTP. Per esempio, se si è configurato Apache per usare script PHP per la manipolazione di richieste fallite (usando la direttiva ErrorDocument), potete desiderare di assicurarvi che il vostro script generi il codice adeguato.
Nota: In PHP 3, questo funziona solo se PHP è compilato come modulo Apache. Potete ottenere lo stesso effetto usando l'header Status.
Spesso gli scrit PHP generano contenuti dinamici, se volete evitare che i contenuti vengano mantenuti nella cache di browser o proxy, potete forzare il loro comportamento con questa direttiva:
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Data passata header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // sempre modificato 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: E' possibile che alcune pagine rimangano in chache anche dopo l'uso degli header descritti sopra. Ci sono delle opzioni che l'utente può settare dal browser, capaci di modificare i comportamenti di default del caching. Per trasmettere efficacemente gli header descritti, bisogna che sia inattiva ogni regolazione che può forzare comportamenti contrari.
Inoltre, session_cache_limiter() e e la configurazione session.cache_limiter possono essere usate per generare automaticamente i corretti header relativi al caching durante l'uso delle sessioni.
Bisogna ricordare che la funzioneheader() va chiamata prima di qualsiasi output HTML o PHP (anche righe o spazi vuoti). E' un errore comune leggere files con funzioni include(), o require() (o altre funzioni capaci di accedere a files), che possano emettere in output spazi o linee vuote prima di una chiamata della funzione header(). Lo stesso problema esiste nell'utilizzare file PHP/HTML.
<?php require("user_logging.inc") ?> <?php header ("Content-type: audio/x-pn-realaudio"); ?> // Non funziona, notate le linee vuote sopra |
Nota: In PHP 4, potete usare il buffering dell'output per aggirare questo problema, evitando ogni output al browser trattenedolo al server fino a che non gli si impone l'invio. Si può fare questa operazione chiamando ob_start() e ob_end_flush() nello script, o settando la direttiva di configurazione output_buffering nel file php.ini o nel file di configurazione del server.
Se desiderate che l'utente sia spinto a salvare i dati trasmessi per esempio utilizzando un file PDF, potete usare l'header Content-Disposition, che vi permette di dare un nome al file e forzare il browser a mostrare la finestra di dialogo save.
<?php header("Content-type: application/pdf"); header("Content-Disposition: attachment; filename=downloaded.pdf"); /* ... manda in output un file pdf ... */ |
Nota: Per un bug di Microsoft Internet Explorer 4.01 qusto sistema non funziona. Non ci sono soluzioni. C'è un altro bug in Microsoft Internet Explorer 5.5 che impedisce il giusto funzionamento, ma è possibile risolverlo con l'upgrade del Service Pack 2 o superiore.
Vedi anche headers_sent(), setcookie(), e la sezione Autenticazione HTTP usando PHP.
headers_list() will return a numerically indexed array of headers to be sent to the browser / client. To determine whether or not these headers have been sent yet, use headers_sent().
Esempio 1. Examples using headers_list()
this will output :
|
See Also: headers_sent(), header(), and setcookie().
Questa funzione restituisce TRUE se gli header HTTP sono stati spedite correttamente, FALSE in caso contrario.
Vedi anche header()
setcookie() definisce un cookie da inviare insieme alle altre informazioni di header. I cookie devono essere spediti prima di qualsiasi altra intestazione (questa è una restrizione dei cookies, non di PHP). E' necessario perciò chiamare la funzione setcookie() prima di qualsiasi tags, anche <html> o <head>.
Tutti gli argomenti della funzione eccetto name sono opzionali. Se viene passato alla funzione solo l'argomento name, il cookie registrato con quel nome verrà cancellato dal client su cui è archiviato. E' possibile sostituire gli argomenti che non si intende specificare utitlizzando una stringa vuota (""). Gli argomenti expire e secure che richiedono numeri interi, non possono essere omessi inserendo una stringa vuota, per questo scopo si usa (0). L'argomento expire è un normale intero Unix Timestamp ottenibile grazie alle funzioni time() o mktime(). secure sta ad indicare che il cookie dovrebbe essere trasmesso soltanto attraverso un collegamento sicuro di tipo HTTPS.
Errori comuni:
I cookie diventano disponibili soltanto dalla pagina successiva a quella che li ha generati, o dopo il ricaricamento di questa.
I cookie devono essere cancellati specificando gli stessi parametri con cui sono stati creati.
In PHP 3, chiamate successive di setcookie() nello stesso script sono eseguite in ordine inverso. Se state provando a cancellare un cookie prima dell' inserimento di un altro cookie, dovete creare il secondo prima della cancellazione del primo. In PHP 4, chiamate successive di setcookie() invece, sono eseguite secondo l'ordine di chiamata.
Alcuni esempi sul modo di spedire cookie:
Gli esempi mostrano come cancellare i cookie introdotti nell'esempio precedente:
Si noti che i valori salvati nei cookies sono automaticamente codificati per la trasmissione via URL (urlencoded) quando il cookie viene inviato, e che al momento del richiamo sono automaticamente decodificati e assegnati ad una variabile che ha lo stesso nome del cookie. Per vedere il contenuto di un cookie in uno script, si usa una di queste due sintassi:
Potete registrare array in un cookie usando la notazione degli array al posto del nome del cookie. Questo equivale alla spedizione di tanti cookie quanti sono gli elementi dell'array, ma si ha un vantaggio: quando il cookie è ricevuto, tutti i suoi valori sono ordinati in un singolo array che ha per nome il nome del cookie:
setcookie ("cookie[three]", "cookiethree"); setcookie ("cookie[two]", "cookietwo"); setcookie ("cookie[one]", "cookieone"); if (isset ($cookie)) { while (list ($name, $value) = each ($cookie)) { echo "$name == $value<br>\n"; } } |
Per saperne di più sui cookies, Netscape's cookie specification è la risorsa giusta http://wp.netscape.com/newsref/std/cookie_spec.html.
Microsoft Internet Explorer 4 con Service Pack 1 non crea correttamente cookie che hanno il parametro path specificato.
Netscape Communicator 4.05 e Microsoft Internet Explorer 3.x sembrano utilizzare in modo errato i cookie quando path ed expire non sono specificati.
setrawcookie() is exactly the same as setcookie() except that the cookie value will not be automatically urlencoded when sent to the browser.
See also header(), setcookie() and the cookies section.
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: A 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.
This PECL extension is not bundled with PHP.
In order to use these functions you must compile PHP with Hyperwave support by using the --with-hyperwave[=DIR] configure option.
Windows users will enable php_hyperwave.dll inside of php.ini in order to use these functions. You may download this PECL extension DLL from the PHP Downloads page or at http://snaps.php.net/.
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.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. Hyperwave configuration options
Name | Default | Changeable | Changelog |
---|---|---|---|
hyperwave.allow_persistent | "0" | PHP_INI_SYSTEM | Available since PHP 4.3.2. |
hyperwave.default_port | "418" | PHP_INI_ALL |
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
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.
(PHP 3 >= 3.0.4, PHP 4, PECL)
hw_Array2Objrec -- Convert attributes from object array to object recordConverts an object_array into an object record. Multiple attributes like 'Title' in different languages are treated properly.
See also hw_objrec2array().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
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, PECL)
hw_connection_info -- Prints information about the connection to Hyperwave server
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
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.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
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(), and 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().
(PHP 3 >= 3.0.3, PHP 4, PECL)
hw_GetChildDocCollObj -- Object records of child documents of collectionReturns 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.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
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 through 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 formatted 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 exactly 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 hierarchy 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 separator between hierarchy 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 hierarchy 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 think 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().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
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 corresponding 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 recursive modification. If some of the objects cannot be modified they will be skipped 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 necessary if you want 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 surround this function by calls to hw_getandlock() and hw_unlock(). hw_modifyobject() does this internally.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
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 returned 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().
(PHP 3 >= 3.0.3, PHP 4, PECL)
hw_objrec2array -- Convert attributes from object record to object arrayConverts 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 transferred 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.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
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 initiated 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.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. Hyperwave API configuration options
Name | Default | Changeable | Changelog |
---|---|---|---|
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 several parameters they are all put into an associated array and passed as one parameter. 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().
Nota: Methods returning boolean can return TRUE, FALSE or HW_API_Error object.
Returns the name of the attribute.
See also hwapi_attribute_value().
(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 hierarchy 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 committed on check-in.
See also hwapi_checkout().
This function checks out an object or a whole hierarchy 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 server
See also hwapi_dcstat(), hwapi_hwstat(), hwapi_ftstat().
(no version information, might be only in CVS)
hw_api->dcstat -- Returns statistics about document cache server
See 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->dstofsrcanchor -- 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().
Returns the number of error reasons.
See also hwapi_error_reason().
Returns the first error reason.
See also hwapi_error_count().
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', 'languages' 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 server
See 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 server
See also hwapi_dcstat(), hwapi_dbstat(), hwapi_ftstat().
Logs into the Hyperwave Server. The parameter array must contain the elements 'username' and '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 configuration
See 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 further 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 system 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 the collection and 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 occurred.
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 occurred.
This simple example retrieves an object and checks for errors.
Esempio 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 reasonRemoves 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 skipped. 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 immediately. 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->setcommittedversion -- Commits version other than last versionCommits a version of a document. The committed version is the one which is visible to users with read access. By default the last version is the committed 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().
These functions enable you to access IBM DB2 Universal Database, IBM Cloudscape, and Apache Derby databases using the DB2 Call Level Interface (DB2 CLI).
To connect to IBM DB2 Universal Database for Linux, UNIX, and Windows, or IBM Cloudscape, or Apache Derby, you must install an IBM DB2 Universal Database client on the same computer on which you are running PHP. The extension has been developed and tested with DB2 Version 8.2.
To connect to IBM DB2 Universal Database for z/OS or iSeries, you also require IBM DB2 Connect or the equivalent DRDA gateway software.
The user invoking the PHP executable or SAPI must specify the DB2 instance before accessing these functions. You can set the name of the DB2 instance in php.ini using the ibm_db2.instance_name configuration option, or you can source the DB2 instance profile before invoking the PHP executable.
If you created a DB2 instance named db2inst1 in /home/db2inst1/, for example, you can add the following line to php.ini:
ibm_db2.instance_name=db2inst1 |
bash$ source /home/db2inst1/sqllib/db2profile |
To build the ibm_db2 extension, the DB2 application development header files and libraries must be installed on your system. DB2 does not install these by default, so you may have to return to your DB2 installer and add this option. The header files are included with the DB2 Application Development Client freely available for download from the IBM DB2 Universal Database support site.
If you add the DB2 application development header files and libraries to a Linux or Unix operating system on which DB2 was already installed, you must issue the command db2iupdt -e to update the symbolic links to the header files and libraries in your DB2 instances.
ibm_db2 is a PECL extension, so follow the instructions in Capitolo 7 to install the ibm_db2 extension for PHP. Issue the configure command to point to the location of your DB2 header files and libraries as follows:
bash$ ./configure --with-IBM_DB2=/path/to/DB2 |
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. ibm_db2 Opioni di configurazione
Nome | Default | Modificabile | Changelog |
---|---|---|---|
ibm_db2.binmode | "1" | PHP_INI_ALL | |
ibm_db2.instance_name | NULL | PHP_INI_SYSTEM |
Breve descrizione dei parametri di configurazione.
This option controls the mode used for converting to and from binary data in the PHP application.
1 (DB2_BINARY)
2 (DB2_CONVERT)
3 (DB2_PASSTHRU)
On Linux and UNIX operating systems, this option defines the name of the instance to use for cataloged database connections. If this option is set, its value overrides the DB2INSTANCE environment variable setting.
This option is ignored on Windows operating systems.
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Specifies that binary data shall be returned as is. This is the default mode.
Specifies that binary data shall be converted to a hexadecimal encoding and returned as an ASCII string.
Specifies that binary data shall be converted to a NULL value.
Specifies a scrollable cursor for a statement resource. This mode enables random access to rows in a result set, but currently is supported only by IBM DB2 Universal Database.
Specifies a forward-only cursor for a statement resource. This is the default cursor type and is supported on all database servers.
Specifies the PHP variable should be bound as an IN parameter for a stored procedure.
Specifies the PHP variable should be bound as an OUT parameter for a stored procedure.
Specifies the PHP variable should be bound as an INOUT parameter for a stored procedure.
Specifies that the column should be bound directly to a file for input or output.
Specifies that autocommit should be turned on.
Specifies that autocommit should be turned off.
Specifies that the variable should be bound as a DOUBLE, FLOAT, or REAL data type.
Specifies that the variable should be bound as a SMALLINT, INTEGER, or BIGINT data type.
Specifies that the variable should be bound as a CHAR or VARCHAR data type.
The ibm_db2 extension returns connection resources, statement resources, and result set resources.
Sets or gets the AUTOCOMMIT behavior of the specified connection resource.
A valid database connection resource variable as returned from db2_connect() or db2_pconnect().
One of the following constants:
Turns AUTOCOMMIT off.
Turns AUTOCOMMIT on.
When db2_autocommit() receives only the connection parameter, it returns the current state of AUTOCOMMIT for the requested connection as an integer value. A value of 0 indicates that AUTOCOMMIT is off, while a value of 1 indicates that AUTOCOMMIT is on.
When db2_autocommit() receives both the connection parameter and autocommit parameter, it attempts to set the AUTOCOMMIT state of the requested connection to the corresponding state. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Esempio 1. Retrieving the AUTOCOMMIT value for a connection In the following example, a connection which has been created with AUTOCOMMIT turned off is tested with the db2_autocommit() function.
Il precedente esempio visualizzerà:
|
Esempio 2. Setting the AUTOCOMMIT value for a connection In the following example, a connection which was initially created with AUTOCOMMIT turned off has its behavior changed to turn AUTOCOMMIT on.
Il precedente esempio visualizzerà:
|
Binds a PHP variable to an SQL statement parameter in a statement resource returned by db2_prepare(). This function gives you more control over the parameter type, data type, precision, and scale for the parameter than simply passing the variable as part of the optional input array to db2_execute().
A prepared statement returned from db2_prepare().
Specifies the 1-indexed position of the parameter in the prepared statement.
A string specifying the name of the PHP variable to bind to the parameter specified by parameter-number.
A constant specifying whether the PHP variable should be bound to the SQL parameter as an input parameter (DB2_PARAM_IN), an output parameter (DB2_PARAM_OUT), or as a parameter that accepts input and returns output (DB2_PARAM_INOUT).
A constant specifying the SQL data type that the PHP variable should be bound as: one of DB2_BINARY, DB2_CHAR, DB2_DOUBLE, or DB2_LONG .
Specifies the precision with which the variable should be bound to the database.
Specifies the scale with which the variable should be bound to the database.
Esempio 1. Binding PHP variables to a prepared statement The SQL statement in the following example uses two input parameters in the WHERE clause. We call db2_bind_param() to bind two PHP variables to the corresponding SQL parameters. Notice that the PHP variables do not have to be declared or assigned before the call to db2_bind_param(); in the example, $lower_limit is assigned a value before the call to db2_bind_param(), but $upper_limit is assigned a value after the call to db2_bind_param(). The variables must be bound and, for parameters that accept input, must have any value assigned, before calling db2_execute().
Il precedente esempio visualizzerà:
|
Esempio 2. Calling stored procedures with IN and OUT parameters The stored procedure match_animal in the following example accepts three different parameters:
Il precedente esempio visualizzerà:
|
(no version information, might be only in CVS)
db2_client_info -- Returns an object with properties that describe the DB2 database clientThis function returns an object with read-only properties that return information about the DB2 database client. The following table lists the DB2 client properties:
Tabella 1. DB2 client properties
Property name | Return type | Description |
---|---|---|
APPL_CODEPAGE | int | The application code page. |
CONN_CODEPAGE | int | The code page for the current connection. |
DATA_SOURCE_NAME | string | The data source name (DSN) used to create the current connection to the database. |
DRIVER_NAME | string | The name of the library that implements the DB2 Call Level Interface (CLI) specification. |
DRIVER_ODBC_VER | string | The version of ODBC that the DB2 client supports. This returns a string "MM.mm" where MM is the major version and mm is the minor version. The DB2 client always returns "03.51". |
DRIVER_VER | string | The version of the client, in the form of a string "MM.mm.uuuu" where MM is the major version, mm is the minor version, and uuuu is the update. For example, "08.02.0001" represents major version 8, minor version 2, update 1. |
ODBC_SQL_CONFORMANCE | string | The level of ODBC SQL grammar supported by the client:
|
ODBC_VER | string | The version of ODBC that the ODBC driver manager supports. This returns a string "MM.mm.rrrr" where MM is the major version, mm is the minor version, and rrrr is the release. The DB2 client always returns "03.01.0000". |
Esempio 1. A db2_client_info() example To retrieve information about the client, you must pass a valid database connection resource to db2_client_info().
Il precedente esempio visualizzerà:
|
This function closes a DB2 client connection created with db2_connect() and returns the corresponding resources to the database server.
If you attempt to close a persistent DB2 client connection created with db2_pconnect(), the close request is ignored and the persistent DB2 client connection remains available for the next caller.
Esempio 1. Closing a connection The following example demonstrates a successful attempt to close a connection to an IBM DB2, Cloudscape, or Apache Derby database.
Il precedente esempio visualizzerà:
|
(PECL)
db2_column_privileges -- Returns a result set listing the columns and associated privileges for a tableReturns a result set listing the columns and associated privileges for a table.
A valid connection to an IBM DB2, Cloudscape, or Apache Derby database.
A qualifier for DB2 databases running on OS/390 or z/OS servers. For other databases, pass NULL or an empty string.
The schema which contains the tables. To match all schemas, pass NULL or an empty string.
The name of the table or view. To match all tables in the database, pass NULL or an empty string.
The name of the column. To match all columns in the table, pass NULL or an empty string.
Returns a statement resource with a result set containing rows describing the column privileges for columns matching the specified parameters. The rows are composed of the following columns:
Column name | Description |
---|---|
TABLE_CAT | Name of the catalog. The value is NULL if this table does not have catalogs. |
TABLE_SCHEM | Name of the schema. |
TABLE_NAME | Name of the table or view. |
COLUMN_NAME | Name of the column. |
GRANTOR | Authorization ID of the user who granted the privilege. |
GRANTEE | Authorization ID of the user to whom the privilege was granted. |
PRIVILEGE | The privilege for the column. |
IS_GRANTABLE | Whether the GRANTEE is permitted to grant this privilege to other users. |
db2_columns() |
db2_foreign_keys() |
db2_primary_keys() |
db2_procedure_columns() |
db2_procedures() |
db2_special_columns() |
db2_statistics() |
db2_table_privileges() |
db2_tables() |
Returns a result set listing the columns and associated metadata for a table.
A valid connection to an IBM DB2, Cloudscape, or Apache Derby database.
A qualifier for DB2 databases running on OS/390 or z/OS servers. For other databases, pass NULL or an empty string.
The schema which contains the tables. To match all schemas, pass '%'.
The name of the table or view. To match all tables in the database, pass NULL or an empty string.
The name of the column. To match all columns in the table, pass NULL or an empty string.
Returns a statement resource with a result set containing rows describing the columns matching the specified parameters. The rows are composed of the following columns:
Column name | Description |
---|---|
TABLE_CAT | Name of the catalog. The value is NULL if this table does not have catalogs. |
TABLE_SCHEM | Name of the schema. |
TABLE_NAME | Name of the table or view. |
COLUMN_NAME | Name of the column. |
DATA_TYPE | The SQL data type for the column represented as an integer value. |
TYPE_NAME | A string representing the data type for the column. |
COLUMN_SIZE | An integer value representing the size of the column. |
BUFFER_LENGTH | Maximum number of bytes necessary to store data from this column. |
DECIMAL_DIGITS | The scale of the column, or NULL where scale is not applicable. |
NUM_PREC_RADIX | An integer value of either 10 (representing an exact numeric data type), 2 (representing an approximate numeric data type), or NULL (representing a data type for which radix is not applicable). |
NULLABLE | An integer value representing whether the column is nullable or not. |
REMARKS | Description of the column. |
COLUMN_DEF | Default value for the column. |
SQL_DATA_TYPE | An integer value representing the size of the column. |
SQL_DATETIME_SUB | Returns an integer value representing a datetime subtype code, or NULL for SQL data types to which this does not apply. |
CHAR_OCTET_LENGTH | Maximum length in octets for a character data type column, which matches COLUMN_SIZE for single-byte character set data, or NULL for non-character data types. |
ORDINAL_POSITION | The 1-indexed position of the column in the table. |
IS_NULLABLE | A string value where 'YES' means that the column is nullable and 'NO' means that the column is not nullable. |
db2_column_privileges() |
db2_foreign_keys() |
db2_primary_keys() |
db2_procedure_columns() |
db2_procedures() |
db2_special_columns() |
db2_statistics() |
db2_table_privileges() |
db2_tables() |
Commits an in-progress transaction on the specified connection resource and begins a new transaction. PHP applications normally default to AUTOCOMMIT mode, so db2_commit() is not necessary unless AUTOCOMMIT has been turned off for the connection resource.
Nota: If the specified connection resource is a persistent connection, all transactions in progress for all applications using that persistent connection will be committed. For this reason, persistent connections are not recommended for use in applications that require transactions.
A valid database connection resource variable as returned from db2_connect() or db2_pconnect().
(PECL)
db2_conn_error -- Returns a string containing the SQLSTATE returned by the last connection attemptdb2_conn_error() returns an SQLSTATE value representing the reason the last attempt to connect to a database failed. As db2_connect() returns FALSE in the event of a failed connection attempt, you do not pass any parameters to db2_conn_error() to retrieve the SQLSTATE value.
If, however, the connection was successful but becomes invalid over time, you can pass the connection parameter to retrieve the SQLSTATE value for a specific connection.
To learn what the SQLSTATE value means, you can issue the following command at a DB2 Command Line Processor prompt: db2 '? sqlstate-value'. You can also call db2_conn_errormsg() to retrieve an explicit error message and the associated SQLCODE value.
A connection resource associated with a connection that initially succeeded, but which over time became invalid.
Returns the SQLSTATE value resulting from a failed connection attempt. Returns an empty string if there is no error associated with the last connection attempt.
Esempio 1. Retrieving an SQLSTATE value for a failed connection attempt The following example demonstrates how to return an SQLSTATE value after deliberately passing invalid parameters to db2_connect().
Il precedente esempio visualizzerà:
|
db2_conn_errormsg() returns an error message and SQLCODE value representing the reason the last database connection attempt failed. As db2_connect() returns FALSE in the event of a failed connection attempt, do not pass any parameters to db2_conn_errormsg() to retrieve the associated error message and SQLCODE value.
If, however, the connection was successful but becomes invalid over time, you can pass the connection parameter to retrieve the associated error message and SQLCODE value for a specific connection.
A connection resource associated with a connection that initially succeeded, but which over time became invalid.
Returns a string containing the error message and SQLCODE value resulting from a failed connection attempt. If there is no error associated with the last connection attempt, db2_conn_errormsg() returns an empty string.
Esempio 1. Retrieving the error message returned by a failed connection attempt The following example demonstrates how to return an error message and SQLCODE value after deliberately passing invalid parameters to db2_connect().
Il precedente esempio visualizzerà:
|
Creates a new connection to an IBM DB2 Universal Database, IBM Cloudscape, or Apache Derby database.
For a cataloged connection to a database, database represents the database alias in the DB2 client catalog.
For an uncataloged connection to a database, database represents a complete connection string in the following format: DRIVER={IBM DB2 ODBC DRIVER};DATABASE=database;HOSTNAME=hostname;PORT=port;PROTOCOL=TCPIP;UID=username;PWD=password; where the parameters represent the following values:
The name of the database.
The hostname or IP address of the database server.
The TCP/IP port on which the database is listening for requests.
The username with which you are connecting to the database.
The password with which you are connecting to the database.
The username with which you are connecting to the database.
For uncataloged connections, you must pass a NULL value or empty string.
The password with which you are connecting to the database.
For uncataloged connections, you must pass a NULL value or empty string.
An associative array of connection options that affect the behavior of the connection, where valid array keys include:
Passing the DB2_AUTOCOMMIT_ON value turns autocommit on for this connection handle.
Passing the DB2_AUTOCOMMIT_OFF value turns autocommit off for this connection handle.
Returns a connection handle resource if the connection attempt is successful. If the connection attempt fails, db2_connect() returns FALSE.
Esempio 1. Creating a cataloged connection Cataloged connections require you to have previously cataloged the target database through the DB2 Command Line Processor (CLP) or DB2 Configuration Assistant.
Il precedente esempio visualizzerà:
|
Esempio 2. Creating an uncataloged connection An uncataloged connection enables you to dynamically connect to a database.
Il precedente esempio visualizzerà:
|
Esempio 3. Creating a connection with autocommit off by default Passing an array of options to db2_connect() enables you to modify the default behavior of the connection handle.
Il precedente esempio visualizzerà:
|
Returns the cursor type used by a statement resource. Use this to determine if you are working with a forward-only cursor or scrollable cursor.
Returns either DB2_FORWARD_ONLY if the statement resource uses a forward-only cursor or DB2_SCROLLABLE if the statement resource uses a scrollable cursor.
Prepares and executes an SQL statement.
If you plan to interpolate PHP variables into the SQL statement, understand that this is one of the more common security exposures. Consider calling db2_prepare() to prepare an SQL statement with parameter markers for input values. Then you can call db2_execute() to pass in the input values and avoid SQL injection attacks.
If you plan to repeatedly issue the same SQL statement with different parameters, consider calling db2_prepare() and db2_execute() to enable the database server to reuse its access plan and increase the efficiency of your database access.
A valid database connection resource variable as returned from db2_connect() or db2_pconnect().
An SQL statement. The statement cannot contain any parameter markers.
An associative array containing statement options. You can use this parameter to request a scrollable cursor on database servers that support this functionality.
Passing the DB2_FORWARD_ONLY value requests a forward-only cursor for this SQL statement. This is the default type of cursor, and it is supported by all database servers. It is also much faster than a scrollable cursor.
Passing the DB2_SCROLLABLE value requests a scrollable cursor for this SQL statement. This type of cursor enables you to fetch rows non-sequentially from the database server. However, it is only supported by DB2 servers, and is much slower than forward-only cursors.
Returns a statement resource if the SQL statement was issued successfully, or FALSE if the database failed to execute the SQL statement.
Esempio 1. Creating a table with db2_exec() The following example uses db2_exec() to issue a set of DDL statements in the process of creating a table.
Il precedente esempio visualizzerà:
|
Esempio 2. Executing a SELECT statement with a scrollable cursor The following example demonstrates how to request a scrollable cursor for an SQL statement issued by db2_exec().
Il precedente esempio visualizzerà:
|
db2_execute() executes an SQL statement that was prepared by db2_prepare().
If the SQL statement returns a result set, for example, a SELECT statement or a CALL to a stored procedure that returns one or more result sets, you can retrieve a row as an array from the stmt resource using db2_fetch_assoc(), db2_fetch_both(), or db2_fetch_array(). Alternatively, you can use db2_fetch_row() to move the result set pointer to the next row and fetch a column at a time from that row with db2_result().
Refer to db2_prepare() for a brief discussion of the advantages of using db2_prepare() and db2_execute() rather than db2_exec().
A prepared statement returned from db2_prepare().
An array of input parameters matching any parameter markers contained in the prepared statement.
Esempio 1. Preparing and executing an SQL statement with parameter markers The following example prepares an INSERT statement that accepts four parameter markers, then iterates over an array of arrays containing the input values to be passed to db2_execute().
Il precedente esempio visualizzerà:
|
Esempio 2. Calling a stored procedure with an OUT parameter The following example prepares a CALL statement that accepts one parameter marker representing an OUT parameter, binds the PHP variable $my_pets to the parameter using db2_bind_param(), then issues db2_execute() to execute the CALL statement. After the CALL to the stored procedure has been made, the value of $num_pets changes to reflect the value returned by the stored procedure for that OUT parameter.
Il precedente esempio visualizzerà:
|
db2_exec() |
db2_fetch_array() |
db2_fetch_assoc() |
db2_fetch_both() |
db2_fetch_row() |
db2_prepare() |
db2_result() |
(PECL)
db2_fetch_array -- Returns an array, indexed by column position, representing a row in a result setReturns an array, indexed by column position, representing a row in a result set. The columns are 0-indexed.
A valid stmt resource containing a result set.
Requests a specific 1-indexed row from the result set. Passing this parameter results in a PHP warning if the result set uses a forward-only cursor.
Returns a 0-indexed array with column values indexed by the column position representing the next or requested row in the result set. Returns FALSE if there are no rows left in the result set, or if the row requested by row_number does not exist in the result set.
Esempio 1. Iterating through a forward-only cursor If you call db2_fetch_array() without a specific row number, it automatically retrieves the next row in the result set.
Il precedente esempio visualizzerà:
|
Esempio 2. Retrieving specific rows with db2_fetch_assoc() from a scrollable cursor If your result set uses a scrollable cursor, you can call db2_fetch_assoc() with a specific row number. The following example retrieves every other row in the result set, starting with the second row.
Il precedente esempio visualizzerà:
|
(PECL)
db2_fetch_assoc -- Returns an array, indexed by column name, representing a row in a result setReturns an array, indexed by column name, representing a row in a result set.
A valid stmt resource containing a result set.
Requests a specific 1-indexed row from the result set. Passing this parameter results in a PHP warning if the result set uses a forward-only cursor.
Returns an associative array with column values indexed by the column name representing the next or requested row in the result set. Returns FALSE if there are no rows left in the result set, or if the row requested by row_number does not exist in the result set.
Esempio 1. Iterating through a forward-only cursor If you call db2_fetch_assoc() without a specific row number, it automatically retrieves the next row in the result set.
Il precedente esempio visualizzerà:
|
Esempio 2. Retrieving specific rows with db2_fetch_assoc() from a scrollable cursor If your result set uses a scrollable cursor, you can call db2_fetch_assoc() with a specific row number. The following example retrieves every other row in the result set, starting with the second row.
Il precedente esempio visualizzerà:
|
(PECL)
db2_fetch_both -- Returns an array, indexed by both column name and position, representing a row in a result setReturns an array, indexed by both column name and position, representing a row in a result set. Note that the row returned by db2_fetch_both() requires more memory than the single-indexed arrays returned by db2_fetch_assoc() or db2_fetch_array().
A valid stmt resource containing a result set.
Requests a specific 1-indexed row from the result set. Passing this parameter results in a PHP warning if the result set uses a forward-only cursor.
Returns an associative array with column values indexed by both the column name and 0-indexed column number. The array represents the next or requested row in the result set. Returns FALSE if there are no rows left in the result set, or if the row requested by row_number does not exist in the result set.
Esempio 1. Iterating through a forward-only cursor If you call db2_fetch_both() without a specific row number, it automatically retrieves the next row in the result set. The following example accesses columns in the returned array by both column name and by numeric index.
Il precedente esempio visualizzerà:
|
Esempio 2. Retrieving specific rows with db2_fetch_both() from a scrollable cursor If your result set uses a scrollable cursor, you can call db2_fetch_both() with a specific row number. The following example retrieves every other row in the result set, starting with the second row.
Il precedente esempio visualizzerà:
|
Returns an object in which each property represents a column returned in the row fetched from a result set.
A valid stmt resource containing a result set.
Requests a specific 1-indexed row from the result set. Passing this parameter results in a PHP warning if the result set uses a forward-only cursor.
Returns an object representing a single row in the result set. The properties of the object map to the names of the columns in the result set.
The IBM DB2, Cloudscape, and Apache Derby database servers typically fold column names to upper-case, so the object properties will reflect that case.
If your SELECT statement calls a scalar function to modify the value of a column, the database servers return the column number as the name of the column in the result set. If you prefer a more descriptive column name and object property, you can use the AS clause to assign a name to the column in the result set.
Returns FALSE if no row was retrieved.
Esempio 1. A db2_fetch_object() example The following example issues a SELECT statement with a scalar function, RTRIM, that removes whitespace from the end of the column. Rather than creating an object with the properties "BREED" and "2", we use the AS clause in the SELECT statement to assign the name "name" to the modified column. The database server folds the column names to upper-case, resulting in an object with the properties "BREED" and "NAME".
Il precedente esempio visualizzerà:
|
Use db2_fetch_row() to iterate through a result set, or to point to a specific row in a result set if you requested a scrollable cursor.
To retrieve individual fields from the result set, call the db2_result() function.
Rather than calling db2_fetch_row() and db2_result(), most applications will call one of db2_fetch_assoc(), db2_fetch_both(), or db2_fetch_array() to advance the result set pointer and return a complete row as an array.
A valid stmt resource.
With scrollable cursors, you can request a specific row number in the result set. Row numbering is 1-indexed.
Returns TRUE if the requested row exists in the result set. Returns FALSE if the requested row does not exist in the result set.
Esempio 1. Iterating through a result set The following example demonstrates how to iterate through a result set with db2_fetch_row() and retrieve columns from the result set with db2_result().
Il precedente esempio visualizzerà:
|
Returns the maximum number of bytes required to display a column in a result set.
Specifies a statement resource containing a result set.
Specifies the column in the result set. This can either be an integer representing the 0-indexed position of the column, or a string containing the name of the column.
Returns an integer value with the maximum number of bytes required to display the specified column. If the column does not exist in the result set, db2_field_display_size() returns FALSE.
db2_field_name() |
db2_field_num() |
db2_field_precision() |
db2_field_scale() |
db2_field_type() |
db2_field_width() |
Returns the name of the specified column in the result set.
Specifies a statement resource containing a result set.
Specifies the column in the result set. This can either be an integer representing the 0-indexed position of the column, or a string containing the name of the column.
Returns a string containing the name of the specified column. If the specified column does not exist in the result set, db2_field_name() returns FALSE.
db2_field_display_size() |
db2_field_num() |
db2_field_precision() |
db2_field_scale() |
db2_field_type() |
db2_field_width() |
Returns the position of the named column in a result set.
Specifies a statement resource containing a result set.
Specifies the column in the result set. This can either be an integer representing the 0-indexed position of the column, or a string containing the name of the column.
Returns an integer containing the 0-indexed position of the named column in the result set. If the specified column does not exist in the result set, db2_field_num() returns FALSE.
db2_field_display_size() |
db2_field_name() |
db2_field_precision() |
db2_field_scale() |
db2_field_type() |
db2_field_width() |
Returns the precision of the indicated column in a result set.
Specifies a statement resource containing a result set.
Specifies the column in the result set. This can either be an integer representing the 0-indexed position of the column, or a string containing the name of the column.
Returns an integer containing the precision of the specified column. If the specified column does not exist in the result set, db2_field_precision() returns FALSE.
db2_field_display_size() |
db2_field_name() |
db2_field_num() |
db2_field_scale() |
db2_field_type() |
db2_field_width() |
Returns the scale of the indicated column in a result set.
Specifies a statement resource containing a result set.
Specifies the column in the result set. This can either be an integer representing the 0-indexed position of the column, or a string containing the name of the column.
Returns an integer containing the scale of the specified column. If the specified column does not exist in the result set, db2_field_scale() returns FALSE.
db2_field_display_size() |
db2_field_name() |
db2_field_num() |
db2_field_precision() |
db2_field_type() |
db2_field_width() |
Returns the data type of the indicated column in a result set.
Specifies a statement resource containing a result set.
Specifies the column in the result set. This can either be an integer representing the 0-indexed position of the column, or a string containing the name of the column.
Returns a string containing the defined data type of the specified column. If the specified column does not exist in the result set, db2_field_type() returns FALSE.
db2_field_display_size() |
db2_field_name() |
db2_field_num() |
db2_field_precision() |
db2_field_scale() |
db2_field_width() |
(PECL)
db2_field_width -- Returns the width of the current value of the indicated column in a result setReturns the width of the current value of the indicated column in a result set. This is the maximum width of the column for a fixed-length data type, or the actual width of the column for a variable-length data type.
Specifies a statement resource containing a result set.
Specifies the column in the result set. This can either be an integer representing the 0-indexed position of the column, or a string containing the name of the column.
Returns an integer containing the width of the specified character or binary data type column in a result set. If the specified column does not exist in the result set, db2_field_width() returns FALSE.
db2_field_display_size() |
db2_field_name() |
db2_field_num() |
db2_field_precision() |
db2_field_scale() |
db2_field_type() |
Returns a result set listing the foreign keys for a table.
A valid connection to an IBM DB2, Cloudscape, or Apache Derby database.
A qualifier for DB2 databases running on OS/390 or z/OS servers. For other databases, pass NULL or an empty string.
The schema which contains the tables. If schema is NULL, db2_foreign_keys() matches the schema for the current connection.
The name of the table.
Returns a statement resource with a result set containing rows describing the foreign keys for the specified table. The result set is composed of the following columns:
Column name | Description |
---|---|
PKTABLE_CAT | Name of the catalog for the table containing the primary key. The value is NULL if this table does not have catalogs. |
PKTABLE_SCHEM | Name of the schema for the table containing the primary key. |
PKTABLE_NAME | Name of the table containing the primary key. |
PKCOLUMN_NAME | Name of the column containing the primary key. |
FKTABLE_CAT | Name of the catalog for the table containing the foreign key. The value is NULL if this table does not have catalogs. |
FKTABLE_SCHEM | Name of the schema for the table containing the foreign key. |
FKTABLE_NAME | Name of the table containing the foreign key. |
FKCOLUMN_NAME | Name of the column containing the foreign key. |
KEY_SEQ | 1-indexed position of the column in the key. |
UPDATE_RULE | Integer value representing the action applied to the foreign key when the SQL operation is UPDATE. |
DELETE_RULE | Integer value representing the action applied to the foreign key when the SQL operation is DELETE. |
FK_NAME | The name of the foreign key. |
PK_NAME | The name of the primary key. |
DEFERRABILITY | An integer value representing whether the foreign key deferrability is SQL_INITIALLY_DEFERRED, SQL_INITIALLY_IMMEDIATE, or SQL_NOT_DEFERRABLE. |
db2_column_privileges() |
db2_columns() |
db2_primary_keys() |
db2_procedure_columns() |
db2_procedures() |
db2_special_columns() |
db2_statistics() |
db2_table_privileges() |
db2_tables() |
Frees the system and database resources that are associated with a result set. These resources are freed implicitly when a script finishes, but you can call db2_free_result() to explicitly free the result set resources before the end of the script.
Frees the system and database resources that are associated with a statement resource. These resources are freed implicitly when a script finishes, but you can call db2_free_stmt() to explicitly free the statement resources before the end of the script.
A stored procedure can return zero or more result sets. While you handle the first result set in exactly the same way you would handle the results returned by a simple SELECT statement, to fetch the second and subsequent result sets from a stored procedure you must call the db2_next_result() function and return the result to a uniquely named PHP variable.
Returns a new statement resource containing the next result set if the stored procedure returned another result set. Returns FALSE if the stored procedure did not return another result set.
Esempio 1. Calling a stored procedure that returns multiple result sets In the following example, we call a stored procedure that returns three result sets. The first result set is fetched directly from the same statement resource on which we invoked the CALL statement, while the second and third result sets are fetched from statement resources returned from our calls to the db2_next_result() function.
Il precedente esempio visualizzerà:
|
Returns the number of fields contained in a result set. This is most useful for handling the result sets returned by dynamically generated queries, or for result sets returned by stored procedures, where your application cannot otherwise know how to retrieve and use the results.
Returns an integer value representing the number of fields in the result set associated with the specified statement resource. Returns FALSE if the statement resource is not a valid input value.
Esempio 1. Retrieving the number of fields in a result set The following example demonstrates how to retrieve the number of fields returned in a result set.
Il precedente esempio visualizzerà:
|
db2_execute() |
db2_field_display_size() |
db2_field_name() |
db2_field_num() |
db2_field_precision() |
db2_field_scale() |
db2_field_type() |
db2_field_width() |
Returns the number of rows deleted, inserted, or updated by an SQL statement.
To determine the number of rows that will be returned by a SELECT statement, issue SELECT COUNT(*) with the same predicates as your intended SELECT statement and retrieve the value.
If your application logic checks the number of rows returned by a SELECT statement and branches if the number of rows is 0, consider modifying your application to attempt to return the first row with one of db2_fetch_assoc(), db2_fetch_both(), db2_fetch_array(), or db2_fetch_row(), and branch if the fetch function returns FALSE.
Nota: If you issue a SELECT statement using a scrollable cursor, db2_num_rows() returns the number of rows returned by the SELECT statement. However, the overhead associated with scrollable cursors significantly degrades the performance of your application, so if this is the only reason you are considering using scrollable cursors, you should use a forward-only cursor and either call SELECT COUNT(*) or rely on the boolean return value of the fetch functions to achieve the equivalent functionality with much better performance.
Returns the number of rows affected by the last SQL statement issued by the specified statement handle.
Returns a persistent connection to an IBM DB2 Universal Database, IBM Cloudscape, or Apache Derby database. For more information on persistent connections, refer to Capitolo 41.
Calling db2_close() on a persistent connection always returns TRUE, but the underlying DB2 client connection remains open and waiting to serve the next matching db2_pconnect() request.
Note that you are strongly urged to only use persistent connections on connections with autocommit turned on. If you attempt to combine transactions with persistent connections, issuing db2_commit() or db2_rollback() against a persistent connection will affect every persistent connection that is currently using the same underlying DB2 client connection. You may also rapidly experience locking escalation if you do not use autocommit for your persistent connections.
The database alias in the DB2 client catalog.
The username with which you are connecting to the database.
The password with which you are connecting to the database.
An associative array of connection options that affect the behavior of the connection, where valid array keys include:
Passing the DB2_AUTOCOMMIT_ON value turns autocommit on for this connection handle.
Passing the DB2_AUTOCOMMIT_OFF value turns autocommit off for this connection handle.
Returns a connection handle resource if the connection attempt is successful. db2_pconnect() tries to reuse an existing connection resource that exactly matches the database, username, and password parameters. If the connection attempt fails, db2_pconnect() returns FALSE.
Esempio 1. A db2_pconnect() example In the following example, the first call to db2_pconnect() returns a new persistent connection resource. The second call to db2_pconnect() returns a persistent connection resource that simply reuses the first persistent connection resource.
Il precedente esempio visualizzerà:
|
db2_prepare() creates a prepared SQL statement which can include 0 or more parameter markers (? characters) representing parameters for input, output, or input/output. You can pass parameters to the prepared statement using db2_bind_param(), or for input values only, as an array passed to db2_execute().
There are three main advantages to using prepared statements in your application:
Performance: when you prepare a statement, the database server creates an optimized access plan for retrieving data with that statement. Subsequently issuing the prepared statement with db2_execute() enables the statements to reuse that access plan and avoids the overhead of dynamically creating a new access plan for every statement you issue.
Security: when you prepare a statement, you can include parameter markers for input values. When you execute a prepared statement with input values for placeholders, the database server checks each input value to ensure that the type matches the column definition or parameter definition.
Advanced functionality: Parameter markers not only enable you to pass input values to prepared SQL statements, they also enable you to retrieve OUT and INOUT parameters from stored procedures using db2_bind_param().
A valid database connection resource variable as returned from db2_connect() or db2_pconnect().
An SQL statement, optionally containing one or more parameter markers..
An associative array containing statement options. You can use this parameter to request a scrollable cursor on database servers that support this functionality.
Passing the DB2_FORWARD_ONLY value requests a forward-only cursor for this SQL statement. This is the default type of cursor, and it is supported by all database servers. It is also much faster than a scrollable cursor.
Passing the DB2_SCROLLABLE value requests a scrollable cursor for this SQL statement. This type of cursor enables you to fetch rows non-sequentially from the database server. However, it is only supported by DB2 servers, and is much slower than forward-only cursors.
Returns a statement resource if the SQL statement was successfully parsed and prepared by the database server. Returns FALSE if the database server returned an error. You can determine which error was returned by calling db2_stmt_error() or db2_stmt_errormsg().
Esempio 1. Preparing and executing an SQL statement with parameter markers The following example prepares an INSERT statement that accepts four parameter markers, then iterates over an array of arrays containing the input values to be passed to db2_execute().
|
Returns a result set listing the primary keys for a table.
A valid connection to an IBM DB2, Cloudscape, or Apache Derby database.
A qualifier for DB2 databases running on OS/390 or z/OS servers. For other databases, pass NULL or an empty string.
The schema which contains the tables. If schema is NULL, db2_primary_keys() matches the schema for the current connection.
The name of the table.
Returns a statement resource with a result set containing rows describing the primary keys for the specified table. The result set is composed of the following columns:
Column name | Description |
---|---|
TABLE_CAT | Name of the catalog for the table containing the primary key. The value is NULL if this table does not have catalogs. |
TABLE_SCHEM | Name of the schema for the table containing the primary key. |
TABLE_NAME | Name of the table containing the primary key. |
COLUMN_NAME | Name of the column containing the primary key. |
KEY_SEQ | 1-indexed position of the column in the key. |
PK_NAME | The name of the primary key. |
db2_column_privileges() |
db2_columns() |
db2_foreign_keys() |
db2_procedure_columns() |
db2_procedures() |
db2_special_columns() |
db2_statistics() |
db2_table_privileges() |
db2_tables() |
Returns a result set listing the parameters for one or more stored procedures.
A valid connection to an IBM DB2, Cloudscape, or Apache Derby database.
A qualifier for DB2 databases running on OS/390 or z/OS servers. For other databases, pass NULL or an empty string.
The schema which contains the procedures. This parameter accepts a search pattern containing _ and % as wildcards.
The name of the procedure. This parameter accepts a search pattern containing _ and % as wildcards.
The name of the parameter. This parameter accepts a search pattern containing _ and % as wildcards. If this parameter is NULL, all parameters for the specified stored procedures are returned.
Returns a statement resource with a result set containing rows describing the parameters for the stored procedures matching the specified parameters. The rows are composed of the following columns:
Column name | Description |
---|---|
PROCEDURE_CAT | The catalog that contains the procedure. The value is NULL if this table does not have catalogs. |
PROCEDURE_SCHEM | Name of the schema that contains the stored procedure. |
PROCEDURE_NAME | Name of the procedure. |
COLUMN_NAME | Name of the parameter. |
COLUMN_TYPE |
An integer value representing the type of the parameter: |
DATA_TYPE | The SQL data type for the parameter represented as an integer value. |
TYPE_NAME | A string representing the data type for the parameter. |
COLUMN_SIZE | An integer value representing the size of the parameter. |
BUFFER_LENGTH | Maximum number of bytes necessary to store data for this parameter. |
DECIMAL_DIGITS | The scale of the parameter, or NULL where scale is not applicable. |
NUM_PREC_RADIX | An integer value of either 10 (representing an exact numeric data type), 2 (representing an approximate numeric data type), or NULL (representing a data type for which radix is not applicable). |
NULLABLE | An integer value representing whether the parameter is nullable or not. |
REMARKS | Description of the parameter. |
COLUMN_DEF | Default value for the parameter. |
SQL_DATA_TYPE | An integer value representing the size of the parameter. |
SQL_DATETIME_SUB | Returns an integer value representing a datetime subtype code, or NULL for SQL data types to which this does not apply. |
CHAR_OCTET_LENGTH | Maximum length in octets for a character data type parameter, which matches COLUMN_SIZE for single-byte character set data, or NULL for non-character data types. |
ORDINAL_POSITION | The 1-indexed position of the parameter in the CALL statement. |
IS_NULLABLE | A string value where 'YES' means that the parameter accepts or returns NULL values and 'NO' means that the parameter does not accept or return NULL values. |
db2_column_privileges() |
db2_columns() |
db2_foreign_keys() |
db2_primary_keys() |
db2_procedures() |
db2_special_columns() |
db2_statistics() |
db2_table_privileges() |
db2_tables() |
Returns a result set listing the stored procedures registered in a database.
A valid connection to an IBM DB2, Cloudscape, or Apache Derby database.
A qualifier for DB2 databases running on OS/390 or z/OS servers. For other databases, pass NULL or an empty string.
The schema which contains the procedures. This parameter accepts a search pattern containing _ and % as wildcards.
The name of the procedure. This parameter accepts a search pattern containing _ and % as wildcards.
Returns a statement resource with a result set containing rows describing the stored procedures matching the specified parameters. The rows are composed of the following columns:
Column name | Description |
---|---|
PROCEDURE_CAT | The catalog that contains the procedure. The value is NULL if this table does not have catalogs. |
PROCEDURE_SCHEM | Name of the schema that contains the stored procedure. |
PROCEDURE_NAME | Name of the procedure. |
NUM_INPUT_PARAMS | Number of input (IN) parameters for the stored procedure. |
NUM_OUTPUT_PARAMS | Number of output (OUT) parameters for the stored procedure. |
NUM_RESULT_SETS | Number of result sets returned by the stored procedure. |
REMARKS | Any comments about the stored procedure. |
PROCEDURE_TYPE | Always returns 1, indicating that the stored procedure does not return a return value. |
db2_column_privileges() |
db2_columns() |
db2_foreign_keys() |
db2_primary_keys() |
db2_procedure_columns() |
db2_special_columns() |
db2_statistics() |
db2_table_privileges() |
db2_tables() |
Use db2_result() to return the value of a specified column in the current row of a result set. You must call db2_fetch_row() before calling db2_result() to set the location of the result set pointer.
A valid stmt resource.
Either an integer mapping to the 0-indexed field in the result set, or a string matching the name of the column.
Returns the value of the requested field if the field exists in the result set. Returns NULL if the field does not exist, and issues a warning.
Esempio 1. A db2_result() example The following example demonstrates how to iterate through a result set with db2_fetch_row() and retrieve columns from the result set with db2_result().
Il precedente esempio visualizzerà:
|
Rolls back an in-progress transaction on the specified connection resource and begins a new transaction. PHP applications normally default to AUTOCOMMIT mode, so db2_rollback() normally has no effect unless AUTOCOMMIT has been turned off for the connection resource.
Nota: If the specified connection resource is a persistent connection, all transactions in progress for all applications using that persistent connection will be rolled back. For this reason, persistent connections are not recommended for use in applications that require transactions.
A valid database connection resource variable as returned from db2_connect() or db2_pconnect().
Esempio 1. Rolling back a DELETE statement In the following example, we count the number of rows in a table, turn off AUTOCOMMIT mode on a database connection, delete all of the rows in the table and return the count of 0 to prove that the rows have been removed. We then issue db2_rollback() and return the updated count of rows in the table to show that the number is the same as before we issued the DELETE statement. The return to the original state of the table demonstrates that the roll back of the transaction succeeded.
Il precedente esempio visualizzerà:
|
(no version information, might be only in CVS)
db2_server_info -- Returns an object with properties that describe the DB2 database serverThis function returns an object with read-only properties that return information about the IBM DB2, Cloudscape, or Apache Derby database server. The following table lists the database server properties:
Tabella 1. Database server properties
Property name | Return type | Description |
---|---|---|
DBMS_NAME | string | The name of the database server to which you are connected. For DB2 servers this is a combination of DB2 followed by the operating system on which the database server is running. |
DBMS_VER | string | The version of the database server, in the form of a string "MM.mm.uuuu" where MM is the major version, mm is the minor version, and uuuu is the update. For example, "08.02.0001" represents major version 8, minor version 2, update 1. |
DB_CODEPAGE | int | The code page of the database to which you are connected. |
DB_NAME | string | The name of the database to which you are connected. |
DFT_ISOLATION | string | The default transaction isolation level supported by the
server:
|
IDENTIFIER_QUOTE_CHAR | string | The character used to delimit an identifier. |
INST_NAME | string | The instance on the database server that contains the database. |
ISOLATION_OPTION | array | An array of the isolation options supported by the database server. The isolation options are described in the DFT_ISOLATION property. |
KEYWORDS | array | An array of the keywords reserved by the database server. |
LIKE_ESCAPE_CLAUSE | bool | TRUE if the database server supports the use of % and _ wildcard characters. FALSE if the database server does not support these wildcard characters. |
MAX_COL_NAME_LEN | int | Maximum length of a column name supported by the database server, expressed in bytes. |
MAX_IDENTIFIER_LEN | int | Maximum length of an SQL identifier supported by the database server, expressed in characters. |
MAX_INDEX_SIZE | int | Maximum size of columns combined in an index supported by the database server, expressed in bytes. |
MAX_PROC_NAME_LEN | int | Maximum length of a procedure name supported by the database server, expressed in bytes. |
MAX_ROW_SIZE | int | Maximum length of a row in a base table supported by the database server, expressed in bytes. |
MAX_SCHEMA_NAME_LEN | int | Maximum length of a schema name supported by the database server, expressed in bytes. |
MAX_STATEMENT_LEN | int | Maximum length of an SQL statement supported by the database server, expressed in bytes. |
MAX_TABLE_NAME_LEN | int | Maximum length of a table name supported by the database server, expressed in bytes. |
NON_NULLABLE_COLUMNS | bool | TRUE if the database server supports columns that can be defined as NOT NULL, FALSE if the database server does not support columns defined as NOT NULL. |
PROCEDURES | bool | TRUE if the database server supports the use of the CALL statement to call stored procedures, FALSE if the database server does not support the CALL statement. |
SPECIAL_CHARS | string | A string containing all of the characters other than a-Z, 0-9, and underscore that can be used in an identifier name. |
SQL_CONFORMANCE | string | The level of conformance to the ANSI/ISO SQL-92 specification
offered by the database server:
|
Esempio 1. A db2_server_info() example To retrieve information about the server, you must pass a valid database connection resource to db2_server_info().
Il precedente esempio visualizzerà:
|
(PECL)
db2_special_columns -- Returns a result set listing the unique row identifier columns for a tableReturns a result set listing the unique row identifier columns for a table.
A valid connection to an IBM DB2, Cloudscape, or Apache Derby database.
A qualifier for DB2 databases running on OS/390 or z/OS servers. For other databases, pass NULL or an empty string.
The schema which contains the tables.
The name of the table.
Integer value representing the minimum duration for which the unique row identifier is valid. This can be one of the following values:
Returns a statement resource with a result set containing rows with unique row identifier information for a table. The rows are composed of the following columns:
Column name | Description |
---|---|
SCOPE |
|
COLUMN_NAME | Name of the unique column. |
DATA_TYPE | SQL data type for the column. |
TYPE_NAME | Character string representation of the SQL data type for the column. |
COLUMN_SIZE | An integer value representing the size of the column. |
BUFFER_LENGTH | Maximum number of bytes necessary to store data from this column. |
DECIMAL_DIGITS | The scale of the column, or NULL where scale is not applicable. |
NUM_PREC_RADIX | An integer value of either 10 (representing an exact numeric data type), 2 (representing an approximate numeric data type), or NULL (representing a data type for which radix is not applicable). |
PSEUDO_COLUMN | Always returns 1. |
db2_column_privileges() |
db2_columns() |
db2_foreign_keys() |
db2_primary_keys() |
db2_procedure_columns() |
db2_procedures() |
db2_statistics() |
db2_table_privileges() |
db2_tables() |
Returns a result set listing the index and statistics for a table.
A valid connection to an IBM DB2, Cloudscape, or Apache Derby database.
A qualifier for DB2 databases running on OS/390 or z/OS servers. For other databases, pass NULL or an empty string.
The schema that contains the targeted table. If this parameter is NULL, the statistics and indexes are returned for the schema of the current user.
The name of the table.
An integer value representing the type of index information to return.
Return only the information for unique indexes on the table.
Return the information for all indexes on the table.
Returns a statement resource with a result set containing rows describing the statistics and indexes for the base tables matching the specified parameters. The rows are composed of the following columns:
Column name | Description | ||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
TABLE_CAT | The catalog that contains the table. The value is NULL if this table does not have catalogs. | ||||||||||
TABLE_SCHEM | Name of the schema that contains the table. | ||||||||||
TABLE_NAME | Name of the table. | ||||||||||
NON_UNIQUE |
An integer value representing whether the index prohibits unique values, or whether the row represents statistics on the table itself: | ||||||||||
INDEX_QUALIFIER | A string value representing the qualifier that would have to be prepended to INDEX_NAME to fully qualify the index. | ||||||||||
INDEX_NAME | A string representing the name of the index. | ||||||||||
TYPE |
An integer value representing the type of information contained in this row of the result set:
| ||||||||||
ORDINAL_POSITION | The 1-indexed position of the column in the index. NULL if the row contains statistics information about the table itself. | ||||||||||
COLUMN_NAME | The name of the column in the index. NULL if the row contains statistics information about the table itself. | ||||||||||
ASC_OR_DESC | A if the column is sorted in ascending order, D if the column is sorted in descending order, NULL if the row contains statistics information about the table itself. | ||||||||||
CARDINALITY |
If the row contains information about an index, this column contains an integer value representing the number of unique values in the index. If the row contains information about the table itself, this column contains an integer value representing the number of rows in the table. | ||||||||||
PAGES |
If the row contains information about an index, this column contains an integer value representing the number of pages used to store the index. If the row contains information about the table itself, this column contains an integer value representing the number of pages used to store the table. | ||||||||||
FILTER_CONDITION | Always returns NULL. |
db2_column_privileges() |
db2_columns() |
db2_foreign_keys() |
db2_primary_keys() |
db2_procedure_columns() |
db2_procedures() |
db2_special_columns() |
db2_table_privileges() |
db2_tables() |
Returns a string containing the SQLSTATE value returned by an SQL statement.
If you do not pass a statement resource as an argument to db2_stmt_error(), the driver returns the SQLSTATE value associated with the last attempt to return a statement resource, for example, from db2_prepare() or db2_exec().
To learn what the SQLSTATE value means, you can issue the following command at a DB2 Command Line Processor prompt: db2 '? sqlstate-value'. You can also call db2_stmt_errormsg() to retrieve an explicit error message and the associated SQLCODE value.
Returns a string containing the last SQL statement error message.
If you do not pass a statement resource as an argument to db2_stmt_errormsg(), the driver returns the error message associated with the last attempt to return a statement resource, for example, from db2_prepare() or db2_exec().
Returns a string containing the error message and SQLCODE value for the last error that occurred issuing an SQL statement.
(PECL)
db2_table_privileges -- Returns a result set listing the tables and associated privileges in a databaseReturns a result set listing the tables and associated privileges in a database.
A valid connection to an IBM DB2, Cloudscape, or Apache Derby database.
A qualifier for DB2 databases running on OS/390 or z/OS servers. For other databases, pass NULL or an empty string.
The schema which contains the tables. This parameter accepts a search pattern containing _ and % as wildcards.
The name of the table. This parameter accepts a search pattern containing _ and % as wildcards.
Returns a statement resource with a result set containing rows describing the privileges for the tables that match the specified parameters. The rows are composed of the following columns:
Column name | Description |
---|---|
TABLE_CAT | The catalog that contains the table. The value is NULL if this table does not have catalogs. |
TABLE_SCHEM | Name of the schema that contains the table. |
TABLE_NAME | Name of the table. |
GRANTOR | Authorization ID of the user who granted the privilege. |
GRANTEE | Authorization ID of the user to whom the privilege was granted. |
PRIVILEGE | The privilege that has been granted. This can be one of ALTER, CONTROL, DELETE, INDEX, INSERT, REFERENCES, SELECT, or UPDATE. |
IS_GRANTABLE | A string value of "YES" or "NO" indicating whether the grantee can grant the privilege to other users. |
db2_column_privileges() |
db2_columns() |
db2_foreign_keys() |
db2_primary_keys() |
db2_procedure_columns() |
db2_procedures() |
db2_special_columns() |
db2_statistics() |
db2_tables() |
Returns a result set listing the tables and associated metadata in a database.
A valid connection to an IBM DB2, Cloudscape, or Apache Derby database.
A qualifier for DB2 databases running on OS/390 or z/OS servers. For other databases, pass NULL or an empty string.
The schema which contains the tables. This parameter accepts a search pattern containing _ and % as wildcards.
The name of the table. This parameter accepts a search pattern containing _ and % as wildcards.
A list of comma-delimited table type identifiers. To match all table types, pass NULL or an empty string. Valid table type identifiers include: ALIAS, HIERARCHY TABLE, INOPERATIVE VIEW, NICKNAME, MATERIALIZED QUERY TABLE, SYSTEM TABLE, TABLE, TYPED TABLE, TYPED VIEW, and VIEW.
Nota: Icap will be removed in near future. Neither this module, nor those versions of icap library are supported any longer. If you want to use calendar capabilities in PHP, use mcal instead.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
icap_delete_event() deletes the calendar event specified by the uid.
Returns TRUE.
icap_fetch_event() fetches an event from the calendar stream specified by event_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 year - year
int month - month
int mday - day of month
int hour - hour
int min - minutes
int sec - seconds
(PHP 4 <= 4.2.3)
icap_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 at the given datetime.
icap_list_alarms() function takes in a datetime for a calendar stream. An array of event id's that has an alarm should be going off at the datetime are returned.
All datetime entries consist of an object that contains:
int year - year
int month - month
int mday - day of month
int hour - hour
int min - minutes
int sec - seconds
Returns an array of event ID's that are between the two given datetimes.
icap_list_events() function takes in a beginning datetime and an end datetime for a calendar stream. An array of event id's that are between the given datetimes are returned.
All datetime entries consist of an object that contains:
int year - year
int month - month
int mday - day of month
int hour - hour
int min - minutes
int sec - seconds
Returns an ICAP stream on success, FALSE on error.
icap_open() opens up an ICAP connection to the specified calendar store. If the optional options is specified, passes the options to that mailbox also.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
icap_snooze() turns on an alarm for a calendar event specified by the uid.
Returns TRUE.
icap_store_event() Stores an event into an ICAP calendar. An event object consists of:
int public - 1 if public, 0 if 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 out an alarm.
datetime start - datetime object of the start of the event.
datetime end - datetime object of the end of the event.
All datetime entries consist of an object that contains:
int year - year
int month - month
int mday - day of month
int hour - hour
int min - minutes
int sec - seconds
Returns TRUE on success and FALSE on error.
Questo modulo contiene un'interfaccia al tool di conversione dei caratteri iconv. Tramite questo modulo si può convertire una stringa dal set di caratteri locale ad un'altro. I set di caratteri supportati dipendono dalla implementazione di iconv installata. Occorre rilevare che le funzioni iconv, in alcuni sistemi, possono non fornire le risposte attese. In questi casi è una buona idea installarela libreria GNU libiconv, la quale fornisce risultati più consistenti.
Dalla versione 5.0.0 di PHP, questa versione viene rilasciata con diverse funzioni che aiutano a realizzare script in più lingue. Guardare nelle sezioni seguenti per scoprire queste nuove caratteristiche.
Non occorre nulla se il sistema che si sta utilizzando è un sistema recente compatibile POSIX, poichè le librerie C standard fornite con la macchina forniscono le funzioni iconv. Negli altri casi occorre installare sul sistema la libreria libiconv
Per potere utilizzare le funzioni fornite da questo modulo, occorre compila il PHP con la seguente linea di configurazione: --with-iconv[=DIR].
Note per gli utenti Windows®: Per potere abilitare questo modulo nei sistemi Windows® occorre posizionare la DLL iconv.dll o iconv-1.3.dll (nelle versioni precedenti alla 4.2.1), rilasciata con il pacchetto PHP/Win32 nella directory indicata dalla variabile d'ambiente PATH oppure in una directory di installazione di Windows®.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. Parametri di configurazione di Iconv
Nome | Default | Modificabile |
---|---|---|
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 |
Dalla versione 4.3.0 di PHP è possibile identificare da untime quale implementazione di iconv è adottata da questo modulo.
Tabella 2. Costanti iconv
Nome | Tipo | Descrizione |
---|---|---|
ICONV_IMPL | string | Il nome dell'implementazione |
ICONV_VERSION | string | Versione dell'implementazione |
Nota: La scrittura di codice che utilizzi tali costanti per identificare l'implementazione è scoraggiata.
Dalla versione 5.0.0 di PHP saranno disponibili le seguenti costanti:
Tabella 3. Costanti iconv dispèonibili da PHP 5.0.0
Nome | Tipo | Descrizione |
---|---|---|
ICONV_MIME_DECODE_STRICT | integer | Maschera di bit utilizzata da iconv_mime_decode() |
ICONV_MIME_DECODE_CONTINUE_ON_ERROR | integer | Maschera di bit utilizzata per iconv_mime_decode() |
(PHP 4 >= 4.0.5, PHP 5)
iconv_get_encoding -- Visualizza l'attuale impostazione per la conversione dei caratteri codificatiRestituisce l'attuale impostazione di ob_iconv_handler() come array o FALSE in caso di insuccesso.
Vedere anche: iconv_set_encoding() e ob_iconv_handler().
Returns an associative array that holds a whole set of MIME header fields specified by encoded_headers on success, or FALSE if an error occurs during the decoding.
Each key of the return value represents an individual field name and the corresponding element represents a field value. If more than one field of the same name are present, iconv_mime_decode_headers() automatically incorporates them into a numerically indexed array in the order of occurrence.
mode determines the behaviour in the event iconv_mime_decode_headers() encounters a malformed MIME header field. You can specify any combination of the following bitmasks.
Tabella 1. Bitmasks acceptable to iconv_mime_decode_headers()
Value | Constant | Description |
---|---|---|
1 | ICONV_MIME_DECODE_STRICT | If set, the given header is decoded in full conformance with the standards defined in RFC2047. This option is disabled by default because there are a lot of broken mail user agents that don't follow the specification and don't produce correct MIME headers. |
2 | ICONV_MIME_DECODE_CONTINUE_ON_ERROR | If set, iconv_mime_decode_headers() attempts to ignore any grammatical errors and continue to process a given header. |
The optional charset parameter specifies the character set to represent the result by. If omitted, iconv.internal_charset will be used.
Esempio 1. iconv_mime_decode_headers() example
Il precedente esempio visualizzerà:
|
See also iconv_mime_decode(), mb_decode_mimeheader(), imap_mime_header_decode(), imap_base64() and imap_qprint().
Returns a decoded MIME field on success, or FALSE if an error occurs during the decoding.
mode determines the behaviour in the event iconv_mime_decode() encounters a malformed MIME header field. You can specify any combination of the following bitmasks.
Tabella 1. Bitmasks acceptable to iconv_mime_decode()
Value | Constant | Description |
---|---|---|
1 | ICONV_MIME_DECODE_STRICT | If set, the given header is decoded in full conformance with the standards defined in RFC2047. This option is disabled by default because there are a lot of broken mail user agents that don't follow the specification and don't produce correct MIME headers. |
2 | ICONV_MIME_DECODE_CONTINUE_ON_ERROR | If set, iconv_mime_decode() attempts to continue to process the given header even though an error occurs. |
The optional charset parameter specifies the character set to represent the result by. If omitted, iconv.internal_charset will be used.
See also iconv_mime_decode_headers(), mb_decode_mimeheader(), imap_mime_header_decode(), imap_base64() and imap_qprint().
Composes and returns a string that represents a valid MIME header field, which looks like the following:
Subject: =?ISO-8859-1?Q?Pr=FCfung_f=FCr?= Entwerfen von einer MIME kopfzeile |
You can control the behaviour of iconv_mime_encode() by specifying an associative array that contains configuration items to the optional third parameter preferences. The items supported by iconv_mime_encode() are listed below. Note that item names are treated case-sensitive.
Tabella 1. Configuration items supported by iconv_mime_encode()
Item | Type | Description | Default value | Example |
---|---|---|---|---|
scheme | boolean | Specifies the method to encode a field value by. The value of this item may be either "B" or "Q", where "B" stands for base64 encoding scheme and "Q" stands for quoted-printable encoding scheme. | B | B |
input-charset | string | Specifies the character set in which the first parameter field_name and the second parameter field_value are presented. If not given, iconv_mime_encode() assumes those parameters are presented to it in the iconv.internal_charset ini setting. | iconv.internal_charset | ISO-8859-1 |
output-charset | string | Specifies the character set to use to compose the MIME header. If not given, the same value as input-charset will be used. | the same value as input-charset | UTF-8 |
line-length | integer | Specifies the maximum length of the header lines. The resulting header is "folded" to a set of multiple lines in case the resulting header field would be longer than the value of this parameter, according to RFC2822 - Internet Message Format. If not given, the length will be limited to 76 characters. | 76 | 996 |
line-break-chars | string | Specifies the sequence of characters to append to each line as an end-of-line sign when "folding" is performed on a long header field. If not given, this defaults to "\r\n" (CR LF). Note that this parameter is always treated as an ASCII string regardless of the value of input-charset. | \r\n | \n |
Esempio 1. iconv_mime_encode() example:
|
See also imap_binary(), mb_encode_mimeheader() and imap_8bit().
(PHP 4 >= 4.0.5, PHP 5)
iconv_set_encoding -- Setta l'attuale impostazione per la conversione dei caratteri codificatiCambia il valore di type in charset e restituisc TRUE in caso di successo o FALSE in caso di fallimento.
Vedere anche: iconv_get_encoding() e ob_iconv_handler().
Returns the character count of str.
In contrast to strlen(), iconv_strlen() counts the occurrences of characters in the given byte sequence str on the basis of the specified character set, the result of which is not necessarily identical to the length of the string in byte.
If charset parameter is omitted, str is assumed to be encoded in iconv.internal_charset.
See also strlen() and mb_strlen().
Returns the numeric position of the first occurrence of needle in haystack.
The optional offset parameter specifies the position from which the search should be performed.
If needle is not found, iconv_strpos() will return FALSE.
Avvertimento |
Questa funzione può restituire il Booleano FALSE, ma può anche restituire un valore non-Booleano valutato come FALSE, come ad esempio 0 o "". Per favore fare riferimento alla sezione Booleans per maggiori informazioni. Usare l'operatore === per controllare il valore restituito da questa funzione. |
If haystack or needle is not a string, it is converted to a string and applied as the ordinal value of a character.
In contrast to strpos(), the return value of iconv_strpos() is the number of characters that appear before the needle, rather than the offset in bytes to the position where the needle has been found. The characters are counted on the basis of the specified character set charset.
If charset parameter is omitted, string are assumed to be encoded in iconv.internal_charset.
See also strpos(), iconv_strrpos() and mb_strpos().
(PHP 5)
iconv_strrpos -- Finds the last occurrence of a needle within the specified range of haystackReturns the numeric position of the last occurrence of needle in haystack.
If needle is not found, iconv_strrpos() will return FALSE.
Avvertimento |
Questa funzione può restituire il Booleano FALSE, ma può anche restituire un valore non-Booleano valutato come FALSE, come ad esempio 0 o "". Per favore fare riferimento alla sezione Booleans per maggiori informazioni. Usare l'operatore === per controllare il valore restituito da questa funzione. |
If haystack or needle is not a string, it is converted to a string and applied as the ordinal value of a character.
In contrast to strpos(), the return value of iconv_strrpos() is the number of characters that appear before the needle, rather than the offset in bytes to the position where the needle has been found. The characters are counted on the basis of the specified character set charset.
See also strrpos(), iconv_strpos() and mb_strrpos().
Returns the portion of str specified by the start and length parameters.
If start is non-negative, iconv_substr() cuts the portion out of str beginning at start'th character, counting from zero.
If start is negative, iconv_substr() cuts out the portion beginning at the position, start characters away from the end of str.
If length is given and is positive, the return value will contain at most length characters of the portion that begins at start (depending on the length of string). If str is shorter than start characters long, FALSE will be returned.
If negative length is passed, iconv_substr() cuts the portion out of str from the start'th character up to the character that is length characters away from the end of the string. In case start is also negative, the start position is calculated beforehand according to the rule explained above.
Note that offset and length parameters are always deemed to represent offsets that are calculated on the basis of the character set determined by charset, whilst the counterpart substr() always takes these for byte offsets. If charset is not given, the character set is determined by the iconv.internal_encoding ini setting.
See also substr(), mb_substr() and mb_strcut().
Converte la stringa codificata nel parametro stringa in in_charset nella stringa codificata in out_charset. Restituisce la stringa convertita o FALSE, se fallisce.
(PHP 4 >= 4.0.5, PHP 5)
ob_iconv_handler -- Converte caratteri codificati come un output buffer handlerConverte la stringa codificata del parametro internal_encoding in output_encoding.
internal_encoding e output_encoding dovrebbero essere definite da iconv_set_encoding() o nel file di configurazione.
Vedere anche: iconv_get_encoding() e iconv_set_encoding().
These functions let you read and manipulate ID3 tags. ID3 tags are used in MP3 files to store title of the song, as well as information about the artist, album, genre, year and track number.
Since version 0.2 it is also possible to extract text frames from ID3 v2.2+ tags.
id3 is part of PECL and can be installed using the PEAR installer. To compile PHP with id3 support, download the sourcecode, put it in php-src/ext/id3 and compile PHP using --enable-id3.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Most of the id3 functions either let you specify or return a tag version. In order to specify the version please use on of these constants.
ID3_V1_0 is used if you are working with ID3 V1.0 tags. These tags may contain the fields title, artist, album, genre, year and comment.
ID3_V1_1 is used if you are working with ID3 V1.1 tags. These tags may all information contained in v1.0 tags plus the track number.
ID3_V2_1 is used if you are working with ID3 V2.1 tags.
ID3_V2_2 is used if you are working with ID3 V2.2 tags.
ID3_V2_3 is used if you are working with ID3 V2.3 tags.
ID3_V2_4 is used if you are working with ID3 V2.4 tags.
ID3_BEST is used if would like to let the id3 functions determine which tag version should be used.
id3_get_frame_long_name() returns the long name for an ID3v2 frame.
See also id3_get_frame_short_name().
id3_get_frame_short_name() returns the short name for an ID3v2 frame.
The values returned by id3_get_short_name() are used in the array returned by id3_get_tag().
See also id3_get_frame_long_name().
id3_get_genre_id() returns the id for a genre. If the specified genre is not available in the genre list, id3_get_genre_id() will return FALSE
In an ID3 tag, the genre is stored using a integer ranging from 0 to 147.
See also id3_get_genre_list() and id3_get_genre_name().
id3_get_genre_list() returns an array containing all possible genres that may be stored in an ID3 tag. This list has been created by Eric Kemp and later extended by WinAmp.
This function is useful to provide you users a list of genres from which they may choose one. When updating the ID3 tag you will always have to specify the genre as an integer ranging from 0 to 147.
Esempio 1. id3_get_genre_list() example
This will output:
|
See also id3_get_genre_name() and id3_get_genre_id().
id3_get_genre_name() returns the name for a genre id.
In an ID3 tag, the genre is stored using a integer ranging from 0 to 147.
See also id3_get_genre_list() and id3_get_genre_id().
id3_get_tag() is used to get all information stored in the id3 tag of the specified file.
Nota: Instead of a filename you may also pass a valid stream resource.
The optional version parameter allows you to specify the version of the tag as MP3 files may contain both, version 1.x and version 2.x tags.
The key genre will contain an integer between 0 and 147. You may use id3_get_genre_name() to convert it to a human readable string.
Since version 0.2 id3_get_tag() also supports ID3 tags of version 2.2, 2.3 and 2.4. To extract information from these tags, pass one of the constants ID3_V2_2, ID3_V2_3 or ID3_V2_4 as the second parameter.
Esempio 2. id3_get_tag() example
This will output something like:
|
ID3 v2.x tags can contain a lot more information about the MP3 file than ID3 v1.x tags.
See also id3_set_tag(), id3_remove_tag() and id3_get_version().
id3_get_version() retrieves the version(s) of the ID3 tag(s) in the MP3 file. As a tag can contain ID3 v1.x and v2.x tags, the return value of this function should be bitwise compared with the predefined constants ID3_V1_0, ID3_V1_1 and ID3_V2.
Nota: Instead of a filename you may also pass a valid stream resource.
Esempio 1. id3_get_version() example
This will output something like:
|
If a file contains an ID3 v1.1 tag, it always contains a 1.0 tag, as version 1.1 is just an extension of 1.0.
See also id3_get_tag(), id3_set_tag() and id3_remove_tag().
id3_remove_tag() is used to remove the information stored of an ID3 tag. If no tag has been present, it will return FALSE and leave the file as it was.
Nota: Instead of a filename you may also pass a valid stream resource.
The optional version parameter allows you to specify the version of the tag as MP3 files may contain both, version 1.x and version 2.x tags.
Nota: Currently id3_remove_tag() only supports version 1.0 and 1.1. If you choose to remove a 1.0 tag and the file contains a 1.1 tag, this tag will be removed, as v1.1 is only an extension of 1.0.
See also id3_get_tag(), id3_set_tag() and id3_get_version().
id3_set_tag() is used to change the information stored of an ID3 tag. If no tag has been present, it will be added to the file.
Nota: Instead of a filename you may also pass a valid stream resource.
The optional version parameter allows you to specify the version of the tag as MP3 files may contain both, version 1.x and version 2.x tags.
Esempio 1. id3_set_tag() example
If the file is writable, this will output:
|
Nota: Currently id3_set_tag() only supports version 1.0 and 1.1.
The following keys may be used in the associative array:
Tabella 1. Keys in the associative array
key | possible value | available in version |
---|---|---|
title | string with maximum of 30 characters | v1.0, v1.1 |
artist | string with maximum of 30 characters | v1.0, v1.1 |
album | string with maximum of 30 characters | v1.0, v1.1 |
year | 4 digits | v1.0, v1.1 |
genre | integer value between 0 and 147 | v1.0, v1.1 |
comment | string with maximum of 30 characters (28 in v1.1) | v1.0, v1.1 |
track | integer between 0 and 255 | v1.1 |
See also id3_get_tag(), id3_remove_tag() and id3_get_version().
This PECL extension is not bundled with PHP. Questa estensione è disponibile solo per sistemi Win32. Prevede funzioni per amministrare Microsoft Internet Information Server (IIS). L'estensione include la funzione per creare siti web e directory virtuali come meglio e come la configurazione della sicurezza e lo script mapping. Queste funzioni sono state aggiunte nel PHP 4.
Per potere utilizzare queste funzioni occorre abilitare l'uso della dll php_iisfunc.dll dal php.ini. You may download this PECL extension DLL from the PHP Downloads page or at http://snaps.php.net/.
Non è necessaria nessuna installazione per usare queste funzioni, esse fanno parte del core di PHP.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
(PECL)
iis_get_script_map -- Riceve informazioni sul mapping dello script sulla cartella virtuale per una specifica estensioneo
Ogni server virtuale in IIS è associato con un numero di istanza. iis_get_server_by_path() trova il numero di istanza dall'attuale path alla root directory.
In PHP puoi usare delle funzioni specifiche per sapere la dimensione di un'immagine JPEG, GIF, PNG, SWF, TIFF e JPEG2000.
Se hai installato le librerie GD (scaricabili su http://www.boutell.com/gd/) sarai anche in grado di creare immagini al volo e di modificarle.
I formati delle immagini sulle quali potrai agire dipendono dalla versione delle librerie GD che hai installato, e dalle altre librerie di cui GD può aver bisogno per accedere a quei formati di immagine. Versioni precedenti alla gd-1.6 supportano il formato GIF ma non quello PNG, mentre versioni superiori alla gd-1.6 supportano il formato PNG ma non il GIF.
Se hai compilato PHP con l'opzione --enable-exif sarai in grado di lavorare con le informazioni memorizzate negli header delle immagini JPEG e TIFF. Queste funzioni non richiedono le librerie GD.
Per leggere e scrivere immagini in formato JPEG avrai bisogno di installare jpeg-6b (scaricabile da ftp://ftp.uu.net/graphics/jpeg/) e quindi ricompilare le librerie GD in modo che usino jpeg-6b. Dovrai anche compilare PHP con l'opzione --with-jpeg-dir=/percorso/per/jpeg-6b.
Per aggiungere il supporto per i Font Type 1 dovrai installare t1lib (scaricabile su ftp://sunsite.unc.edu/pub/Linux/libs/graphics/), e quindi aggiungere l'opzione --with-t1lib[=dir].
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Returns an associative array describing the version and capabilities of the installed GD library.
Tabella 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. |
Esempio 1. Using gd_info()
The typical output is :
|
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, IFF, JP2, JPX, JB2, JPC, XBM, or WBMP 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.
If accessing the filename image is impossible, or if it isn't a valid picture, getimagesize() will return FALSE and generate an error of level E_WARNING.
Nota: Support for JPC, JP2, JPX, JB2, XBM, and WBMP became available in PHP 4.3.2. Support for SWC exists as of PHP 4.3.0 and TIFF support was added in PHP 4.2.0
Nota: JPEG 2000 support was added in PHP 4.3.2. Note that JPC and JP2 are capable of having components with different bit depths. In this case, the value for "bits" is the highest bit depth encountered. Also, JP2 files may contain multiple JPEG 2000 codestreams. In this case, getimagesize() returns the values for the first codestream it encounters in the root of the file.
Nota: The getimagesize() function does not require the GD image library.
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, 15 = WBMP, 16 = XBM. These values correspond to the IMAGETYPE constants that were added in PHP 4.3.0. Index 3 is a text string with the correct height="yyy" width="xxx" string that can be used directly in an IMG tag.
URL support was added in PHP 4.0.5
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.0, 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.0, 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:
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.
See also image_type_to_mime_type(), exif_imagetype(), exif_read_data(), and exif_thumbnail().
(no version information, might be only in CVS)
image_type_to_extension -- Get file extension for image typeAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.3.0, PHP 5)
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.
The returned values are as follows
Tabella 1. Returned values Constants
imagetype | Returned value |
---|---|
IMAGETYPE_GIF | image/gif |
IMAGETYPE_JPEG | image/jpeg |
IMAGETYPE_PNG | image/png |
IMAGETYPE_SWF | application/x-shockwave-flash |
IMAGETYPE_PSD | image/psd |
IMAGETYPE_BMP | image/bmp |
IMAGETYPE_TIFF_II (intel byte order) | image/tiff |
IMAGETYPE_TIFF_MM (motorola byte order) | image/tiff |
IMAGETYPE_JPC | application/octet-stream |
IMAGETYPE_JP2 | image/jp2 |
IMAGETYPE_JPX | application/octet-stream |
IMAGETYPE_JB2 | application/octet-stream |
IMAGETYPE_SWC | application/x-shockwave-flash |
IMAGETYPE_IFF | image/iff |
IMAGETYPE_WBMP | image/vnd.wap.wbmp |
IMAGETYPE_XBM | image/xbm |
Nota: This function does not require the GD image library.
See also getimagesize(), exif_imagetype(), exif_read_data() and exif_thumbnail().
(PHP 4 >= 4.0.5, PHP 5)
image2wbmp -- Rende disponibile l'immagine per il browser o la salva in un fileimage2wbmp() crea un file WBMP dall'immagine specificata nel parametro image. L'argomento image è quello ritornato dalla funzione imagecreate().
L'argomento filename è opzionale, e può essere omesso. Puoi creare uno script PHP che ha direttamente un'immagine WBMP come output inviando image/vnd.wap.wbmp insieme alla funzione header().
Nota: Il supporto per WBMP è disponibile solo se PHP è compilato assieme a GD-1.8 o superiori.
Vedere anche 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. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: This function requires GD 2.0.1 or later.
Activate the fast drawing antialiased methods for lines and wired polygons. It does not support alpha components. It works using a direct blend operation. It works only with truecolor images.
Thickness and styled are not supported.
Using antialiased primitives with transparent background color can end with some unexpected results. The blend method uses the background color as any other colors. The lack of alpha component support does not allow an alpha based antialiasing method.
Nota: Questa funzione è disponibile soltanto se il PHP ` compilato con la libreria GD allegata.
See also imagecreatetruecolor().
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 clockwise.
Esempio 1. Drawing a circle with imagearc()
|
See also imageellipse(), imagefilledellipse(), and imagefilledarc().
imagechar() draws the first character of c in the image identified by image with its upper-left at x,y (top left is 0, 0) with the color color. If font is 1, 2, 3, 4 or 5, a built-in font is used (with higher numbers corresponding to larger fonts).
Esempio 1. imagechar() example
|
See also imagecharup() and 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 color. If font is 1, 2, 3, 4 or 5, a built-in font is used.
Esempio 1. imagecharup() example
|
See also imagechar() and imageloadfont().
imagecolorallocate() returns a color identifier representing the color composed of the given RGB components. The image argument is the return from the imagecreatetruecolor() 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 or hexadecimals between 0x00 and 0xFF. imagecolorallocate() must be called to create each color that is to be used in the image represented by image.
Nota: The first call to imagecolorallocate() fills the background color.
<?php $im = imagecreatetruecolor('example.jpg'); // sets background to red $background = imagecolorallocate($im, 255, 0, 0); // sets some colors $white = imagecolorallocate($im, 255, 255, 255); $black = imagecolorallocate($im, 0, 0, 0); // hexadecimal way $white = imagecolorallocate($im, 0xFF, 0xFF, 0xFF); $black = imagecolorallocate($im, 0x00, 0x00, 0x00); ?> |
Returns -1 if the allocation failed.
See also imagecolorallocatealpha() and imagecolordeallocate().
imagecolorallocatealpha() behaves identically to imagecolorallocate() with the addition of the transparency parameter alpha which may have a value between 0 and 127. 0 indicates completely opaque while 127 indicates completely transparent.
Returns FALSE if the allocation failed.
Esempio 1. Example of using imagecolorallocatealpha()
|
Nota: This function requires GD 2.0.1 or later.
See also imagecolorallocate() and imagecolordeallocate().
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.
If you created the image from a file, only colors used in the image are resolved. Colors present only in the pallete are not resolved.
See also imagecolorexact().
(PHP 4 >= 4.0.6, PHP 5)
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.
Nota: This function requires GD 2.0.1 or later.
See also imagecolorexactalpha().
(PHP 4 >= 4.0.1, PHP 5)
imagecolorclosesthwb -- Get the index of the color which has the hue, white and blackness nearest to the given color
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
The imagecolordeallocate() function de-allocates a color previously allocated with imagecolorallocate() or imagecolorallocatealpha().
See also imagecolorallocate() and imagecolorallocatealpha().
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.
If you created the image from a file, only colors used in the image are resolved. Colors present only in the pallete are not resolved.
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.
Nota: This function requires GD 2.0.1 or later.
See also imagecolorclosestalpha().
(PHP 4 >= 4.3.0, PHP 5)
imagecolormatch -- Makes the colors of the palette version of an image more closely match the true color versionAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
image1 must be Truecolor, image2 must be Palette, and both image1 and image2 must be the same size.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: Questa funzione è disponibile soltanto se il PHP ` compilato con la libreria GD allegata.
Nota: This function requires GD 2.0.1 or later.
See also imagecreatetruecolor().
(PHP 3 >= 3.0.2, PHP 4, PHP 5)
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.
If you created the image from a file, only colors used in the image are resolved. Colors present only in the pallete are not resolved.
See also imagecolorclosest().
(PHP 4 >= 4.0.6, PHP 5)
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.
Nota: This function requires GD 2.0.1 or later.
See also imagecolorclosestalpha().
This sets the specified index in the palette to the specified color. This is useful for creating flood-fill-like effects in palleted images without the overhead of performing the actual flood-fill.
See also imagecolorat().
This returns an associative array with red, green, blue and alpha keys that contain the appropriate values for the specified color index.
Esempio 1. imagecolorsforindex() example
This example will output :
|
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 imagecreatetruecolor() 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 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.
Nota: Transparency is copied only with imagecopymerge() and true color images, not with imagecopy() or pallete images.
(PHP 5 >= 5.1.0RC1)
imageconvolution -- Apply a 3x3 convolution matrix, using coefficient div and offsetRestituisce TRUE in caso di successo, FALSE in caso di fallimento.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Nota: Questa funzione è disponibile soltanto se il PHP ` compilato con la libreria GD allegata.
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() for pallete images, while it implements alpha transparency for true colour images.
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 preserves 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. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
dst_image is the destination image, src_image 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_image is the same as src_image) 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: This function requires GD 2.0.1 or later.
Esempio 1. Simple example This example will resample an image to half its original size.
|
Esempio 2. Resampling an image proportionally This example will display an image with the maximum width, or height, of 200 pixels.
|
imagecopyresized() copies a rectangular portion of one image to another image. dst_image is the destination image, src_image 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_image is the same as src_image) 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().
Esempio 1. Resizing an image This example will display the image at half size.
The image will be output at half size, though better quality could be obtained using imagecopyresampled(). |
imagecreate() returns an image identifier representing a blank image of size x_size by y_size.
We recommend the use of imagecreatetruecolor().
Esempio 1. Creating a new GD image stream and outputting an image.
|
See also imagedestroy() and imagecreatetruecolor().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Nota: This function requires GD 2.0.1 or later.
Suggerimento: È possibile utilizzare una URL come un nome di file con questa funzione se fopen wrappers è stata abilitata. Per maggiori informazioni su come specificare i nomi di file vedere fopen() e Appendice M per avere la lista dei protocolli URL supportati.
Avvertimento |
la versione per Windows di PHP antecedente la 4.3.0 non supporta l'accesso remoto ai file da parte di questa funzione, anche se allow_url_fopen è abilitato. |
(PHP 4 >= 4.1.0, PHP 5)
imagecreatefromgd2part -- Create a new image from a given part of GD2 file or URL
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Nota: This function requires GD 2.0.1 or later.
Suggerimento: È possibile utilizzare una URL come un nome di file con questa funzione se fopen wrappers è stata abilitata. Per maggiori informazioni su come specificare i nomi di file vedere fopen() e Appendice M per avere la lista dei protocolli URL supportati.
Avvertimento |
la versione per Windows di PHP antecedente la 4.3.0 non supporta l'accesso remoto ai file da parte di questa funzione, anche se allow_url_fopen è abilitato. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Suggerimento: È possibile utilizzare una URL come un nome di file con questa funzione se fopen wrappers è stata abilitata. Per maggiori informazioni su come specificare i nomi di file vedere fopen() e Appendice M per avere la lista dei protocolli URL supportati.
Avvertimento |
la versione per Windows di PHP antecedente la 4.3.0 non supporta l'accesso remoto ai file da parte di questa funzione, anche se allow_url_fopen è abilitato. |
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:
Esempio 1. Example to handle an error during creation
|
Nota: GIF support was removed from the GD library in Version 1.6, and added back in Version 2.0.28. This function is not available between these versions.
Suggerimento: È possibile utilizzare una URL come un nome di file con questa funzione se fopen wrappers è stata abilitata. Per maggiori informazioni su come specificare i nomi di file vedere fopen() e Appendice M per avere la lista dei protocolli URL supportati.
Avvertimento |
la versione per Windows di PHP antecedente la 4.3.0 non supporta l'accesso remoto ai file da parte di questa funzione, anche se allow_url_fopen è abilitato. |
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:
Esempio 1. Example to handle an error during creation
|
Nota: JPEG support is only available if PHP was compiled against GD-1.8 or later.
Suggerimento: È possibile utilizzare una URL come un nome di file con questa funzione se fopen wrappers è stata abilitata. Per maggiori informazioni su come specificare i nomi di file vedere fopen() e Appendice M per avere la lista dei protocolli URL supportati.
Avvertimento |
la versione per Windows di PHP antecedente la 4.3.0 non supporta l'accesso remoto ai file da parte di questa funzione, anche se allow_url_fopen è abilitato. |
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:
Esempio 1. Example to handle an error during creation
|
Suggerimento: È possibile utilizzare una URL come un nome di file con questa funzione se fopen wrappers è stata abilitata. Per maggiori informazioni su come specificare i nomi di file vedere fopen() e Appendice M per avere la lista dei protocolli URL supportati.
Avvertimento |
la versione per Windows di PHP antecedente la 4.3.0 non supporta l'accesso remoto ai file da parte di questa funzione, anche se allow_url_fopen è abilitato. |
(PHP 4 >= 4.0.4, PHP 5)
imagecreatefromstring -- Create a new image from the image stream in the stringimagecreatefromstring() returns an image identifier representing the image obtained from the given string. These types will be automatically detected if your build of PHP supports them: JPEG, PNG, GIF, WBMP, and GD2.
An image resource will be returned on success. FALSE is returned if the image type is unsupported, the data is not in a recognised format, or the image is corrupt and cannot be loaded.
Esempio 1. imagecreatefromstring() example
|
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:
Esempio 1. Example to handle an error during creation
|
Nota: WBMP support is only available if PHP was compiled against GD-1.8 or later.
Suggerimento: È possibile utilizzare una URL come un nome di file con questa funzione se fopen wrappers è stata abilitata. Per maggiori informazioni su come specificare i nomi di file vedere fopen() e Appendice M per avere la lista dei protocolli URL supportati.
Avvertimento |
la versione per Windows di PHP antecedente la 4.3.0 non supporta l'accesso remoto ai file da parte di questa funzione, anche se allow_url_fopen è abilitato. |
imagecreatefromxbm() returns an image identifier representing the image obtained from the given filename.
Suggerimento: È possibile utilizzare una URL come un nome di file con questa funzione se fopen wrappers è stata abilitata. Per maggiori informazioni su come specificare i nomi di file vedere fopen() e Appendice M per avere la lista dei protocolli URL supportati.
Avvertimento |
la versione per Windows di PHP antecedente la 4.3.0 non supporta l'accesso remoto ai file da parte di questa funzione, anche se allow_url_fopen è abilitato. |
imagecreatefromxpm() returns an image identifier representing the image obtained from the given filename.
Nota: Questa funzione è disponibile soltanto se il PHP ` compilato con la libreria GD allegata.
Suggerimento: È possibile utilizzare una URL come un nome di file con questa funzione se fopen wrappers è stata abilitata. Per maggiori informazioni su come specificare i nomi di file vedere fopen() e Appendice M per avere la lista dei protocolli URL supportati.
Avvertimento |
la versione per Windows di PHP antecedente la 4.3.0 non supporta l'accesso remoto ai file da parte di questa funzione, anche se allow_url_fopen è abilitato. |
imagecreatetruecolor() returns an image identifier representing a black image of size x_size by y_size.
Depending on your PHP and GD versions this function is defined or not. With PHP 4.0.6 through 4.1.x this function always exists if the GD module is loaded, but calling it without GD2 being installed PHP will issue a fatal error and exit. With PHP 4.2.x this behaviour is differnet in issueing a warning instead of an error. Other versions only define this function, if the correct GD version is installed.
Esempio 1. Creating a new GD image stream and outputting an image.
|
Nota: This function requires GD 2.0.1 or later.
Nota: This function will not work with GIF file formats.
See also imagedestroy() and imagecreate().
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 one of the image create functions, such as imagecreatetruecolor().
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/
Esempio 1. imageellipse() example
|
See also imagefilledellipse() and imagearc().
imagefill() performs a flood fill starting at coordinate x, y (top left is 0, 0) with color color in the image image.
imagefilledarc() draws a partial ellipse centered at cx, cy (top left is 0, 0) in the image represented by image. Restituisce TRUE in caso di successo, FALSE in caso di fallimento. 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
Esempio 1. Creating a 3D looking pie
|
Nota: This function requires GD 2.0.1 or later.
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. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Esempio 1. imagefilledellipse() example
|
Nota: This function requires GD 2.0.1 or later.
See also imageellipse() and imagefilledarc().
imagefilledpolygon() creates a filled polygon in image image.
points is an array containing the x and y co-ordinates of the polygons vertices consecutively.
The parameter num_points is the total number of vertices, which must be larger than 3.
Esempio 1. imagefilledpolygon() example
|
imagefilledrectangle() creates a filled rectangle of color color 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 color.
imagefilter() applies the filter filtertype to the image, using arg1, arg2 and arg3 where necessary.
filtertype can be one of the following:
IMG_FILTER_NEGATE: Reverses all colors of the image.
IMG_FILTER_GRAYSCALE: Converts the image into grayscale.
IMG_FILTER_BRIGHTNESS: Changes the brightness of the image. Use arg1 to set the level of brightness.
IMG_FILTER_CONTRAST: Changes the contrast of the image. Use arg1 to set the level of contrast.
IMG_FILTER_COLORIZE: Like IMG_FILTER_GRAYSCALE, except you can specify the color. Use arg1, arg2 and arg3 in the form of red, blue, green. The range for each color is 0 to 255.
IMG_FILTER_EDGEDETECT: Uses edge detection to highlight the edges in the image.
IMG_FILTER_EMBOSS: Embosses the image.
IMG_FILTER_GAUSSIAN_BLUR: Blurs the image using the Gaussian method.
IMG_FILTER_SELECTIVE_BLUR: Blurs the image.
IMG_FILTER_MEAN_REMOVAL: Uses mean removal to achieve a "sketchy" effect.
IMG_FILTER_SMOOTH: Makes the image smoother. Use arg1 to set the level of smoothness.
Nota: Questa funzione è disponibile soltanto se il PHP ` compilato con la libreria GD allegata.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Esempio 3. imagefilter() colorize example
|
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().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Nota: This function requires GD 2.0.1 or later.
Nota: Parameter extrainfo is optional since PHP 4.3.5.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Nota: This function requires GD 2.0.1 or later.
Nota: Parameter extrainfo is optional since PHP 4.3.5.
The imagegammacorrect() function applies gamma correction to a gd image stream (image) given an input gamma, the parameter inputgamma and an output gamma, the parameter outputgamma.
imagegd2() outputs a GD2 image to filename. The image parameter is the return from the imagecreatetruecolor() function.
The filename parameter is optional, and if left off, the raw image stream will be output directly.
The optional type parameter is either IMG_GD2_RAW or IMG_GD2_COMPRESSED. Default is IMG_GD2_RAW.
Nota: The optional chunk_size and type parameters became available in PHP 4.3.2.
Nota: The GD2 format is commonly used to allow fast loading of parts of images. Note that the GD2 format is only usable in GD2-compatible applications.
Nota: This function requires GD 2.0.1 or later.
See also imagegd()
imagegd() outputs a GD image to filename. The image argument is the return from the imagecreatetruecolor() function.
The filename parameter is optional, and if left off, the raw image stream will be output directly.
Nota: The GD format is commonly used to allow fast loading of parts of images. Note that the GD format is only usable in GD-compatible applications.
See also imagegd2().
imagegif() creates the GIF file in filename from the image image. The image argument is the return from the imagecreatetruecolor() 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. Support is expected to return in a version subsequent to the rerelease of GIF support in the GD library in mid 2004. For more information, see the GD Project site.
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() and 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.
imageistruecolor() finds whether the image image is a truecolor image.
Nota: This function requires GD 2.0.1 or later.
See also imagecreatetruecolor().
imagejpeg() creates the JPEG file in filename from the image image. The image argument is the return from the imagecreatetruecolor() 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().
(PHP 4 >= 4.3.0, PHP 5)
imagelayereffect -- Set the alpha blending flag to use the bundled libgd layering effectsAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Nota: Questa funzione è disponibile soltanto se il PHP ` compilato con la libreria GD allegata.
Nota: This function requires GD 2.0.1 or later.
imageline() draws a line from x1, y1 to x2, y2 (top left is 0, 0) in image image of color color.
Esempio 1. Drawing a thick line
|
See also imagecreatetruecolor() 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). It returns FALSE in case of error.
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.
Tabella 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. |
Esempio 1. Using imageloadfont
|
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, i.e. points[0] = x0, points[1] = y0, points[2] = x1, points[3] = y1, etc. num_points is the total number of points (vertices).
Esempio 1. imagepolygon() example
|
See also imagecreate() and imagecreatetruecolor().
(PHP 3 >= 3.0.9, PHP 4, PHP 5)
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.
Nota: Questa funzione è disponibile soltanto se il PHP ` compilato utilizzando --with-t1lib.
This function returns an array containing the following elements:
See also imagepstext().
(PHP 3 >= 3.0.9, PHP 4, PHP 5)
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 its 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.
Nota: Questa funzione è disponibile soltanto se il PHP ` compilato utilizzando --with-t1lib.
See also imagepsloadfont().
Loads a character encoding vector 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.
Nota: Questa funzione è disponibile soltanto se il PHP ` compilato utilizzando --with-t1lib.
Extend or condense a font (font_index), if the value of the extend parameter is less than one you will be condensing the font.
Nota: Questa funzione è disponibile soltanto se il PHP ` compilato utilizzando --with-t1lib.
imagepsfreefont() frees memory used by a PostScript Type 1 font.
Nota: Questa funzione è disponibile soltanto se il PHP ` compilato utilizzando --with-t1lib.
See also imagepsloadfont().
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.
Esempio 1. imagepsloadfont() example
|
Nota: Questa funzione è disponibile soltanto se il PHP ` compilato utilizzando --with-t1lib.
See also imagepsfreefont().
Slant a font given by the font_index parameter with a slant of the value of the slant parameter.
Nota: Questa funzione è disponibile soltanto se il PHP ` compilato utilizzando --with-t1lib.
(PHP 3 >= 3.0.9, PHP 4, PHP 5)
imagepstext -- To draw a text string over an image using PostScript Type1 fontsforeground 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 PostScript 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.
size is expressed in pixels.
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_steps are optional.
Nota: Questa funzione è disponibile soltanto se il PHP ` compilato utilizzando --with-t1lib.
This function returns an array containing the following elements:
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 degrees. bgd_color specifies the color of the uncovered zone after the rotation.
The center of rotation is the center of the image, and the rotated image is scaled down so that the whole rotated image fits in the destination image - the edges are not clipped.
If ignore_transparent is set and non-zero, transparent colors are ignored (otherwise kept). This parameter was added in PHP 5.1.
Esempio 1. Rotate an image 180 degrees This example rotates an image 180 degrees - upside down.
|
Nota: Questa funzione è disponibile soltanto se il PHP ` compilato con la libreria GD allegata.
(PHP 4 >= 4.3.2, PHP 5)
imagesavealpha -- Set the flag to save full alpha channel information (as opposed to single-color transparency) when saving PNG imagesimagesavealpha() sets the flag to attempt to save full alpha channel information (as opposed to single-color transparency) when saving PNG images.
You have to unset alphablending (imagealphablending($im, FALSE)), to use it.
Alpha channel is not supported by all browsers, if you have problem with your browser, try to load your script with an alpha channel compliant browser, e.g. latest Mozilla.
Nota: This function requires GD 2.0.1 or later.
See also imagealphablending().
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 color.
See also imagecreatetruecolor() 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. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
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:
Esempio 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. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: This function 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!
imagestring() draws the string s in the image identified by image with the upper-left corner 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.
Esempio 1. imagestring() example
|
See also imageloadfont(), and imagettftext().
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 imagecreatetruecolor(), getimagesize() and imagesy().
imagesy() returns the height of the image identified by image.
See also imagecreatetruecolor(), getimagesize() 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 requires GD 2.0.1 or later.
This function calculates and returns the bounding box in pixels for a TrueType text.
The font size in pixels.
Angle in degrees in which text will be measured.
The name of the TrueType font file (can be a 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.
The string to 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().
The image resource. See imagecreatetruecolor().
The font size. Depending on your version of GD, this should be specified as the pixel size (GD1) or point size (GD2).
The angle in degrees, with 0 degrees being left-to-right reading text. Higher values represent a counter-clockwise rotation. For example, a value of 90 would result in bottom-to-top reading text.
The coordinates given by x and 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 and y define the upper-left corner of the first character. For example, "top left" is 0, 0.
The y-ordinate. This sets the position of the fonts baseline, not the very bottom of the character.
The color index. Using the negative of a color index has the effect of turning off antialiasing. See imagecolorallocate().
The path to the TrueType font you wish to use.
Depending on which version of the GD library PHP is using, when fontfile does not begin with a leading / then .ttf will be appended to the filename and the library will attempt to search for that filename along a library-defined font path.
When using versions of the GD library lower than 2.0.18, a space character, rather than a semicolon, was used as the 'path separator' for different font files. Unintentional use of this feature will result in the warning message: Warning: Could not find/open font. For these affected versions, the only solution is moving the font to a path which does not contain spaces.
In many cases where a font resides in the same directory as the script using it the following trick will alleviate any include problems.
<?php // Set the enviroment variable for GD putenv('GDFONTPATH=' . realpath('.')); // Name the font to be used (note the lack of the .ttf extension) $font = 'SomeFont'; ?> |
The text string.
May include decimal numeric character references (of the form: €) to access characters in a font beyond position 127. Strings in UTF-8 encoding can be passed directly.
If a character is used in the string which is not supported by the font, a hollow rectangle will replace the character.
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 horizontally.
Esempio 1. imagettftext() example This example script will produce a white PNG 400x30 pixels, with the words "Testing..." in black (with grey shadow), in the font Arial.
|
This function requires both the GD library and the FreeType library.
See also imagettfbbox().
(PHP 3 CVS only, PHP 4 >= 4.0.2, PHP 5)
imagetypes -- Return the image types supported by this PHP buildThis 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 | IMG_XPM. 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 imagecreatetruecolor() 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().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Nota: Questa funzione è disponibile soltanto se il PHP ` compilato con la libreria GD allegata.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 3 >= 3.0.6, PHP 4, PHP 5)
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: JPEG support is only available if PHP was compiled against GD-1.8 or later.
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().
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.
Nota: In Mandrake Linux, the IMAP library (libc-client.a) is compiled without Kerberos support. A separate version with SSL (client-PHP4.a) is installed. The library must be recompiled in order to add Kerberos support.
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. Windows users may include the php_imap.dll DLL in php.ini. IMAP is not supported on systems earlier that Windows 2000. This is because it uses encryption functions in order to enable SSL connections to the mail servers.
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.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Open mailbox read-only
Don't use or update a .newsrc for news (NNTP only)
For IMAP and NNTP names, open a connection but don't open a mailbox.
silently expunge the mailbox before closing when calling imap_close()
The parameter is a UID
Do not set the \Seen flag if not already set
The return string is in internal format, will not canonicalize to CRLF.
The sequence argument contains UIDs instead of sequence numbers
the sequence numbers contain UIDS
Delete the messages from the current mailbox after copying with imap_mail_copy()
Return UIDs instead of sequence numbers
Don't prefetch searched messages
This mailbox has no "children" (there are no mailboxes below this one).
This is only a container, not a mailbox - you cannot open it.
This mailbox is marked. Only used by UW-IMAPD.
This mailbox is not marked. Only used by UW-IMAPD.
Sort criteria for imap_sort(): message Date
Sort criteria for imap_sort(): arrival date
Sort criteria for imap_sort(): mailbox in first From address
Sort criteria for imap_sort(): message subject
Sort criteria for imap_sort(): mailbox in first To address
Sort criteria for imap_sort(): mailbox in first cc address
Sort criteria for imap_sort(): size of message in octets
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, PHP 5)
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.
imap_append() appends a string message to the specified mailbox mbox. If the optional options is specified, writes the options to that mailbox also.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
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.
Esempio 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(), base64_encode() and base64_decode().
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 options are a bit mask 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, 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, PHP 5)
imap_bodystruct -- Read the structure of a specified body section of a specific message
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
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 - current system time formatted according to RFC822
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
Esempio 1. imap_check() example
this will output :
|
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). Restituisce TRUE in caso di successo, FALSE in caso di fallimento..
options are a bit mask and may contain the single option:
ST_UID - The sequence argument contains UIDs instead of sequence numbers
See also: imap_setflag_full().
Closes the imap stream. Takes an optional flag CL_EXPUNGE, which will silently expunge the mailbox before closing, removing all messages marked for deletion.
See also: imap_open().
imap_createmailbox() creates a new mailbox specified by mbox. Names containing international characters should be encoded by imap_utf7_encode()
Restituisce TRUE in caso di successo, FALSE in caso di fallimento..
Esempio 1. imap_createmailbox() example
|
See also imap_renamemailbox(), imap_deletemailbox() and imap_open() for the format of mbox names.
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.
Esempio 1. imap_delete() example
|
See also: imap_undelete(), imap_expunge(), and imap_close().
imap_deletemailbox() deletes the specified mailbox (see imap_open() for the format of mbox names).
Restituisce TRUE in caso di successo, FALSE in caso di fallimento..
See also imap_createmailbox(), imap_renamemailbox(), and imap_open() for the format of mbox.
(PHP 3 >= 3.0.12, PHP 4, PHP 5)
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 resetThis 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.
See also: imap_last_error().
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, PHP 5)
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
to - recipient
date - when was it sent
message_id - Message-ID
references - is a reference to this message id
in_reply_to - is a reply to this message id
size - size in bytes
uid - UID the message has in the mailbox
msgno - message sequence number in the mailbox
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
Esempio 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, will not canonicalize to 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 options 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 attachment. The structure of the returned objects is as follows:
Tabella 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. |
See also: imap_fetchbody().
(PHP 4 >= 4.0.5, PHP 5)
imap_get_quota -- Retrieve the quota level settings, and usage statics per mailboxReturns 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.
Esempio 1. imap_get_quota() example
|
As of PHP 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 original access methods are still available for use, although it is suggested to update.
Esempio 2. imap_get_quota() 4.3 or greater example
|
See also imap_open(), imap_set_quota() and 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).
Esempio 1. imap_get_quotaroot() example
|
See also imap_open(), imap_set_quota() and imap_get_quota().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
This function is currently only available to users of the c-client2000 or greater library.
See also imap_setacl().
(PHP 3 >= 3.0.12, PHP 4, PHP 5)
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.
Esempio 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 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, PHP 5)
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.
See also: imap_errors().
Returns an array containing the names of the mailboxes. See imap_getmailboxes() for a description of ref and pattern.
Esempio 1. imap_list() example
|
See also: imap_getmailboxes().
(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.
Returns an array of all the mailboxes that you have subscribed.
(PHP 3 >= 3.0.5, PHP 4, PHP 5)
imap_mail_compose -- Create a MIME message based on given envelope and body sections
Esempio 1. imap_mail_compose() example
|
Copies mail messages specified by msglist to specified mailbox. Restituisce TRUE in caso di successo, FALSE in caso di fallimento..
msglist is a range not just message numbers (as described in RFC2060).
options 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
See also imap_mail_move().
Moves mail messages specified by msglist to specified mailbox mbox. Restituisce TRUE in caso di successo, FALSE in caso di fallimento..
msglist is a range not just message numbers (as described in RFC2060).
options is a bitmask and may contain the single option:
CP_UID - the sequence numbers contain UIDS
See also imap_mail_copy().
This function allows sending of emails with correct handling of Cc and Bcc receivers. Restituisce TRUE in caso di successo, FALSE in caso di fallimento..
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.
Tabella 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 |
Esempio 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" and "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, PHP 5)
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().
See also 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().
All names which start with { are remote names, and are in the form "{" remote_system_name [":" port] [flags] "}" [mailbox_name] where:
remote_system_name - Internet domain name or bracketed IP address of server.
port - optional TCP port number, default is the default port for that service
flags - optional flags, see following table.
mailbox_name - remote mailbox name, default is INBOX
Tabella 1. Optional flags for names
Flag | Description |
---|---|
/service=service | mailbox access service, default is "imap" |
/user=user | remote user name for login on the server |
/authuser=user | remote authentication user; if specified this is the user name whose password is used (e.g. administrator) |
/anonymous | remote access as anonymous user |
/debug | record protocol telemetry in application's debug log |
/secure | do not transmit a plaintext password over the network |
/imap, /imap2, /imap2bis, /imap4, /imap4rev1 | equivalent to /service=imap |
/pop3 | equivalent to /service=pop3 |
/nntp | equivalent to /service=nntp |
/norsh | do not use rsh or ssh to establish a preauthenticated IMAP session |
/ssl | use the Secure Socket Layer to encrypt the session |
/validate-cert | validate certificates from TLS/SSL server (this is the default behavior) |
/novalidate-cert | do not validate certificates from TLS/SSL server, needed if server uses self-signed certificates |
/tls | force use of start-TLS to encrypt the session, and reject connection to servers that do not support it |
/notls | do not do start-TLS to encrypt the session, even with servers that support it |
/readonly | request read-only mailbox open (IMAP only; ignored on NNTP, and an error with SMTP and POP3) |
The options are a bit mask with one or more of the following:
OP_READONLY - Open mailbox read-only
OP_ANONYMOUS - Don't use or update a .newsrc for news (NNTP only)
OP_HALFOPEN - For IMAP and NNTP names, open a connection but don't open a mailbox.
CL_EXPUNGE - Expunge mailbox automatically upon mailbox close (see also imap_delete() and imap_expunge())
OP_DEBUG - Debug protocol negotiations
OP_SHORTCACHE - Short (elt-only) caching
OP_SILENT - Don't pass up events (internal use)
OP_PROTOTYPE - Return driver prototype
OP_EXPUNGE - Silently expunge recycle stream
OP_SECURE - Don't do non-secure authentication
Esempio 1. Different use of imap_open()
|
Esempio 2. imap_open() example
|
Returns TRUE if the stream is still alive, FALSE otherwise.
imap_ping() pings the stream to see if it's 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.
Convert a quoted-printable string to an 8 bit string (according to RFC2045, section 6.7).
See also imap_8bit().
This function renames on old mailbox to new mailbox (see imap_open() for the format of mbox names).
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
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 - Don't use or update a .newsrc for news (NNTP only)
OP_HALFOPEN - For IMAP and NNTP names, open a connection but don't open a mailbox.
CL_EXPUNGE - Expunge mailbox automatically upon mailbox close (see also imap_delete() and imap_expunge())
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
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
Esempio 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, PHP 5)
imap_rfc822_write_address -- Returns a properly formatted email address given the mailbox, host, and personal infoReturns a properly formatted email address as defined in RFC2822 given the mailbox, host, and personal info.
(PHP 3 >= 3.0.12, PHP 4, PHP 5)
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 (e.g. 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 incomplete 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.
Parameter charset was added in PHP 4.3.3.
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() and imap_get_quota().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
This function is currently only available to users of the c-client2000 or greater library.
See also imap_getacl().
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).
options are a bit mask and may contain the single option:
ST_UID - The sequence argument contains UIDs instead of sequence numbers
See also: imap_clearflag_full().
Returns an array of message numbers sorted by the given parameters.
Reverse is 1 for reverse-sorting.
Criteria can be one (and only one) of the following:
SORTDATE - message Date
SORTARRIVAL - arrival date
SORTFROM - mailbox in first From address
SORTSUBJECT - message subject
SORTTO - mailbox in first To address
SORTCC - mailbox in first cc address
SORTSIZE - size of message in octets
The flags are a bitmask of one or more of the following:
SE_UID - Return UIDs instead of sequence numbers
SE_NOPREFETCH - Don't prefetch searched messages
Parameter charset was added in PHP 4.3.3.
(PHP 3 >= 3.0.4, PHP 4, PHP 5)
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.
Esempio 1. imap_status() example
|
Subscribe to a new mailbox.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also: imap_unsubscribe().
imap_thread() returns an associative array containing a tree of messages threaded by REFERENCES, or FALSE on error.
Every message in the current mailbox will be represented by three entries in the resulting array:
$thread["XX.num"] - current message number
$thread["XX.next"]
$thread["XX.branch"]
Esempio 1. imap_thread() Example
|
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 3 >= 3.0.3, PHP 4, PHP 5)
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 a 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.
See also: imap_msgno().
This function removes the deletion flag for a specified message, which is set by imap_delete() or imap_mail_move().
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also: imap_delete(), and imap_mail_move().
Unsubscribe from a specified mailbox.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also: imap_subscribe().
Decodes modified UTF-7 text into ISO-8859-1 string.
Returns a string that is encoded in ISO-8859-1 and consists of the same sequence of characters in text, or FALSE if text contains invalid modified UTF-7 sequence or text contains a character that is not part of ISO-8859-1 character set.
This function is needed to decode mailbox names that contain certain characters which are not in range of printable ASCII characters.
The modified UTF-7 encoding is defined in RFC 2060, section 5.1.3 (original UTF-7 was defined in RFC1642).
See also: imap_utf7_encode().
(PHP 3 >= 3.0.15, PHP 4, PHP 5)
imap_utf7_encode -- Converts ISO-8859-1 string to modified UTF-7 textConverts data to modified UTF-7 text. Note that data is expected to be encoded in ISO-8859-1.
This is needed to encode mailbox names that contain certain characters which are not in range of printable ASCII characters.
The modified UTF-7 encoding is defined in RFC 2060, section 5.1.3 (original UTF-7 was defined in RFC1642).
See also: imap_utf7_decode().
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.
Il comportamento di queste funzioni è influenzato dalle impostazioni di 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.
Tabella 1. Informix configuration options
Name | Default | Changeable | Changelog |
---|---|---|---|
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 |
Breve descrizione dei parametri di configurazione.
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 modalità sicura.
The default user id to use when none is specified in ifx_connect() or ifx_pconnect(). Doesn't apply in modalità sicura.
The default password to use when none is specified in ifx_connect() or ifx_pconnect(). Doesn't apply in modalità sicura.
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.
Esempio 1. Informix affected rows
|
See also ifx_num_rows().
(PHP 3 >= 3.0.4, PHP 4, PHP 5)
ifx_blobinfile_mode -- Set the default blob mode for all select queriesSet 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.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
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" parameter 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.
Esempio 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. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Deletes the charobject for the given char object-id bid. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Releases resources for the query associated with result_id. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
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.
Esempio 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
Esempio 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 an 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).
Esempio 1. Show all rows of the "orders" table as a HTML table
|
Esempio 2. Insert some values into the "catalog" table
|
See also ifx_connect().
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. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Updates the content of the char object for the given char object bid. content is a string with new data. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Deletes the slob object on the given slob object-id bid. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
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. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
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.
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 committed or rolled back before opening another transaction (which is automatically done when sending the first query).
To compile PHP with Ingres support, you need the Open API library and header files included with Ingres II.
This PECL extension is not bundled with PHP. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: http://pecl.php.net/package/ingres.
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 environment 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.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. Ingres configuration options
Name | Default | Changeable | Changelog |
---|---|---|---|
ingres.allow_persistent | "1" | PHP_INI_SYSTEM | Available since PHP 4.0.2. |
ingres.max_persistent | "-1" | PHP_INI_SYSTEM | Available since PHP 4.0.2. |
ingres.max_links | "-1" | PHP_INI_SYSTEM | Available since PHP 4.0.2. |
ingres.default_database | NULL | PHP_INI_ALL | Available since PHP 4.0.2. |
ingres.default_user | NULL | PHP_INI_ALL | Available since PHP 4.0.2. |
ingres.default_password | NULL | PHP_INI_ALL | Available since PHP 4.0.2. |
ingres.report_db_warnings | "1" | PHP_INI_ALL | Available since version 1.1.0 of the PECL extension. |
ingres.cursor_mode | "0" | PHP_INI_ALL | Available since version 1.1.0 of the PECL extension. |
ingres.blob_segment_length | "4096" | PHP_INI_ALL | Available since version 1.2.0 of the PECL extension. |
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Columns are returned into the array having the fieldname as the array index.
Columns are returned into the array having a numerical index to the fields. This index starts with 1, the first field in the result.
Columns are returned into the array having both a numerical index and the fieldname as the array index.
Specifies the version of the Ingres Extension. Available since version 1.2.0 of the PECL extension.
Specifies the version of Ingres OpenAPI the extension was built against. Available since version 1.2.0 of the PECL extension.
Specifies that Ingres cursors should be opened in 'readonly' mode. Available since version 1.2.0 of the PECL extension.
Specifies that Ingres cursors should be opened 'for update'. Available since version 1.2.0 of the PECL extension.
Equivalent to the II_DATE_FORMAT setting of MULTINATIONAL. Available since version 1.2.0 of the PECL extension.
Equivalent to the II_DATE_FORMAT setting of MULTINATIONAL4. Available since version 1.2.0 of the PECL extension.
Equivalent to the II_DATE_FORMAT setting of FINNISH. Available since version 1.2.0 of the PECL extension.
Equivalent to the II_DATE_FORMAT setting of ISO. Available since version 1.2.0 of the PECL extension.
Equivalent to the II_DATE_FORMAT setting of ISO4. Available since version 1.2.0 of the PECL extension.
Equivalent to the II_DATE_FORMAT setting of GERMAN. Available since version 1.2.0 of the PECL extension.
Equivalent to the II_DATE_FORMAT setting of MDY. Available since version 1.2.0 of the PECL extension.
Equivalent to the II_DATE_FORMAT setting of DMY. Available since version 1.2.0 of the PECL extension.
Equivalent to the II_DATE_FORMAT setting of YMD. Available since version 1.2.0 of the PECL extension.
Speifies the currency character should be placed a the start of a money value. Equivalent to setting II_MONEY_FORMAT to 'L:'. Available since version 1.2.0 of the PECL extension.
Speifies the currency character should be placed a the end of a money value. Equivalent to setting II_MONEY_FORMAT to 'T:'. Available since version 1.2.0 of the PECL extension.
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 automatically committed by the server, as if ingres_commit() was called after every call to ingres_query().
See also ingres_query(), ingres_rollback(), and ingres_commit().
Returns TRUE on success, or FALSE on failure.
ingres_close() closes the connection to the Ingres server that's associated with the specified link. If the link parameter isn't specified, the last opened link is used.
ingres_close() isn't usually necessary, as it won't close persistent connections and all non-persistent connections are automatically closed at the end of the script.
See also ingres_connect() and ingres_pconnect().
ingres_commit() 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 automatically after every query by calling ingres_autocommit() before opening the transaction.
See also ingres_query(), ingres_rollback(), and ingres_autocommit().
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().
Returns an string containing the active cursor name. If no cursor is active then NULL is returned.
If a link resource is passed to ingres_cursor() it returns the cursor name recorded for the link. If no link is passed then ingres_cursor() returns the cursor name asssociated with the default link.
See also ingres_prepare() and ingres_execute().
Returns an integer containing the last error number. If no error was reported 0 is returned.
If a link resource is passed to ingres_errno() it returns the last error recorded for the link. If no link is passed then ingres_errno() returns the last error reported using the default link.
The function, ingres_errno(), should always be called after executing a database query. Calling another function before ingres_errno() is called, will reset or change any error code from the last Ingres function call.
Esempio 1. ingres_error() example
|
See also ingres_error() and ingres_errsqlstate().
Returns a string containing the last error, or NULL if no error has occurred.
If a link resource is passed to ingres_error() it returns the last error recorded for the link. If no link is passed then ingres_error() returns the last error reported using the default link.
The function, ingres_error(), should always be called after executing any database query. Calling another function before ingres_error() is called will reset or change any error message from the last Ingres function call.
See also ingres_errno() and ingres_errsqlstate().
Returns a string containing the last SQLSTATE, or NULL if no error has occurred.
If a link resource is passed to ingres_errsqlstate() it returns the last error recorded for the link. If no link is passed then ingres_errsqlstate() returns the last error reported using the default link.
The function, ingres_errsqlstate(), should always be called after executing any database query. Calling another function before ingres_errsqlstate() is called will reset or change any error message from the last Ingres function call.
See also ingres_errno() and ingres_errsqlstate().
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.
<?php 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().
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().
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().
ingres_field_length() returns the length of a field. This is the number of bytes used by the server to store the field. For detailed information, see the Ingres/OpenAPI User Guide - Appendix C.
index is the number of the field and must be between 1 and the value given by ingres_num_fields().
See also ingres_query(), ingres_fetch_array(), ingres_fetch_object(), and ingres_fetch_row().
ingres_field_name() returns the name of a field in a query result, or FALSE on failure.
index is the number of the field and must be between 1 and the value given by ingres_num_fields().
See also ingres_query(), ingres_fetch_array(), ingres_fetch_object() and ingres_fetch_row().
ingres_field_nullable() returns TRUE if the field can be set to the NULL value and FALSE if it can't.
index is the number of the field and must be between 1 and the value given by ingres_num_fields().
See also ingres_query(), ingres_fetch_array(), ingres_fetch_object(), and ingres_fetch_row().
ingres_field_precision() returns the precision of a field. This value is used only for decimal, float and money SQL data types. For detailed information, see the Ingres/OpenAPI User Guide - Appendix C.
index is the number of the field and must be between 1 and the value given by ingres_num_fields().
See also ingres_query(), ingres_fetch_array(), ingres_fetch_object(), and ingres_fetch_row().
ingres_field_scale() returns the scale of a field. This value is used only for the decimal SQL data type. For detailed information, see the Ingres/OpenAPI User Guide - Appendix C.
index is the number of the field and must be between 1 and the value given by ingres_num_fields().
See also ingres_query(), ingres_fetch_array(), ingres_fetch_object(), and ingres_fetch_row().
ingres_field_type() 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().
(PHP 4 >= 4.0.2, PHP 5 <= 5.0.4)
ingres_num_fields -- Get the number of fields returned by the last queryingres_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().
(PHP 4 >= 4.0.2, PHP 5 <= 5.0.4)
ingres_num_rows -- Get the number of rows affected or returned by the last queryFor 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().
(PHP 4 >= 4.0.2, PHP 5 <= 5.0.4)
ingres_pconnect -- Open a persistent connection to an Ingres II databaseReturns 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().
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 immediately committed.
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().
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 v4, IRCG runs under these platforms:
AIX
FreeBSD
HP-UX
Irix
Linux
Solaris
Tru64
Windows
Nota: Questo modulo è stato spostato nel repository PECL e non sarà più rilascio con il PHP dalla versione 5.1.0.
Detailed installation instructions can be found at http://www.schumann.cx/ircg/. We urge you to use the provided installation script.
It is not recommended, but you can try enable IRCG support yourself. Provide the path to the ircg-config script, --with-ircg-config=path/to/irc-config and in addition add --with-ircg to your configure line.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
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().
(PHP 4 >= 4.3.0, PHP 5 <= 5.0.4)
ircg_eval_ecmascript_params -- Decodes a list of JS-encoded parametersAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
From the ircg_eval_ecmascript_params source file: /* * State 0: Looking for ' or digit * State 1: Assembling parameter inside '..' * State 2: After escape sign: Copies single char verbatim, go to 1 * State 3: Assembling numeric para, no quotation * State 4: Looking for ",", skipping whitespace */ |
See also ircg_lookup_format_messages().
(PHP 4 >= 4.1.0, PHP 5 <= 5.0.4)
ircg_fetch_error_msg -- Returns the error from previous IRCG operationircg_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_invite() will send an invitation to the user nickname, prompting him to join channel. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
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.
ircg_list() will request a list of users in the channel. The answer is sent to the output defined by ircg_set_file() or ircg_set_current(). Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Esempio 1. ircg_list() example
This example will output something similar to:
|
See also: ircg_set_file(), ircg_set_current(), and ircg_who().
(PHP 4 >= 4.0.5, PHP 5 <= 5.0.4)
ircg_lookup_format_messages -- Check for the existence of a format message setCheck 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_lusers() will request a statistical breakdown of users on the network connected to on connection. The answer is sent to the output defined by ircg_set_file() or ircg_set_current(). Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also: ircg_set_file(), and ircg_set_current().
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.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
See also ircg_get_username() and ircg_lusers().
Change your nickname on the given connection to the one given in nick, if possible.
Will return TRUE on success and FALSE on failure.
(PHP 4 >= 4.0.6, PHP 5 <= 5.0.4)
ircg_nickname_escape -- Encode special characters in nickname to be IRC-compliantFunction ircg_nickname_escape() returns an encoded nickname specified by nick which 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.
ircg_oper() will authenticate the logged in user on connection as an IRC operator. name and password must match a registered IRC operator account. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
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.
ircg_who() will request a list of users whose nickname is matching mask on connected network connection. The optional parameter ops_only will shrink the list to server operators only.
The answer is sent to the output defined by ircg_set_file() or ircg_set_current(). Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also: ircg_set_file(), and ircg_set_current().
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.
Avvertimento |
Questo modulo è SPERIMENTALE. Ovvero, il comportamento di queste funzioni, i nomi di queste funzioni, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questo modulo è a vostro rischio. |
This PECL extension is not bundled with PHP.
In PHP 4 this PECL extensions source can be found in the ext/ directory within the PHP source or at the PECL link above. In order to use these functions you must compile PHP with Java support by using the --with-java[=DIR] where DIR points to the base install directory of your JDK. This extension can only be built as a shared extension. Additional build extensions can be found in php-src/ext/java/README.
Windows users will enable php_java.dll inside of php.ini in order to use these functions. In PHP 4 this DLL resides in the extensions/ directory within the PHP Windows binaries download. You may download this PECL extension DLL from the PHP Downloads page or at http://snaps.php.net/.
Nota: In order to enable this module on a Windows environment with PHP <= 4.0.6, you must make jvm.dll available to your systems PATH. No additional DLL is needed for PHP versions > 4.0.6.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. Java configuration options
Name | Default | Changeable | Changelog |
---|---|---|---|
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 |
Esempio 1. Java Example
|
Esempio 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 coerced 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 advantage 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.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
See java_last_exception_get() for an example.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
The following example demonstrates the usage of Java's exception handler from within PHP:
Esempio 1. Java exception handler
|
These package allows you to access Kerberos V administration servers. You can create, modify, and delete Kerberos V principals and policies.
More information about Kerberos can be found at http://web.mit.edu/kerberos/www/.
Documentation for Kerberos and KADM5 can be found at http://web.mit.edu/kerberos/www/krb5-1.2/krb5-1.2.8/doc/admin_toc.html.
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
The functions kadm5_create_principal(), kadm5_modify_principal(), and kadm5_modify_principal() allow to specify special attributes using a bitfield. The symbols are defined below:
Tabella 1. Attributes for use by the KDC
constant |
---|
KRB5_KDB_DISALLOW_POSTDATED |
KRB5_KDB_DISALLOW_FORWARDABLE |
KRB5_KDB_DISALLOW_TGT_BASED |
KRB5_KDB_DISALLOW_RENEWABLE |
KRB5_KDB_DISALLOW_PROXIABLE |
KRB5_KDB_DISALLOW_DUP_SKEY |
KRB5_KDB_DISALLOW_ALL_TIX |
KRB5_KDB_REQUIRES_PRE_AUTH |
KRB5_KDB_REQUIRES_HW_AUTH |
KRB5_KDB_REQUIRES_PWCHANGE |
KRB5_KDB_DISALLOW_SVR |
KRB5_KDB_PWCHANGE_SERVER |
KRB5_KDB_SUPPORT_DESMD5 |
KRB5_KDB_NEW_PRINC |
The functions kadm5_create_principal(), kadm5_modify_principal(), and kadm5_get_principal() allow to specify or return principal's options as an associative array. The keys for the associative array are defined as string constants below:
Tabella 2. Options for creating/modifying/retrieving principals
constant | funcdef | description |
---|---|---|
KADM5_PRINCIPAL | long | The expire time of the princial as a Kerberos timestamp. |
KADM5_PRINC_EXPIRE_TIME | long | The expire time of the princial as a Kerberos timestamp. |
KADM5_LAST_PW_CHANGE | long | The time this principal's password was last changed. |
KADM5_PW_EXPIRATION | long | The expire time of the principal's current password, as a Kerberos timestamp. |
KADM5_MAX_LIFE | long | The maximum lifetime of any Kerberos ticket issued to this principal. |
KADM5_MAX_RLIFE | long | The maximum renewable lifetime of any Kerberos ticket issued to or for this principal. |
KADM5_MOD_NAME | string | The name of the Kerberos principal that most recently modified this principal. |
KADM5_MOD_TIME | long | The time this principal was last modified, as a Kerberos timestamp. |
KADM5_KVNO | long | The version of the principal's current key. |
KADM5_POLICY | string | The name of the policy controlling this principal. |
KADM5_CLEARPOLICY | long | Standard procedure is to assign the 'default' policy to new principals. KADM5_CLEARPOLICY suppresses this behaviour. |
KADM5_LAST_SUCCESS | long | The KDC time of the last successfull AS_REQ. |
KADM5_LAST_FAILED | long | The KDC time of the last failed AS_REQ. |
KADM5_FAIL_AUTH_COUNT | long | The number of consecutive failed AS_REQs. |
KADM5_RANDKEY | long | Generates a random password for the principal. The parameter password will be ignored. |
KADM5_ATTRIBUTES | long | A bitfield of attributes for use by the KDC. |
This simple example shows how to connect, query, print resulting principals and disconnect from a KADM5 database.
Esempio 1. KADM5 extension overview example
|
If you have comments, bugfixes, enhancements or want to help in developing this you can send me a mail at holger.burbach@gonicus.de. The project homepage can be found at http://oss.gonicus.de/project/?group_id=7.
kadm5_chpass_principal() sets the new password password for the principal.
kadm5_create_principal() creates a principal with the given password. If password is omitted or is NULL, a random key will be generated.
It is possible to specify several optional parameters within the array options. Allowed are the following options: KADM5_PRINC_EXPIRE_TIME, KADM5_PW_EXPIRATION, KADM5_ATTRIBUTES, KADM5_MAX_LIFE, KADM5_KVNO, KADM5_POLICY, KADM5_CLEARPOLICY, KADM5_MAX_RLIFE.
Esempio 1. Example of principal's creation
|
kadm5_delete_principal() remove the principal from the Kerberos database.
(PECL)
kadm5_flush -- Flush all changes to the Kerberos database, leaving the connection to the Kerberos admin server openkadm5_get_policies() returns an array containing the policies's names.
kadm5_get_principal() returns an associative array containing the following keys: KADM5_PRINCIPAL, KADM5_PRINC_EXPIRE_TIME, KADM5_PW_EXPIRATION, KADM5_ATTRIBUTES, KADM5_MAX_LIFE, KADM5_MOD_NAME, KADM5_MOD_TIME, KADM5_KVNO, KADM5_POLICY, KADM5_MAX_RLIFE, KADM5_LAST_SUCCESS, KADM5_LAST_FAILED, KADM5_FAIL_AUTH_COUNT.
Esempio 1. kadm5_get_principal() example
|
kadm5_get_principals() returns an array containing the principals's names.
(PECL)
kadm5_init_with_password -- Opens a connection to the KADM5 library and initializes any neccessary state informationkadm5_init_with_password() opens a connection with the KADM5 library using the principal and the given password to obtain initial credentials from the admin_server. The parameter realm defines the authentication domain for the connection.
Esempio 1. KADM5 initialization example
|
kadm5_modify_principal() modifies a principal according to the given options. Allowed are the following options: KADM5_PRINC_EXPIRE_TIME, KADM5_PW_EXPIRATION, KADM5_ATTRIBUTES, KADM5_MAX_LIFE, KADM5_KVNO, KADM5_POLICY, KADM5_CLEARPOLICY, KADM5_MAX_RLIFE, KADM5_FAIL_AUTH_COUNT.
Esempio 1. Example of modifying principal
|
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 OpenLDAP or Bind9.net in order 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. To enable SASL support, be sure --with-ldap-sasl[=DIR] is used, and that sasl.h exists on the system.
Note to Win32 Users: In order to enable this module on a Windows environment, you must copy several files from the DLL folder of the PHP/Win32 binary package to the SYSTEM folder of your windows machine. (Ex: C:\WINNT\SYSTEM32, or C:\WINDOWS\SYSTEM). For PHP <= 4.2.0 copy libsasl.dll, for PHP >= 4.3.0 copy libeay32.dll and ssleay32.dll to your SYSTEM folder.
In order to use Oracle LDAP libraries, proper Oracle environment has to be set.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Per maggiori dettagli sulle costanti PHP_INI_* vedere Appendice G.
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Retrieve information for all entries where the surname starts with "S" from a directory server, displaying an extract with name and email address.
Esempio 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"
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
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.
<?php $entree["attribut1"] = "value"; $entree["attribut2"][0] = "value1"; $entree["attribut2"][1] = "value2"; ?> |
Esempio 1. Complete example with authenticated bind
|
Nota: Questa funzione è binary-safe (gestisce correttamente i file binari)
Binds to the LDAP directory with specified RDN and password. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
ldap_bind() does a bind operation on the directory. bind_rdn and bind_password are optional. If not specified, anonymous bind is attempted.
Esempio 1. Using LDAP Bind
|
Esempio 2. Using LDAP Bind Anonymously
|
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.
Esempio 1. Complete example of password check
|
Avvertimento |
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. When OpenLDAP 2.x.x is used, ldap_connect() will always return a resource as it does not actually connect but just initializes the connecting parameters. The actual connect happens with the next calls to ldap_* funcs, usually with ldap_bind().
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.
See also ldap_bind().
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.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
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.
Esempio 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().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
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 |
Esempio 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-dimensional 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. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
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
Esempio 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.
Esempio 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.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
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.
Nota: Questa funzione è binary-safe (gestisce correttamente i file binari)
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
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.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
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.
Nota: Questa funzione è binary-safe (gestisce correttamente i file binari)
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
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().
Nota: Questa funzione è binary-safe (gestisce correttamente i file binari)
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()
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
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. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
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.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Requirement: ldap_sasl_bind() requires SASL support (sasl.h). Be sure --with-ldap-sasl is used when configuring PHP otherwise this function will be undefined.
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 an 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, e.g. 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 eighth 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 documentation (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.
Esempio 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. Restituisce TRUE in caso di successo, FALSE in caso di fallimento. 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.
Esempio 2. Set server controls
|
See also ldap_get_option().
(PHP 4 >= 4.2.0, PHP 5)
ldap_set_rebind_proc -- Set a callback function to do re-binds on referral chasing
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
These functions/constants are available since PHP 5.1.0 and if you have compiled one of the extensions based on libxml, like DOM, SimpleXML and XSLT.
code - the error's code
column - the column where the error occurred. Please note that this property isn't entirely implemented in libxml and therefore 0 is often returned.
file - the filename, or empty if the XML was loaded from a string
level - the severity of the error (one of the following constants: LIBXML_ERR_WARNING, LIBXML_ERR_ERROR or LIBXML_ERR_FATAL)
line - the line where the error occurred
message - the error message
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Activate small nodes allocation optimization. This may speed up your application without needing to change the code.
Nota: Only available in Libxml >= 2.6.21
Default DTD attributes
Load the external subset
Validate with the DTD
Remove blank nodes
Merge CDATA as text nodes
Expand empty tags (e.g. <br/> to <br></br>)
Nota: This option is currently just available in the DOMDocument->save() and DOMDocument->saveXML() functions.
Substitute entities
Suppress error reports
Disable network access when loading documents
Suppress warning reports
Drop the XML declaration when saving a document
Nota: Only available in Libxml >= 2.6.21
Remove redundant namespaces declarations
Implement XInclude substitution
A recoverable error
A fatal error
No errors
A simple warning
libxml version like 20605 or 20617
libxml version like 2.6.5 or 2.6.17
Returns an array with LibXMLError objects if there are any errors in the buffer, or an empty array otherwise.
Esempio 1. A libxml_get_errors() example This example demonstrates how to build a simple libxml error handler.
Il precedente esempio visualizzerà:
|
Returns a LibXMLError object if there is any error in the buffer, FALSE otherwise.
(PHP 5)
libxml_set_streams_context -- Set the streams context for the next libxml document load or writeSets the streams context for the next libxml document load or write.
The stream context resource (created with stream_context_create())
Esempio 1. A libxml_set_streams_context() example
|
(PHP 5 >= 5.1.0RC1)
libxml_use_internal_errors -- Disable libxml errors and allow user to fetch error information as neededlibxml_use_internal_errors() allows you to disable standard libxml errors and enable user error handling.
Esempio 1. A libxml_use_internal_errors() example This example demonstrates the basic usage of libxml errors and the value returned by this function.
Il precedente esempio visualizzerà:
|
Avvertimento |
Questo modulo è SPERIMENTALE. Ovvero, il comportamento di queste funzioni, i nomi di queste funzioni, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questo modulo è a vostro rischio. |
Nota: Questo modulo è stato spostato nel repository PECL e non sarà più rilascio con il PHP dalla versione 5.0.0. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: http://pecl.php.net/package/notes.
Avvertimento |
This extension is currently not supported, thus looking for a maintainer. |
(PHP 4 >= 4.0.5, PECL)
notes_body -- Open the message msg_number in the specified mailbox on the specified server (leave servAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.0.5, PECL)
notes_header_info -- Open the message msg_number in the specified mailbox on the specified server (leave servAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
LZF è un algoritmo di compressione molto veloce, ideale per risparmiare spazio con leggere perdite di velocità. L'algoritmo può essere ottimizzato per velocità o spazio al momento della compila.
This PECL extension is not bundled with PHP. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: http://pecl.php.net/package/lzf.
Per potere utilizzare queste funzioni occorre compilare il PHP con il supporto lzf utilizzando il parametro di configurazione --with-lzf[=DIR]. Occorre, inoltre, indicare --enable-lzf-better-compression per abilitare l'ottimizzazione per lo spazio piuttosto che per la velocità
Gli utenti di Windows devono abilitare php_lzf.dll dal php.ini per potere utilizzare queste funzioni. You may download this PECL extension DLL from the PHP Downloads page or at http://snaps.php.net/.
lzf_compress() comprime i dati presenti nel parametro arg.
Restituisce i dati compressi oppre FALSE se si verifica un errore.
Vedere anche lzf_decompress().
lzf_decompress() decomprime i dati dal parametro arg.
Restituisce id ati decompressi oppure FALSE se si verifica un errore.
Vedere anche lzf_compress().
La funzione mail() permette di inviare messaggi di posta elettronica.
Per avere disponibili le funzioni Mail, il PHP deve potere accedere all'eseguibile sendmail del sistema durante la compila. Qualora si utilizzi un'altro programma di posta, tipo qmail o postfix, occorre utlizzare il wrapper sendmail allegato al programma di posta. Il PHP cercherà sendmail in PATH e quindi in: /usr/bin:/usr/sbin:/usr/etc:/etc:/usr/ucblib:/usr/lib. Si consiglia vivamente di avere sendmail in PATH. Inoltre, l'utente che compila PHP deve avere i diritti di accesso all'eseguibile di sendmail.
Non è necessaria nessuna installazione per usare queste funzioni, esse fanno parte del core di PHP.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. Opzioni di configurazione Mail
Nome | Predefinito | Modificabile in |
---|---|---|
SMTP | "localhost" | PHP_INI_ALL |
smtp_port | "25" | PHP_INI_ALL |
sendmail_from | NULL | PHP_INI_ALL |
sendmail_path | DEFAULT_SENDMAIL_PATH | PHP_INI_SYSTEM |
Breve descrizione dei parametri di configurazione.
Usato solo sotto Windows: Nome DNS o indirizzo IP del server SMTP che PHP deve usare per spedire posta elettronica con la funzione mail().
Usato solo sotto Windows: Numero della porta del server specificato da SMTP al quale connettersi quando si inviano email usando mail(); il valore predefinito è 25. Disponibile solo a partire da PHP 4.3.0.
Quale campo "From:" devono avere i messaggi inviati da PHP sotto Windows.
Dove trovare il programma sendmail, solitamente /usr/sbin/sendmail oppure /usr/lib/sendmail. configure cerca di trovare il file e lo imposta di default, ma se non riesce a localizzarlo, lo si può impostare qui.
I sistemi che non usano sendmail devono impostare questa direttiva al wrapper che i rispettivi sistemi di posta offrono, se esistenti. Per esempio, gli utenti di Qmail possono normalmente impostarla a /var/qmail/bin/sendmail o /var/qmail/bin/qmail-inject.
qmail-inject non necessita di nessuna opzione al fine di processare correttamente la mail.
Questi parametri funzionano anche su Windows. Se si impostate smtp, smtp_port e sendmail_from saranno ignorate e verrà eseguito il comando indicato.
ezmlm_hash() calcola il valore hash che occorre quando si mantengono mailing list EZMLM in un database MySQL.
mail() invia automaticamente il messaggio specificato in messaggio al destinatario specificato in a. Destinatari multipli possono essere specificati mettendo una virgola tra ogni indirizzo in a. Email con allegati e tipi speciali di contenuto possono essere spedite usando questa funzione. Questo è possibile tramite la codifica MIME. Per maggiori informazioni, fare riferimento a un articolo Zend o alle Classi Mime del PEAR.
Le seguenti RFC possono essere di aiuto: RFC 1896, RFC 2045, RFC 2046, RFC 2047, RFC 2048 e RFC 2049.
mail() restituisce TRUE se la mail è stata accettata per la spedizione con successo, altrimenti restituisce FALSE.
Avvertimento |
L'implementazione Windows della funzione mail() differisce sotto molti aspetti dall'implementazione Unix. Primo, non usa una un programma in locale per comporre i messaggi, ma opera soltanto direttamente sui socket, il che significa che deve essere presente in ascolto un MTA su un socket di rete (che può essere su localhost o su una macchina remota). Secondo, gli header custom quali From:, Cc:, Bcc: e Date: non vengono interpretati subito dal MTA, ma ne viene fatto prima il parsing da parte di PHP. PHP < 4.3 supportava solo gli header Cc: (ed era case-sensitive). PHP >= 4.3 supporta tutti gli header e non è più case-sensitive. |
Se viene passata come parametro una quarta stringa, questa stringa viene inserita alla fine dell'intestazione (header). Ciò viene tipicamente usato per aggiungere intestazioni supplementari. Intestazioni multiple supplementari sono separate da un carattere di "a capo" (sia newline che carriage return).
Nota: È necessario usare \r\n per separare le intestazioni, alcuni mail transfer agent sotto Unix potrebbero funzionare anche solo con un singolo newline (\n).
Con il parametro parametri_addizionali è possibile impostare un parametro addizionale a linea di comando per il programma configurato per inviare mail usando sendmail_path. Per esempio si può impostare il corretto valore per envelope sender di sendmail con l'opzione -f di sendmail. Potrebbe essere necessario aggiungere l'utente che ha in esecuzione il server web alla configurazione di sendmail per prevenire l'aggiunta dell'intestazione 'X-Warning' quando si imposta envelope sender in questo modo.
Nota: Questo quinto parametro è stato aggiunto in PHP 4.0.5. A partire da PHP 4.2.3, questo parametro è disabilitato in modalità safe_mode, se si cerca di usarlo comunque, la funzione mail() darà un messaggio di errore e restituirà FALSE.
È possibile costruire messaggi complessi utilizzando la tecnica di concatenazione delle stringhe.
Esempio 4. Invio di mail complessa.
|
Nota: Assicurarsi di non avere nessun carattere di newline nei parametri a o oggetto, o la mail non verrà spedita correttamente.
Nota: Il parametro a non può essere un indirizzo nella forma "Qualcosa <qualcuno@example.com>". Il comando di mail non sarebbe in grado di effettuare correttamente il parsing mentre dialoga con il MTA (in particolare sotto Windows).
Vedere anche imap_mail().
Avvertimento |
Questo modulo è SPERIMENTALE. Ovvero, il comportamento di queste funzioni, i nomi di queste funzioni, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questo modulo è a vostro rischio. |
Questo modulo è stato spostato nel repository PECL e non sarà più rilascio con il PHP dalla versione 4.2.0.
This PECL extension is not bundled with PHP. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: http://pecl.php.net/package/mailparse.
In order to use these functions you must compile PHP with mailparse support by using the --enable-mailparse configure option.
Windows users will enable php_mailparse.dll inside of php.ini in order to use these functions. You may download this PECL extension DLL from the PHP Downloads page or at http://snaps.php.net/.
(4.1.0 - 4.1.2 only, PECL)
mailparse_determine_best_xfer_encoding -- Figures out the best way of encoding the content read from the file pointer fp, which must be seek-ableAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(4.1.0 - 4.1.2 only, PECL)
mailparse_msg_create -- Returns a handle that can be used to parse a messageAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(4.1.0 - 4.1.2 only, PECL)
mailparse_msg_extract_part_file -- Extracts/decodes a message section, decoding the transfer encodingAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
If callbackfunc is not specified, the contents will be sent to "stdout".
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(4.1.0 - 4.1.2 only, PECL)
mailparse_msg_get_part_data -- Returns an associative array of info about the messageAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(4.1.0 - 4.1.2 only, PECL)
mailparse_msg_get_part -- Returns a handle on a given section in a mimemessageAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(4.1.0 - 4.1.2 only, PECL)
mailparse_msg_get_structure -- Returns an array of mime section names in the supplied messageAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(4.1.0 - 4.1.2 only, PECL)
mailparse_msg_parse_file -- Parse file and return a resource representing the structureAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(4.1.0 - 4.1.2 only, PECL)
mailparse_rfc822_parse_addresses -- Parse addresses and returns a hash containing that dataAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(4.1.0 - 4.1.2 only, PECL)
mailparse_stream_encode -- Streams data from source file pointer, apply encoding and write to destfpAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Returns an array listing filename information.
Queste funzioni matematiche operano esclusivamente nel range dei tipi di dato integer e float del computer. (questo corrisponde attualmente ai tipi di dati long e double del C) Se si ha necessità di lavorare con numeri più grandi, fare riferimento alle funzioni matematiche a precisione arbitraria.
Vedere anche il manuale alle pagine operatori aritmetici.
Non è necessaria nessuna installazione per usare queste funzioni, esse fanno parte del core di PHP.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Le costanti qui elencate sono sempre disponibili in quanto parte del core di PHP.
Tabella 1. Costanti Matematiche
Costante | Valore | Descrizione |
---|---|---|
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 | sqrt(pi) [4.0.2] |
M_2_SQRTPI | 1.12837916709551257390 | 2/sqrt(pi) |
M_SQRT2 | 1.41421356237309504880 | sqrt(2) |
M_SQRT3 | 1.73205080756887729352 | sqrt(3) [4.0.2] |
M_SQRT1_2 | 0.70710678118654752440 | 1/sqrt(2) |
M_LNPI | 1.14472988584940017414 | log_e(pi) [4.0.2] |
M_EULER | 0.57721566490153286061 | Costante di Eulero [4.0.2] |
Restituisce il valore assoluto di un numero. Se l'argomento della funzione è di tipo float, il valore restituito è float, altrimenti restituisce un integer (perché float di solito ha un range di valori più grande di integer).
Restituisce l'arco coseno di arg in radianti. La funzione acos() è complementare alla funzione cos(), ovvero che a==cos(acos(a)) per ciascun valore di a nel range di acos().
Restituisce l'inverso del coseno iperbolico di arg, cioè il valore il cui coseno iperbolico vale arg.
Nota: Questa funzione non è implementata su piattaforme Windows
Restituisce l'arco seno di arg in radianti. La funzione asin() è complementare alla funzione sin(), ovvero che a==sin(asin(a)) per ciascun valore di a nel range di asin().
Restituisce l'inverso del seno iperbolico di arg, cioè il valore il cui seno iperbolico vale arg
Nota: Questa funzione non è implementata su piattaforme Windows
Questa funzione calcola l'arco tangente delle due variabili x e y. È simile al calcolo dell'arco tangente di y / x, eccetto per il fatto che viene tenuto in considearazione il segno di entrambi gli argomenti per determinare il quadrante del risultato.
La funzione restituisce il risultato in radianti, compreso fra -PI e PI (inclusi).
Restituisce l'arco tangente di arg in radianti. La funzione è complementare a tan(), ovvero a==tan(atan(a)) per ciascun valore di a nel range di atan()
Restituisce l'inverso della tangente iperbolica di arg, cioè il valore la cui tangente iperbolica vale arg.
Nota: Questa funzione non è implementata su piattaforme Windows
Restituisce una stringa contenente numero rappresentata in base base_di_arrivo. La base in cui numero è dato è specificata da base_di_partenza. Entrambe base_di_partenza e base_di_arrivo devono essere comprese fra 2 e 36, inclusi. Cifre in numeri con una base maggiore di 10 saranno rappresentati con le lettere a-z, con a significante 10, b significante 11 e z significante 35.
Avvertimento |
La funzione base_convert() può perdere di precisione con numeri molto grandi a causa delle proprietà dei tipi "double" o "float" utilizzati internamente. Fare riferimento alla sezione Floating point numbers del manuale per informazioni specifiche e per le limitazione. |
Restituisce il decimale equivalente al numero binario rappresentato dall'argomento stringa_binaria.
bindec() converte un binario in integer. Il più grande numero che può essere convertito è 31 volte la cifra 1 oppure 2147483647 espresso in formato decimale.
Vedere anche decbin(), octdec(), hexdec() e base_convert().
Restituisce il primo intero più grande di numero, se necessario. Il valore restituito da ceil() è ancora di tipo float, poiché la gamma di valori del tipo float è solitamente più grande di quella del tipo integer.
Restituisce il coseno di arg. Il parametro arg deve essere espresso in radianti.
Restituisce il coseno iperbolico di arg, definito come (exp(arg) + exp(-arg))/2.
Restituisce una stringa contenente una rappresentazione binaria di un dato argomento numero. Il più grande numero che può essere convertito è 4294967295 in decimale, risultante in una stringa composta da 32 volte la cifra 1.
Vedere anche bindec(), decoct(), dechex() e base_convert().
Restituisce una stringa contenente una rappresentazione esadecimale di un dato argomento numero. Il più grande numero che puù essere convertito è 2147483647 in decimale risultante in "7fffffff".
Vedere anche hexdec(), decbin(), decoct() e base_convert().
Restituisce una stringa contenente una rappresentazione in ottale di un dato argomento numero. Il più grande numero che può essere convertito è 2147483647 in decimale risultante in "17777777777". Vedere anche octdec().
Vedere anche octdec(), decbin(), dechex() e base_convert().
(PHP 3 >= 3.0.4, PHP 4, PHP 5)
deg2rad -- Converte il numero dato in gradi nell'equivalente espresso in radiantiQuesta funzione converte numero da gradi al valore equivalente espresso in radianti.
Vedere anche rad2deg().
Restituisce e elevato alla potenza di arg.
Nota: 'e' è la base del sistema dei logaritmi dei numeri naturali, e vale 2.718282.
(PHP 4 >= 4.1.0, PHP 5)
expm1 -- Restituisce exp(numero) - 1, computato in maniera tale da essere accurato anche se il valore del numero è vicino a zeroAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Nota: Questa funzione non è implementata su piattaforme Windows
Restituisce il primo intero più piccolo di numero, se necessario. Il valore restituito da floor() è ancora di tipo float, poiché la gamma di valori del tipo float è solitamente più grande di quella del tipo integer.
(PHP 4 >= 4.2.0, PHP 5)
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.
Restituisce il valore massimo che può essere restituito da una chiamata alla funzione rand().
Vedere anche rand(), srand() e mt_getrandmax().
Restituisce l'equivalente decimale di un numero esadecimale rappresentato dall'argomento stringa_esadecimale. hexdec() converte una stringa esadecimale in un numero decimale. Il più grande numero che può essere convertito è 7fffffff o 2147483647 espresso in decimale.
hexdec() ignora i caratteri non esadecimali che incontra.
Vedere anche dechex(), bindec(), octdec() e base_convert().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Restituisce TRUE se val è un numero finito valido all'interno del range dei float, come definito da PHP su questa piattaforma.
Vedere anche is_infinite() e is_nan().
Restituisce TRUE se val è infinito (positivo o negativo), come il risultato di log(0) o ogni altro valore troppo grande per essere contenuto nel range dei float di una determinata piattaforma.
Vedere anche is_finite() e is_nan().
Restituisce TRUE se val 'non è un numero', come il risultato di acos(1.01).
Vedere anche is_finite() e is_infinite().
lcg_value() restituisce uno pseudo numero casuale nell'intervallo (0, 1). La funzione combina due GC con periodo di 2^31 - 85 e 2^31 - 249. Il periodo di questa funzione è uguale al prodotto dei due primi.
Restituisce il logaritmo in base-10 di arg.
Vedere anche: log()
(PHP 4 >= 4.1.0, PHP 5)
log1p -- Restituisce log(1 + numero), computato in maniera tale da essere accurato anche se il valore del numero è vicino a zeroAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Nota: Questa funzione non è implementata su piattaforme Windows
Se si specifica il parametro opzionale base, la funzione log() restituisce logbase arg, altrimenti log() il logaritmo naturale di arg.
Nota: Il parametro base è disponibile dalla versione 4.3.0 di PHP.
Si può comunque calcolare il logaritmo in base b di un numero n, usando la formula matematica: logb(n) = log(n)/log(b), dove log è il logaritmo neperiano (o naturale).
Vedere anche exp().
max() restituisce il numericamente più grande dei valori dati come parametro.
Se il primo ed unico parametro è un array, max() restituisce il massimo dei valori di tale array. Se il primo parametro è un integer, string o double, si ha bisogno almeno di due parametri e max() restituisce il maggiore di tali valori. Si può confrontare un numero illimitato di valori.
Nota: Le stringhe non numeriche saranno considerate dal PHP come 0, ma verrà restituita la stringa se questa è il più alto valore numerico. Se vi sono più argomenti considerati come 0, la funzione max() restituirà il primo (il valore più a sinistra).
Esempio 1. Esempio di max()
|
min() restituisce il numericamente più piccolo dei valori dati come parametro.
Se il primo ed unico pareametro è un array, la funzione min() restituisce il valore più basso nell'array. Se il primo parametro è un intero, una stringa, o un float, occorrono almeno due parametri e min() restituisce il minore tra questi. Si può confrontare un numero illimitato di valori.
Nota: Le stringhe non numeriche saranno considerate dal PHP come 0, ma verrà restituita la stringa se questa è il più basso valore numerico. Se vi sono più argomenti considerati come 0, la funzione min() restituirà il primo (il valore più a sinistra).
Esempio 1. Esempio di uso di min()
|
Restituisce il massimo valore che può essere restituito da una chiamata alla funzione mt_rand().
Vedere anche mt_rand(), mt_srand() e getrandmax().
Molti generatori di numeri casuali di vecchie libc hanno caratteristiche dubbie o sconosciute e sono lenti. Di default, PHP usa il generatore di numeri casuali libc con la funzione rand(). La funzione mt_rand() è un sostituto per questa. Usa un generatore di numeri casuali con caratteristiche conosciute, il Mersenne Twister, il quale produce numeri casuali quattro volte più velocemente di libc.
Se invocata senza i parametri opzionali min, max, mt_rand() restituisce un valore pseudo-casuale compreso fra 0 e RAND_MAX. Se ad esempio si desidera un numero casuale compreso fra 5 e 15 (inclusi), usare mt_rand (5, 15).
Nota: Come in PHP 4.2.0, non vi è necessità di inizializzare il generatore di numeri casuali con srand() oppure con mt_srand() poichè viene eseguito in modo automatico.
Nota: Nelle versioni precedenti la 3.0.7 il significato di max era range. Per ottenere lo stesso risultato in queste vecchie versioni un breve esempio dovrebbe essere il seguente: mt_rand (5, 11), si otterrà un numero casuale compreso fra 5 e 15.
Vedere anche mt_srand(), mt_getrandmax() e rand().
Inizializza il generatore di numeri casuali con il parametro seme. A partire dalla versione 4.2.0 di PHP il parametro seme è diventato opzionale, e, per default, viene impostato ad un valore random.
Nota: Come in PHP 4.2.0, non vi è necessità di inizializzare il generatore di numeri casuali con srand() oppure con mt_srand() poichè viene eseguito in modo automatico.
Vedere anche mt_rand(), mt_getrandmax() e srand().
Restituisce l'equivalente decimale del numero ottale rappresentato dall'argomento stringa_ottale. OctDec converte una stringa ottale in un numero decimale. Il più grande numero che può essere convertito è 17777777777 o 2147483647 in decimale.
Vedere anche decoct(), bindec(), hexdec() e base_convert().
Restituisce una appossimazione di pi. Il valore restituito è un float e ha precisione secondo la direttiva precision del file php.ini, che ha come valore predefinito 14. Inoltre, si può usare la costante M_PI che permette di ottenere risultati identici all'uso di pi().
Restituisce base elevato alla potenza di esp. Se possibile, questa funzione restituisce un integer.
Se la potenza non può essere computata, viene generato un errore, e pow() restituirà FALSE. dalla versione 4.2.0 di PHP la funzione pow() non genera alcun warning.
Nota: Il PHP non può gestire valori negativi per bases.
Avvertimento |
Nel PHP 4.0.6 e precedenti, pow() restituiva sempre un float e non generava alcun errore. |
(PHP 3 >= 3.0.4, PHP 4, PHP 5)
rad2deg -- Converte un numero in radianti nell'equivalente numero in gradiQuesta funzione converte numero da radianti a gradi.
Vedere anche deg2rad().
Se chiamata senza i parametri opzionali min, max, rand() restituisce un valore pseudo casuale compreso fra 0 e RAND_MAX. Se ad esempio si desidera un numero casuale compreso fra 5 e 15 (inclusi) usare rand (5, 15).
Nota: Su alcune piattaforme (come Windows) RAND_MAX vale soltanto 32768. Se si desidera un range più ampio di 32768, indicare i parametri min e max, questo permette di avere range maggiori di RAND_MAX, oppure si valuti l'utilizzo di mt_rand()
Nota: Come in PHP 4.2.0, non vi è necessità di inizializzare il generatore di numeri casuali con srand() oppure con mt_srand() poichè viene eseguito in modo automatico.
Nota: Nelle versioni precedenti la 3.0.7 il significato di max era range. Per ottenere lo stesso risultato in queste vecchie versioni un breve esempio dovrebbe essere il seguente: rand (5, 11), si otterrà un numero casuale compreso fra 5 e 15.
Vedere anche: srand(), getrandmax() e mt_rand().
Restituisce il valore arrotondato di val con la precisione specificata (numero di cifre dopo il punto decimale). precisione può anche essere negativa o zero (predefinito).
Nota: Il PHP non maneggia correttamente stringhe quali "12,300.2" in maniera predefinita. Fare riferimento a conversione da stringhe.
Nota: Il parametro precisione è disponibile dal PHP 4.
Vedere anche: ceil(), floor() e number_format().
La funzione sin() restituisce il seno di arg. Il parametro arg viene espresso in radianti.
Restituisce il seno iperbolico di arg, definito come (exp(arg) - exp(-arg))/2.
Inizializza il generatore di numeri casuali con seme. A partire dalla versione 4.2.0 di PHP il parametro seme è opzionale, e per default viene impostato ad un valore casuale.
Nota: Come in PHP 4.2.0, non vi è necessità di inizializzare il generatore di numeri casuali con srand() oppure con mt_srand() poichè viene eseguito in modo automatico.
Vedere anche: rand(), getrandmax() e mt_srand().
La funzione tan() restituisce la tangente del parametro arg. Il parametro arg deve essere espresso in radianti.
The MaxDB PHP extension allows you to access the functionality provided by MaxDB 7.5.0 and above. More information about the MaxDB Database server can be found at http://www.mysql.com/products/maxdb/.
The MaxDB PHP extension is compatible to the MySQL mysqli extension. There are only minor differences in the behaviour of some functions due to the differences of the underlying database servers, MaxDB and MySQL.
The main differences to mysqli are in the following functions:
maxdb_character_set_name() - Returns only ascii or unicode. |
maxdb_get_client_info() - Returns a different version string. |
maxdb_get_client_version() - Returns a different version string. |
maxdb_get_host_info() - Returns localhost or hostname. |
maxdb_get_server_info() - Returns a different version string. |
maxdb_get_server_version() - Returns a different version string. |
maxdb_kill() - Only disconnects the session. |
maxdb_multi_query() - Can not handle multiple SQL statements. |
maxdb_next_result() - Function returns always false. |
maxdb_options() - Supports a different set of options. |
maxdb_report() - Supports a different report mode. |
maxdb_stat() - Returns a different system status string. |
maxdb_stmt_store_result() - Is not necessary for MaxDB. |
maxdb_store_result() - Is not necessary for MaxDB. |
Documentation for MaxDB can be found at http://dev.mysql.com/doc/maxdb/.
In order to have these functions available, you must compile PHP with MaxDB support. Additionally, you must have the MaxDB SQLDBC runtime library available to access the MaxDB server.
Documentation for MaxDB SQLDBC can be found at http://dev.mysql.com/doc/maxdb/.
Download the MaxDB SQLDBC package from http://dev.mysql.com/downloads/maxdb/clients.html.
By using the --with-maxdb[=DIR] configuration option you enable PHP to access MaxDB databases. [DIR] points to the directory that contains the installed MaxDB SQLDBC package.
Windows users will need to enable php_maxdb.dll inside of php.ini.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. MaxDB Configuration Options
Name | Default | Changeable | Changelog |
---|---|---|---|
maxdb.default_host | NULL | PHP_INI_ALL | |
maxdb.default_db | NULL | PHP_INI_ALL | |
maxdb.default_user | NULL | PHP_INI_ALL | |
maxdb.default_pw | NULL | PHP_INI_ALL | |
maxdb.long_readlen | "200" | PHP_INI_ALL |
Breve descrizione dei parametri di configurazione.
The default server host to use when connecting to the database server if no other host is specified.
The default server database to use when connecting if no other database is specified.
The default user name to use when connecting to the database server if no other name is specified.
The default password to use when connecting to the database server if no other password is specified.
The default maximum length of bytes that is transferred to the client if long data is retrieved from the MaxDB database server.
Represents a connection between PHP and a MaxDB database.
autocommit - turns on or off auto-commiting database modifications
change_user - changes the user of the specified database connection
character_set_name - returns the default character set for the database connection
close - closes a previously opened connection
commit - commits the current transaction
connect - opens a new connection to MaxDB database server
debug - performs debugging operations
dump_debug_info - dumps debug information
get_client_info - returns client version
get_host_info - returns type of connection used
get_server_info - returns version of the MaxDB server
get_server_version - returns version of the MaxDB server
init - initializes maxdb object
info - retrieves information about the most recently executed query
kill - asks the server to kill a MaxDB thread
multi_query - performs multiple queries
more_results - check if more results exist from currently executed multi-query
next_result - reads next result from currently executed multi-query
options - set options
ping - pings a server connection or reconnects if there is no connection
prepare - prepares a SQL query
query - performs a query
real_connect - attempts to open a connection to MaxDB database server
escape_string - escapes special characters in a string for use in a SQL statement, taking into account the current charset of the connection
rollback - rolls back the current transaction
select_db - selects the default database
ssl_set - sets ssl parameters
stat - gets the current system status
stmt_init- initializes a statement for use with maxdb_stmt_prepare
store_result - transfers a resultset from last query
use_result - transfers an unbuffered resultset from last query
thread-safe - returns whether thread safety is given or not
affected_rows - gets the number of affected rows in a previous MaxDB operation
client_info - returns the MaxDB client version as a string
client_version - returns the MaxDB client version as an integer
errno - returns the error code for the most recent function call
error - returns the error string for the most recent function call
field_count - returns the number of columns for the most recent query
host_info - returns a string representing the type of connection used
info - retrieves information about the most recently executed query
insert_id - returns the auto generated id used in the last query
protocol_version - returns the version of the MaxDB protocol used
sqlstate - returns a string containing the SQLSTATE error code for the last error
thread_id - returns the thread ID for the current connection
warning_count - returns the number of warnings generated during execution of the previous SQL statement
Represents a prepared statement.
bind_param - binds variables to a prepared statement
bind_result - binds variables to a prepared statement for result storage
close - closes a prepared statement
data-seek - seeks to an arbitrary row in a statement result set
execute - executes a prepared statement
fetch - fetches result from a prepared statement into bound variables
free_result - frees stored result memory for the given statement handle
result_metadata - retrieves a resultset from a prepared statement for metadata information
prepare - prepares a SQL query
send_long_data - sends data in chunks
close_long_data - end sending long data
reset - resets a prepared statement
store_result - buffers complete resultset from a prepared statement
affected_rows - returns affected rows from last statement execution
errno - returns errorcode for last statement function
errno - returns errormessage for last statement function
param_count - returns number of parameter for a given prepare statement
sqlstate - returns a string containing the SQLSTATE error code for the last statement function
Represents the result set obtained from a query against the database.
close - closes resultset
data_seek - moves internal result pointer
fetch_field - gets column information from a resultset
fetch_fields - gets information for all columns from a resulset
fetch_field_direct - gets column information for specified column
fetch_array - fetches a result row as an associative array, a numeric array, or both.
fetch_assoc - fetches a result row as an associative array
fetch_object - fetches a result row as an object
fetch_row - gets a result row as an enumerated array
close - frees result memory
field_seek - set result pointer to a specified field offset
current_field - returns offset of current fieldpointer
field_count - returns number of fields in resultset
lengths - returns an array of columnlengths
num_rows - returns number of rows in resultset
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
The following constants to use with maxdb_options() are defined. For further description of these constants see http://dev.mysql.com/doc/maxdb/.
Tabella 2. MaxDB PHP client constants
Constant | Description |
---|---|
MAXDB_COMPNAME | The component name used to initialise the SQLDBC runtime environment. |
MAXDB_APPLICATION | The application to be connected to the database. |
MAXDB_APPVERSION | The version of the application. |
MAXDB_SQLMODE | The SQL mode. |
MAXDB_UNICODE | TRUE, if the connection is an unicode (UCS2) client or FALSE, if not. |
MAXDB_TIMEOUT | The maximum allowed time of inactivity after which the connection to the database is closed by the system. |
MAXDB_ISOLATIONLEVEL | Specifies whether and how shared locks and exclusive locks are implicitly requested or released. |
MAXDB_PACKETCOUNT | The number of different request packets used for the connection. |
MAXDB_STATEMENTCACHESIZE | The number of prepared statements to be cached for the connection for re-use. |
MAXDB_CURSORPREFIX | The prefix to use for result tables that are automatically named. |
The function maxdb_fetch_array() uses a constant for the different types of result arrays. The following constants are defined:
Tabella 3. MaxDB fetch constants
Constant | Description |
---|---|
MAXDB_ASSOC | Columns are returned into the array having the fieldname as the array index. |
MAXDB_ASSOC_UPPER | Columns are returned into the array having the upper case fieldname as the array index. |
MAXDB_ASSOC_LOWER | Columns are returned into the array having the lower case fieldname as the array index. |
MAXDB_BOTH | Columns are returned into the array having both a numerical index and the fieldname as the array index. |
MAXDB_NUM | Columns are returned into the array having a numerical index to the fields. This index starts with 0, the first field in the result. |
All examples in the MaxDB PHP documentation use the HOTELDB demo database from MaxDB. More about this database can be found at http://dev.mysql.com/doc/maxdb/en/98/11b83fa6b33c17e10000000a114084/frameset.htm.
To use the examples in the MaxDB PHP documentation, you have to load the tutorial data into your database. Then you have to set maxdb.default_db in php.ini to the database that contains the tutorial data.
This simple example shows how to connect, execute a query, print resulting rows and disconnect from a MaxDB database.
Esempio 1. MaxDB extension overview example
|
The following example shows how to bind variables to a SELECT INTO statement.
Esempio 2. Example for use of SELECT INTO statements
|
The following example shows how to use MaxDB database procedures.
Esempio 3. Example fore using database procedures
|
(PECL)
maxdb_affected_rows(no version information, might be only in CVS)
maxdb->affected_rows -- Gets the number of affected rows in a previous MaxDB operationProcedural style:
int maxdb_affected_rows ( resource link )Object oriented style (property):
class maxdb {maxdb_affected_rows() returns the number of rows affected by the last INSERT, UPDATE, or DELETE query associated with the provided link parameter. If this number cannot be determined, this function will return -1.
Nota: For SELECT statements maxdb_affected_rows() works like maxdb_num_rows().
The maxdb_affected_rows() function only works with queries which modify a table. In order to return the number of rows from a SELECT query, use the maxdb_num_rows() function instead.
An integer greater than zero indicates the number of rows affected or retrieved. Zero indicates that no records where updated for an UPDATE statement, no rows matched the WHERE clause in the query or that no query has yet been executed. -1 indicates that the number of rows affected can not be determined.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Affected rows (INSERT): 15 Affected rows (UPDATE): 15 Affected rows (DELETE): 0 Affected rows (SELECT): 15 |
(PECL)
maxdb_autocommit(no version information, might be only in CVS)
maxdb->auto_commit -- Turns on or off auto-commiting database modificationsProcedural style:
bool maxdb_autocommit ( resource link, bool mode )Object oriented style (method)
class maxdb {maxdb_autocommit() is used to turn on or off auto-commit mode on queries for the database connection represented by the link resource.
This function is an alias of: maxdb_stmt_bind_param()
This function alias is deprecated and only exists for backwards compatibility reasons. It is recommended to not use this function as one day it may be removed from PHP.
This function is an alias of: maxdb_stmt_bind_result().
This function alias is deprecated and only exists for backwards compatibility reasons. It is recommended to not use this function as one day it may be removed from PHP.
(PECL)
maxdb_change_user(no version information, might be only in CVS)
maxdb->change_user -- Changes the user of the specified database connectionProcedural style:
bool maxdb_change_user ( resource link, string user, string password, string database )Object oriented style (method):
class maxdb {maxdb_change_user() is used to change the user of the specified database connection as given by the link parameter and to set the current database to that specified by the database parameter.
In order to successfully change users a valid username and password parameters must be provided and that user must have sufficient permissions to access the desired database. If for any reason authorization fails, the current user authentication will remain.
Nota: Using this command will always cause the current database connection to behave as if was a completely new database connection, regardless of if the operation was completed successfully. This reset includes performing a rollback on any active transactions, closing all temporary tables, and unlocking all locked tables.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Result: a Database running |
(PECL)
maxdb_character_set_name(no version information, might be only in CVS)
maxdb->character_set_name -- Returns the default character set for the database connectionProcedural style:
string maxdb_character_set_name ( resource link )Object oriented style (method):
class maxdb {Returns the current character set for the database connection specified by the link parameter.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would be produce the following output:
Current character set is ascii |
This function is an alias of: maxdb_character_set_name().
This function alias is deprecated and only exists for backwards compatibility reasons. It is recommended to not use this function as one day it may be removed from PHP.
(PECL)
maxdb_close_long_data(no version information, might be only in CVS)
maxdb->close_long_data -- Alias di maxdb_stmt_close_long_data()This function is an alias of: maxdb_stmt_close_long_data().
This function alias is deprecated and only exists for backwards compatibility reasons. It is recommended to not use this function as one day it may be removed from PHP.
(PECL)
maxdb_close(no version information, might be only in CVS)
maxdb->close -- Closes a previously opened database connectionProcedural style:
bool maxdb_close ( resource link )Object oriented style (method):
class maxdb {The maxdb_close() function closes a previously opened database connection specified by the link parameter.
(PECL)
maxdb_commit(no version information, might be only in CVS)
maxdb->commit -- Commits the current transactionProcedural style:
bool maxdb_commit ( resource link )Object oriented style (method)
class maxdb {Commits the current transaction for the database connection specified by the link parameter.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples produces no output.
The maxdb_connect_errno() function will return the last error code number for last call to maxdb_connect(). If no errors have occured, this function will return zero.
An error code value for the last call to maxdb_connect(), if it failed. zero means no error occurred.
The above example would produce the following output:
PHP Warning: maxdb_connect(): -4008 POS(1) Unknown user name/password combination [08004] <...> Can't connect to localhost. Errorcode: -4008 |
The maxdb_connect_error() function is identical to the corresponding maxdb_connect_errno() function in every way, except instead of returning an integer error code the maxdb_connect_error() function will return a string representation of the last error to occur for the last maxdb_connect() call. If no error has occured, this function will return an empty string.
The above example would produce the following output:
PHP Warning: maxdb_connect(): -4008 POS(1) Unknown user name/password combination <...> Can't connect to localhost. Error: POS(1) Unknown user name/password combination |
(PECL)
maxdb_connect(no version information, might be only in CVS)
maxdb() -- Open a new connection to the MaxDB serverProcedural style
resource maxdb_connect ( [string host [, string username [, string passwd [, string dbname [, int port [, string socket]]]]]] )Object oriented style (constructor):
class maxdb {The maxdb_connect() function attempts to open a connection to the MaxDB Server running on host which can be either a host name or an IP address. Passing the string "localhost" to this parameter, the local host is assumed. If successful, the maxdb_connect() will return an resource representing the connection to the database, or FALSE on failure.
The username and password parameters specify the username and password under which to connect to the MaxDB server. If the password is not provided (the NULL value is passed), the MaxDB server will attempt to authenticate the user against the maxdb.default_pw in php.ini.
The dbname parameter if provided will specify the default database to be used when performing queries. If not provied, the entry maxdb.default_db in php.ini is used.
The port and socket parameters are ignored for the MaxDB server.
Returns a resource which represents the connection to a MaxDB Server or FALSE if the connection failed.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Host information: localhost |
(PECL)
maxdb_data_seek(no version information, might be only in CVS)
result->data_seek -- Adjusts the result pointer to an arbitary row in the resultProcedural style:
bool maxdb_data_seek ( resource result, int offset )Object oriented style (method):
class result {The maxdb_data_seek() function seeks to an arbitrary result pointer specified by the offset in the result set represented by result. The offset parameter must be between zero and the total number of rows minus one (0..maxdb_num_rows() - 1).
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
City: Irvine State: CA |
The maxdb_debug() can be used to trace the SQLDBC communication. The following strings can be used as a parameter to maxdb_debug():
TRACE SHORT ON|OFF - Enables/disables method call trace. |
TRACE LONG ON|OFF - Enables/disables method argument and detail debug trace. |
TRACE PACKET ON|OFF|<size> - Enables/disables packet trace, limiting the size of the traced object to the specified number of bytes, or 1000 if no size is specified. |
TRACE SQL ON|OFF - Enables/disables high level api trace. |
TRACE TIMESTAMP ON|OFF - Enables/disables a timestamp prefix on each line that is traced. |
TRACE SIZE <size> - Limits the size of the trace file to <size> bytes, at least 8192 bytes are required. |
(PECL)
maxdb_disable_reads_from_master(no version information, might be only in CVS)
maxdb->disable_reads_from_master -- Disable reads from masterProcedural style:
bool maxdb_disable_reads_from_master ( resource link )Object oriented style (method):
class maxdb {Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PECL)
maxdb_errno(no version information, might be only in CVS)
maxdb->errno -- Returns the error code for the most recent function callProcedural style:
int maxdb_errno ( resource link )Object oriented style (property):
class maxdb {The maxdb_errno() function will return the last error code for the most recent MaxDB function call that can succeed or fail with respect to the database link defined by the link parameter. If no errors have occured, this function will return zero.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
PHP Warning: maxdb_query(): -4005 POS(8) Unknown column name:XXX [42000] <...> Errorcode: -4005 |
Procedural style:
string maxdb_error ( resource link )Object oriented style (property)
class maxdb {The maxdb_error() function is identical to the corresponding maxdb_errno() function in every way, except instead of returning an integer error code the maxdb_error() function will return a string representation of the last error to occur for the database connection represented by the link parameter. If no error has occured, this function will return an empty string.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
PHP Warning: maxdb_query(): -4005 POS(8) Unknown column name:XXX [42000] Errormessgae: POS(8) Unknown column name:XXX |
This function is an alias of: maxdb_stmt_execute().
This function alias is deprecated and only exists for backwards compatibility reasons. It is recommended to not use this function as one day it may be removed from PHP.
(PECL)
maxdb_fetch_array(no version information, might be only in CVS)
result->fetch_array -- Fetch a result row as an associative, a numeric array, or bothProcedural style:
mixed maxdb_fetch_array ( resource result [, int resulttype] )Object oriented style (method):
class result {Returns an array that corresponds to the fetched row or NULL if there are no more rows for the resultset represented by the result parameter.
maxdb_fetch_array() is an extended version of the maxdb_fetch_row() function. In addition to storing the data in the numeric indices of the result array, the maxdb_fetch_array() function can also store the data in associative indices, using the field names of the result set as keys.
Nota: I nomi dei campi restituiti da questa funzione sono case-sensitive.
Nota: This function sets NULL fields to PHP NULL value.
If two or more columns of the result have the same field names, the last column will take precedence and overwrite the earlier data. In order to access multiple columns with the same name, the numerically indexed version of the row must be used.
The optional second argument resulttype is a constant indicating what type of array should be produced from the current row data. The possible values for this parameter are the constants MAXDB_ASSOC, MAXDB_ASSOC_UPPER, MAXDB_ASSOC_LOWER, MAXDB_NUM, or MAXDB_BOTH. By default the maxdb_fetch_array() function will assume MAXDB_BOTH, which is a combination of MAXDB_NUM and MAXDB_ASSOC for this parameter.
By using the MAXDB_ASSOC constant this function will behave identically to the maxdb_fetch_assoc(), while MAXDB_NUM will behave identically to the maxdb_fetch_row() function. The final option MAXDB_BOTH will create a single array with the attributes of both.
By using the MAXDB_ASSOC_UPPER constant, the behaviour of this function is identical to the use of MAXDB_ASSOC except the array index of a column is the fieldname in upper case.
By using the MAXDB_ASSOC_LOWER constant, the behaviour of this function is identical to the use of MAXDB_ASSOC except the array index of a column is the fieldname in lower case.
Returns an array that corresponds to the fetched row or NULL if there are no more rows in resultset.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
New York (NY) New York (NY) Long Island (NY) |
(PECL)
maxdb_fetch_assoc(no version information, might be only in CVS)
maxdb->fetch_assoc -- Fetch a result row as an associative arrayProcedural style:
array maxdb_fetch_assoc ( resource result )Object oriented style (method):
class result {Returns an associative array that corresponds to the fetched row or NULL if there are no more rows.
The maxdb_fetch_assoc() function is used to return an associative array representing the next row in the result set for the result represented by the result parameter, where each key in the array represents the name of one of the result set's columns.
If two or more columns of the result have the same field names, the last column will take precedence. To access the other column(s) of the same name, you either need to access the result with numeric indices by using maxdb_fetch_row() or add alias names.
Nota: I nomi dei campi restituiti da questa funzione sono case-sensitive.
Nota: This function sets NULL fields to PHP NULL value.
Returns an array that corresponds to the fetched row or NULL if there are no more rows in resultset.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
New York (NY) New York (NY) Long Island (NY) Albany (NY) Washington (DC) Washington (DC) Washington (DC) Silver Spring (MD) Daytona Beach (FL) Deerfield Beach (FL) Clearwater (FL) Cincinnati (OH) Detroit (MI) Rosemont (IL) Chicago (IL) Chicago (IL) New Orleans (LA) Dallas (TX) Los Angeles (CA) Hollywood (CA) Long Beach (CA) Palm Springs (CA) Irvine (CA) Santa Clara (CA) Portland (OR) |
(PECL)
maxdb_fetch_field_direct(no version information, might be only in CVS)
result->fetch_field_direct -- Fetch meta-data for a single fieldProcedural style:
mixed maxdb_fetch_field_direct ( resource result, int fieldnr )Object oriented style (method):
class result {maxdb_fetch_field_direct() returns an resource which contains field definition informations from specified resultset. The value of fieldnr must be in the range from 0 to number of fields - 1.
Returns an resource which contains field definition informations or FALSE if no field information for specified fieldnr is available.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Name: CNO Table: max. Len: 4 Flags: -1 Type: 0 |
(PECL)
maxdb_fetch_field(no version information, might be only in CVS)
result->fetch_field -- Returns the next field in the result setProcedural style:
mixed maxdb_fetch_field ( resource result )Object oriented style (method):
class result {The maxdb_fetch_field() returns the definition of one column of a result set as an resource. Call this function repeatedly to retrieve information about all columns in the result set. maxdb_fetch_field() returns FALSE when no more fields are left.
Returns an resource which contains field definition informations or FALSE if no field information is available.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Name: NAME Table: max. Len: 10 Flags: -1 Type: 2 Name: CNO Table: max. Len: 4 Flags: -1 Type: 0 |
(PECL)
maxdb_fetch_fields(no version information, might be only in CVS)
result->fetch_fields -- Returns an array of resources representing the fields in a result setProcedural Style:
mixed maxdb_fetch_fields ( resource result )Object oriented style (method):
class result {This function serves an identical purpose to the maxdb_fetch_field() function with the single difference that, instead of returning one resource at a time for each field, the columns are returned as an array of resources.
Returns an array of resources which contains field definition informations or FALSE if no field information is available.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Name: NAME Table: max. Len: 10 Flags: -1 Type: 2 Name: CNO Table: max. Len: 4 Flags: -1 Type: 0 |
(PECL)
maxdb_fetch_lengths(no version information, might be only in CVS)
result->lengths -- Returns the lengths of the columns of the current row in the result setProcedural style:
array maxdb_fetch_lengths ( resource result )Object oriented style (property):
class result {The maxdb_fetch_lengths() function returns an array containing the lengths of every column of the current row within the result set represented by the result parameter. If successful, a numerically indexed array representing the lengths of each column is returned or FALSE on failure.
An array of integers representing the size of each column (not including any terminating null characters). FALSE if an error occurred.
maxdb_fetch_lengths() is valid only for the current row of the result set. It returns FALSE if you call it before calling maxdb_fetch_row/array/resource or after retrieving all rows in the result.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Field 1 has Length 4 Field 2 has Length 3 Field 3 has Length 5 Field 4 has Length 6 Field 5 has Length 5 Field 6 has Length 21 |
(PECL)
maxdb_fetch_object(no version information, might be only in CVS)
result->fetch_object -- Returns the current row of a result set as an objectProcedural style:
object maxdb_fetch_object ( object result )Object oriented style (method):
class result {The maxdb_fetch_object() will return the current row result set as an object where the attributes of the object represent the names of the fields found within the result set. If no more rows exist in the current result set, NULL is returned.
Returns an object that corresponds to the fetched row or NULL if there are no more rows in resultset.
Nota: I nomi dei campi restituiti da questa funzione sono case-sensitive.
Nota: This function sets NULL fields to PHP NULL value.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
New York (NY) New York (NY) Long Island (NY) Albany (NY) Washington (DC) Washington (DC) Washington (DC) Silver Spring (MD) Daytona Beach (FL) Deerfield Beach (FL) Clearwater (FL) Cincinnati (OH) Detroit (MI) Rosemont (IL) Chicago (IL) Chicago (IL) New Orleans (LA) Dallas (TX) Los Angeles (CA) Hollywood (CA) Long Beach (CA) Palm Springs (CA) Irvine (CA) Santa Clara (CA) Portland (OR) |
(PECL)
maxdb_fetch_row(no version information, might be only in CVS)
result->fetch_row -- Get a result row as an enumerated arrayProcedural style:
mixed maxdb_fetch_row ( resource result )Object oriented style (method):
class result {Returns an array that corresponds to the fetched row, or NULL if there are no more rows.
maxdb_fetch_row() fetches one row of data from the result set represented by result and returns it as an enumerated array, where each column is stored in an array offset starting from 0 (zero). Each subsequent call to the maxdb_fetch_row() function will return the next row within the result set, or FALSE if there are no more rows.
maxdb_fetch_row() returns an array that corresponds to the fetched row or NULL if there are no more rows in result set.
Nota: This function sets NULL fields to PHP NULL value.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
New York (NY) New York (NY) Long Island (NY) Albany (NY) Washington (DC) Washington (DC) Washington (DC) Silver Spring (MD) Daytona Beach (FL) Deerfield Beach (FL) Clearwater (FL) Cincinnati (OH) Detroit (MI) Rosemont (IL) Chicago (IL) Chicago (IL) New Orleans (LA) Dallas (TX) Los Angeles (CA) Hollywood (CA) Long Beach (CA) Palm Springs (CA) Irvine (CA) Santa Clara (CA) Portland (OR) |
This function is an alias of: maxdb_stmt_fetch().
This function alias is deprecated and only exists for backwards compatibility reasons. It is recommended to not use this function as one day it may be removed from PHP.
(PECL)
maxdb_field_count(no version information, might be only in CVS)
maxdb->field_count -- Returns the number of columns for the most recent queryProcedural style:
int maxdb_field_count ( resource link )Object oriented style (method):
class maxdb {Returns the number of columns for the most recent query on the connection represented by the link parameter. This function can be useful when using the maxdb_store_result() function to determine if the query should have produced a non-empty result set or not without knowing the nature of the query.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above example produces no output.
(PECL)
maxdb_field_seek(no version information, might be only in CVS)
result->field_seek -- Set result pointer to a specified field offsetProcedural style:
bool maxdb_field_seek ( resource result, int fieldnr )Object oriented style (method):
class result {Sets the field cursor to the given offset. The next call to maxdb_fetch_field() will retrieve the field definition of the column associated with that offset.
Nota: To seek to the beginning of a row, pass an offset value of zero.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Name: NAME Table: max. Len: 10 Flags: -1 Type: 2 |
(PECL)
maxdb_field_tell(no version information, might be only in CVS)
result->current_field -- Get current field offset of a result pointerProcedural style:
int maxdb_field_tell ( resource result )Object oriented style (property):
class result {Returns the position of the field cursor used for the last maxdb_fetch_field() call. This value can be used as an argument to maxdb_field_seek().
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Column 1: Name: NAME Table: max. Len: 10 Flags: -1 Type: 2 Column 2: Name: CNO Table: max. Len: 4 Flags: -1 Type: 0 |
(PECL)
maxdb_free_result(no version information, might be only in CVS)
result->free -- Frees the memory associated with a resultProcedural style:
void maxdb_free_result ( resource result )Object oriented style (method):
class result {The maxdb_free_result() function frees the memory associated with the result represented by the result parameter, which was allocated by maxdb_query(), maxdb_store_result() or maxdb_use_result().
Nota: You should always free your result with maxdb_free_result(), when your result resource is not needed anymore.
The maxdb_get_client_info() function is used to return a string representing the client version being used in the MaxDB extension.
The above examples would produce the following output:
Client library version: libSQLDBC <...> |
A number that represents the MaxDB client library version in format: main_version*10000 + minor_version *100 + sub_version. For example, 7.5.0 is returned as 70500.
This is useful to quickly determine the version of the client library to know if some capability exits.
(PECL)
maxdb_get_host_info(no version information, might be only in CVS)
maxdb->get_host_info -- Returns a string representing the type of connection usedProcdural style:
string maxdb_get_host_info ( resource link )Object oriented style (property):
class maxdb {The maxdb_get_host_info() function returns a string describing the connection represented by the link parameter is using.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Host info: localhost |
This function is an alias of: maxdb_stmt_result_metadata().
This function alias is deprecated and only exists for backwards compatibility reasons. It is recommended to not use this function as one day it may be removed from PHP.
(PECL)
maxdb_get_proto_info(no version information, might be only in CVS)
maxdb->protocol_version -- Returns the version of the MaxDB protocol usedProcedural style:
int maxdb_get_proto_info ( resource link )Object oriented style (property):
class maxdb {Returns an integer representing the MaxDB protocol version used by the connection represented by the link parameter.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Protocol version: 10 |
(PECL)
maxdb_get_server_info(no version information, might be only in CVS)
maxdb->server_info -- Returns the version of the MaxDB serverProcedural style:
string maxdb_get_server_info ( resource link )Object oriented style (property):
class maxdb {Returns a string representing the version of the MaxDB server that the MaxDB extension is connected to (represented by the link parameter).
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Server version: Kernel 7<...> |
Procedural style:
int maxdb_get_server_version ( resource link )Object oriented style (property):
class maxdb {The maxdb_get_server_version() function returns the version of the server connected to (represented by the link parameter) as an integer.
The form of this version number is main_version * 10000 + minor_version * 100 + sub_version (i.e. version 7.5.0 is 70500).
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Server version: 7<...> |
(PECL)
maxdb_info(no version information, might be only in CVS)
maxdb->info -- Retrieves information about the most recently executed queryProcedural style:
string maxdb_info ( resource link )Object oriented style (property)
class maxdb {The maxdb_info() function returns a string providing information about the last query executed. The nature of this string is provided below:
Tabella 1. Possible maxdb_info return values
Query type | Example result string |
---|---|
INSERT INTO...SELECT... | Records: 100 Duplicates: 0 Warnings: 0 |
INSERT INTO...VALUES (...),(...),(...) | Records: 3 Duplicates: 0 Warnings: 0 |
LOAD DATA INFILE ... | Records: 1 Deleted: 0 Skipped: 0 Warnings: 0 |
ALTER TABLE ... | Records: 3 Duplicates: 0 Warnings: 0 |
UPDATE ... | Rows matched: 40 Changed: 40 Warnings: 0 |
Nota: Queries which do not fall into one of the above formats are not supported. In these situations, maxdb_info() will return an empty string.
A character string representing additional information about the most recently executed query.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Records: 25 Duplicates: 0 Warnings: 0 |
Allocates or initializes a MaxDB resource suitable for maxdb_options() and maxdb_real_connect().
Nota: Any subsequent calls to any maxdb function (except maxdb_options()) will fail until maxdb_real_connect() was called.
(PECL)
maxdb_insert_id(no version information, might be only in CVS)
maxdb->insert_id -- Returns the auto generated id used in the last queryProcedural style:
mixed maxdb_insert_id ( resource link )Object oriented style (property):
class maxdb {The maxdb_insert_id() function returns the ID generated by a query on a table with a column having the DEFAULT SERIAL attribute. If the last query wasn't an INSERT or UPDATE statement or if the modified table does not have a column with the DEFAULT SERIAL attribute, this function will return zero.
The value of the DEFAULT SERIAL field that was updated by the previous query. Returns zero if there was no previous query on the connection or if the query did not update an DEFAULT_SERIAL value.
Nota: If the number is greater than maximal int value, maxdb_insert_id() will return a string.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
New Record has id 1. |
(PECL)
maxdb_kill(no version information, might be only in CVS)
maxdb->kill -- Disconnects from a MaxDB serverProcedural style:
bool maxdb_kill ( resource link, int processid )Object oriented style (method)
class maxdb {This function is used to disconnect from a MaxDB server specified by the processid parameter.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Error: Session not connected |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PECL)
maxdb_more_results(no version information, might be only in CVS)
maxdb->more_results -- Check if there any more query results from a multi querymaxdb_more_results() indicates if one or more result sets are available from a previous call to maxdb_multi_query().
(PECL)
maxdb_multi_query(no version information, might be only in CVS)
maxdb->multi_query -- Performs a query on the databaseProcedural style:
bool maxdb_multi_query ( resource link, string query )Object oriented style (method):
class maxdb {The maxdb_multi_query() works like the function maxdb_query(). Multiple queries are not yet supported.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
a |
(PECL)
maxdb_next_result(no version information, might be only in CVS)
maxdb->next_result -- Prepare next result from multi_querySince multiple queries are not yet supported, maxdb_next_result() returns always FALSE.
(PECL)
maxdb_num_fields(no version information, might be only in CVS)
result->field_count -- Get the number of fields in a resultProcedural style:
int maxdb_num_fields ( resource result )Object oriented style (property):
class result {maxdb_num_fields() returns the number of fields from specified result set.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Result set has 3 fields. |
Procedural style:
int maxdb_num_rows ( resource result )Object oriented style (property):
class maxdb {Returns the number of rows in the result set.
The use of maxdb_num_rows() depends on whether you use buffered or unbuffered result sets. In case you use unbuffered resultsets maxdb_num_rows() will not correct the correct number of rows until all the rows in the result have been retrieved.
Returns number of rows in the result set.
Nota: If the number of rows is greater than maximal int value, the number will be returned as a string.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Result set has 15 rows. |
Procedural style:
bool maxdb_options ( resource link, int option, mixed value )Object oriented style (method)
class maxdb {maxdb_options() can be used to set extra connect options and affect behavior for a connection.
This function may be called multiple times to set several options.
maxdb_options() should be called after maxdb_init() and before maxdb_real_connect().
The parameter option is the option that you want to set, the value is the value for the option. For detailed description of the options see http://dev.mysql.com/doc/maxdb/ The parameter option can be one of the following values:
Tabella 1. Valid options
Name | Description |
---|---|
MAXDB_COMPNAME | The component name used to initialise the SQLDBC runtime environment. |
MAXDB_APPLICATION | The application to be connected to the database. |
MAXDB_APPVERSION | The version of the application. |
MAXDB_SQLMODE | The SQL mode. |
MAXDB_UNICODE | TRUE, if the connection is an unicode (UCS2) client or FALSE, if not. |
MAXDB_TIMEOUT | The maximum allowed time of inactivity after which the connection to the database is closed by the system. |
MAXDB_ISOLATIONLEVEL | Specifies whether and how shared locks and exclusive locks are implicitly requested or released. |
MAXDB_PACKETCOUNT | The number of different request packets used for the connection. |
MAXDB_STATEMENTCACHESIZE | The number of prepared statements to be cached for the connection for re-use. |
MAXDB_CURSORPREFIX | The prefix to use for result tables that are automatically named. |
This function is an alias of: maxdb_stmt_param_count().
This function alias is deprecated and only exists for backwards compatibility reasons. It is recommended to not use this function as one day it may be removed from PHP.
(PECL)
maxdb_ping(no version information, might be only in CVS)
maxdb->ping -- Pings a server connection, or tries to reconnect if the connection has gone downProcedural style:
bool maxdb_ping ( resource link )Object oriented style (method):
class maxdb {Checks whether the connection to the server is working. If it has gone down, and global option maxdb.reconnect is enabled an automatic reconnection is attempted.
This function can be used by clients that remain idle for a long while, to check whether the server has closed the connection and reconnect if necessary.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Our connection is ok! |
(PECL)
maxdb_prepare(no version information, might be only in CVS)
maxdb->prepare -- Prepare a SQL statement for executionProcedure style:
resource maxdb_prepare ( resource link, string query )Object oriented style (method)
class stmt {maxdb_prepare() prepares the SQL query pointed to by the null-terminated string query, and returns a statement handle to be used for further operations on the statement. The query must consist of a single SQL statement.
Nota: You should not add a terminating semicolon or \g to the statement.
The parameter query can include one or more parameter markers in the SQL statement by embedding question mark (?) characters at the appropriate positions.
Nota: The markers are legal only in certain places in SQL statements. For example, they are allowed in the VALUES() list of an INSERT statement (to specify column values for a row), or in a comparison with a column in a WHERE clause to specify a comparison value.
However, they are not allowed for identifiers (such as table or column names), in the select list that names the columns to be returned by a SELECT statement), or to specify both operands of a binary operator such as the = equal sign. The latter restriction is necessary because it would be impossible to determine the parameter type. In general, parameters are legal only in Data Manipulation Languange (DML) statements, and not in Data Defination Language (DDL) statements.
The parameter markers must be bound to application variables using maxdb_stmt_bind_param() and/or maxdb_stmt_bind_result() before executing the statement or fetching rows.
maxdb_stmt_execute(), maxdb_stmt_fetch(), maxdb_stmt_bind_param(), maxdb_stmt_bind_result(), maxdb_stmt_close()
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Rosemont is in district IL |
(PECL)
maxdb_query(no version information, might be only in CVS)
maxdb->query -- Performs a query on the databaseProcedural style:
mixed maxdb_query ( resource link, string query [, int resultmode] )Object oriented style (method):
class maxdb {The maxdb_query() function is used to simplify the act of performing a query against the database represented by the link parameter.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento. For SELECT, SHOW, DESCRIBE or EXPLAIN maxdb_query() will return a result resource.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Table mycity successfully created. Select returned 25 rows. |
(PECL)
maxdb_real_connect(no version information, might be only in CVS)
maxdb->real_connect -- Opens a connection to a MaxDB serverProcedural style
bool maxdb_real_connect ( resource link [, string hostname [, string username [, string passwd [, string dbname [, int port [, string socket]]]]]] )Object oriented style (method)
class maxdb {maxdb_real_connect() attempts to establish a connection to a MaxDB database engine running on hostname.
This function differs from maxdb_connect():
maxdb_real_connect() needs a valid resource which has to be created by function maxdb_init()
With function maxdb_options() you can set various options for connection.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Connection: localhost <...> |
(PECL)
maxdb_real_escape_string(no version information, might be only in CVS)
maxdb->real_escape_string -- Escapes special characters in a string for use in a SQL statement, taking into account the current charset of the connectionProcedural style:
string maxdb_real_escape_string ( resource link, string escapestr )Object oriented style (method):
class maxdb {This function is used to create a legal SQL string that you can use in a SQL statement. The string escapestr is encoded to an escaped SQL string, taking into account the current character set of the connection.
Characters encoded are ', ".
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Warning: maxdb_query(): -5016 POS(43) Missing delimiter: ) <...> Error: 42000 1 Row inserted. |
(PECL)
maxdb_real_query(no version information, might be only in CVS)
maxdb->real_query -- Execute an SQL queryProcedural style
bool maxdb_real_query ( resource link, string query )Object oriented style (method):
class maxdb {The maxdb_real_query() is functionally identical with the maxdb_query().
Nota: In order to determine if a given query should return a result set or not, see maxdb_field_count().
Esempio 1. Procedural style
|
The above examples would produce the following output:
Warning: maxdb_query(): -4004 POS(18) Unknown table name:NONEXISTINGTABLE <...> |
(PECL)
maxdb_rollback(no version information, might be only in CVS)
maxdb->rollback -- Rolls back current transactionRollbacks the current transaction for the database specified by the link parameter.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
0 rows in table mycity. 25 rows in table mycity (after rollback). |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PECL)
maxdb_rpl_query_type(no version information, might be only in CVS)
maxdb->rpl_query_type -- Returns RPL query typeObject oriented style (method)
class maxdb {Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PECL)
maxdb_select_db(no version information, might be only in CVS)
maxdb->select_db -- Selects the default database for database queriesThe maxdb_select_db() function selects the default database (specified by the dbname parameter) to be used when performing queries against the database connection represented by the link parameter.
Nota: This function should only be used to change the default database for the connection. You can select the default database with 4th parameter in maxdb_connect().
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Default database is <...>. Warning: maxdb_select_db(): -10709 Connection failed (RTE:database not running) <...> Warning: maxdb_query(): -10821 Session not connected [] <...> Warning: maxdb_close(): -10821 Session not connected [] <...> |
This function is an alias of: maxdb_stmt_send_long_data().
This function alias is deprecated and only exists for backwards compatibility reasons. It is recommended to not use this function as one day it may be removed from PHP.
(PECL)
maxdb_send_query(no version information, might be only in CVS)
maxdb->send_query -- Send the query and returnObject oriented style (method)
class maxdb {Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PECL)
maxdb_sqlstate(no version information, might be only in CVS)
maxdb->sqlstate -- Returns the SQLSTATE error from previous MaxDB operationProcedural style:
string maxdb_sqlstate ( resource link )Object oriented style (property):
class maxdb {Returns a string containing the SQLSTATE error code for the last error. The error code consists of five characters. '00000' means no error. The values are specified by ANSI SQL and ODBC.
Nota: Note that not all MaxDB errors are yet mapped to SQLSTATE's. The value HY000 (general error) is used for unmapped errors.
Returns a string containing the SQLSTATE error code for the last error. The error code consists of five characters. '00000' means no error.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Warning: maxdb_query(): -6000 POS(20) Duplicate table name:CITY [I6000] <...> Error - SQLSTATE I6000. |
(PECL)
maxdb_ssl_set(no version information, might be only in CVS)
maxdb->ssl_set -- Used for establishing secure connections using SSLProcedural style:
bool maxdb_ssl_set ( resource link, string key, string cert, string ca, string capath, string cipher )Object oriented style (method):
class maxdb {Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PECL)
maxdb_stat(no version information, might be only in CVS)
maxdb->stat -- Gets the current system statusProcedural style:
string maxdb_stat ( resource link )Object oriented style (method):
class maxdb {maxdb_stat() returns a string containing several information about the MaxDB server running.
(PECL)
maxdb_stmt_affected_rows(no version information, might be only in CVS)
maxdb_stmt->affected_rows -- Returns the total number of rows changed, deleted, or inserted by the last executed statementProcedural style :
int maxdb_stmt_affected_rows ( resource stmt )Object oriented style (property):
class stmt {maxdb_stmt_affected_rows() returns the number of rows affected by INSERT, UPDATE, or DELETE query. If the last query was invalid or the number of rows can not determined, this function will return -1.
An integer greater than zero indicates the number of rows affected or retrieved. Zero indicates that no records where updated for an UPDATE/DELETE statement, no rows matched the WHERE clause in the query or that no query has yet been executed. -1 indicates that the query has returned an error or the number of rows can not determined.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
rows inserted: 4 |
(PECL)
maxdb_stmt_bind_param(no version information, might be only in CVS)
stmt->bind_param -- Binds variables to a prepared statement as parametersProcedural style:
bool maxdb_stmt_bind_param ( resource stmt, string types, mixed &var1 [, mixed &...] )Object oriented style (method):
class stmt {maxdb_stmt_bind_param() is used to bind variables for the parameter markers in the SQL statement that was passed to maxdb_prepare(). The string types contains one or more characters which specify the types for the corresponding bind variables.
Variables for SELECT INTO SQL statements can also be bound using maxdb_stmt_bind_param(). Parameters for database procedures can be bound using maxdb_stmt_bind_param(). See the examples how to use maxdb_stmt_bind_param() in this cases.
If a variable bound as INTO variable to a SQL statement was used before, the content of this variable is overwritten by the data of the SELECT INTO statement. A reference to this variable will be invalid after a call to maxdb_stmt_bind_param().
For INOUT parameters of database procedures the content of the bound INOUT variable is overwritten by the output value of the database procedure. A reference to this variable will be invalid after a call to maxdb_stmt_bind_param().
maxdb_stmt_bind_result(), maxdb_stmt_execute(), maxdb_stmt_fetch(), maxdb_prepare(), maxdb_stmt_send_long_data(), maxdb_stmt_errno(), maxdb_stmt_error()
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
1 Row inserted. 1 Row deleted. |
Esempio 3. Procedural style (SELECT INTO)
|
The above examples would produce the following output:
21.600000 |
Esempio 4. Procedural style (DB procedure)
|
The above examples would produce the following output:
a |
(PECL)
maxdb_stmt_bind_result(no version information, might be only in CVS)
stmt->bind_result -- Binds variables to a prepared statement for result storageProcedural style:
bool maxdb_stmt_bind_result ( resource stmt, mixed &var1 [, mixed &...] )Object oriented style (method):
class stmt {maxdb_stmt_bind_result() is used to associate (bind) columns in the result set to variables. When maxdb_stmt_fetch() is called to fetch data, the MaxDB client/server protocol places the data for the bound columns into the specified variables var1, ....
Nota: Note that all columns must be bound prior to calling maxdb_stmt_fetch(). Depending on column types bound variables can silently change to the corresponding PHP type.
A column can be bound or rebound at any time, even after a result set has been partially retrieved. The new binding takes effect the next time maxdb_stmt_fetch() is called.
maxdb_stmt_bind_param(), maxdb_stmt_execute(), maxdb_stmt_fetch(), maxdb_prepare(), maxdb_stmt_prepare(), maxdb_stmt_init(), maxdb_stmt_errno(), maxdb_stmt_error()
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
12203 Albany 60601 Chicago 60615 Chicago 45211 Cincinnati 33575 Clearwater 75243 Dallas 32018 Daytona Beach 33441 Deerfield Beach 48226 Detroit 90029 Hollywood 92714 Irvine 90804 Long Beach 11788 Long Island 90018 Los Angeles 70112 New Orleans 10019 New York 10580 New York 92262 Palm Springs 97213 Portland 60018 Rosemont 95054 Santa Clara 20903 Silver Spring 20005 Washington 20019 Washington 20037 Washington |
(PECL)
maxdb_stmt_close_long_data(no version information, might be only in CVS)
stmt->close_long_data -- Ends a sequence of maxdb_stmt_send_long_data()Procedural style:
bool maxdb_stmt_close_long_data ( resource stmt, int param_nr )Object oriented style (method):
class maxdb_stmt {This function has to be called after a sequence of maxdb_stmt_send_long_data(), that was started after maxdb_execute().
param_nr indicates which parameter to associate the end of data with. Parameters are numbered beginning with 0.
(PECL)
maxdb_stmt_close(no version information, might be only in CVS)
maxdb_stmt->close -- Closes a prepared statementProcedural style:
bool maxdb_stmt_close ( resource stmt )Object oriented style (method):
class maxdb_stmt {Closes a prepared statement. maxdb_stmt_close() also deallocates the statement handle pointed to by stmt. If the current statement has pending or unread results, this function cancels them so that the next query can be executed.
(PECL)
maxdb_stmt_data_seek(no version information, might be only in CVS)
stmt->data_seek -- Seeks to an arbitray row in statement result setProcedural style:
bool maxdb_stmt_data_seek ( resource statement, int offset )Object oriented style (method):
class stmt {The maxdb_stmt_data_seek() function seeks to an arbitrary result pointer specified by the offset in the statement result set represented by statement. The offset parameter must be between zero and the total number of rows minus one (0..maxdb_stmt_num_rows() - 1).
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
City: Dallas Zip: 75243 |
(PECL)
maxdb_stmt_errno(no version information, might be only in CVS)
maxdb_stmt->errno -- Returns the error code for the most recent statement callProcedural style :
int maxdb_stmt_errno ( resource stmt )Object oriented style (property):
class stmt {For the statement specified by stmt, maxdb_stmt_errno() returns the error code for the most recently invoked statement function that can succeed or fail.
Nota: For possible error codes see documentation of SQLDBC: http://dev.mysql.com/doc/maxdb/.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Warning: maxdb_stmt_execute(): -4004 POS(23) Unknown table name:MYCITY [42000] <...> Error: -4004. |
(PECL)
maxdb_stmt_error(no version information, might be only in CVS)
maxdb_stmt->error -- Returns a string description for last statement errorProcedural style:
string maxdb_stmt_error ( resource stmt )Object oriented style (property):
class stmt {For the statement specified by stmt, maxdb_stmt_error() returns a containing the error message for the most recently invoked statement function that can succeed or fail.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Warning: maxdb_stmt_execute(): -4004 POS(23) Unknown table name:MYCITY [42000] <...> Error: POS(23) Unknown table name:MYCITY. |
(PECL)
maxdb_stmt_execute(no version information, might be only in CVS)
stmt->execute -- Executes a prepared QueryProcedural style:
bool maxdb_stmt_execute ( resource stmt )Object oriented style (method):
class stmt {The maxdb_stmt_execute() function executes a query that has been previously prepared using the maxdb_prepare() function represented by the stmt resource. When executed any parameter markers which exist will automatically be replaced with the appropiate data.
If the statement is UPDATE, DELETE, or INSERT, the total number of affected rows can be determined by using the maxdb_stmt_affected_rows() function. Likewise, if the query yields a result set the maxdb_fetch() function is used.
Nota: When using maxdb_stmt_execute(), the maxdb_fetch() function must be used to fetch the data prior to preforming any additional queries.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
11111 (Georgetown,NY) 22222 (Hubbatown,CA) |
(PECL)
maxdb_stmt_fetch(no version information, might be only in CVS)
stmt->fetch -- Fetch results from a prepared statement into the bound variablesProcedural style:
bool maxdb_stmt_fetch ( resource stmt )Object oriented style (method):
class stmt {maxdb_stmt_fetch() returns row data using the variables bound by maxdb_stmt_bind_result().
Nota: Note that all columns must be bound by the application before calling maxdb_stmt_fetch().
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
12203 (Albany) 60601 (Chicago) 60615 (Chicago) 45211 (Cincinnati) 33575 (Clearwater) 75243 (Dallas) 32018 (Daytona Beach) 33441 (Deerfield Beach) 48226 (Detroit) 90029 (Hollywood) 92714 (Irvine) 90804 (Long Beach) 11788 (Long Island) 90018 (Los Angeles) 70112 (New Orleans) 10019 (New York) 10580 (New York) 92262 (Palm Springs) 97213 (Portland) 60018 (Rosemont) 95054 (Santa Clara) 20903 (Silver Spring) 20005 (Washington) 20019 (Washington) 20037 (Washington) |
(PECL)
maxdb_stmt_free_result(no version information, might be only in CVS)
stmt->free_result -- Frees stored result memory for the given statement handleProcedural style:
void maxdb_stmt_free_result ( resource stmt )Object oriented style (method):
class stmt {The maxdb_stmt_free_result() function frees the result memory associated with the statement represented by the stmt parameter, which was allocated by maxdb_stmt_store_result().
(PECL)
maxdb_stmt_init(no version information, might be only in CVS)
maxdb->stmt_init -- Initializes a statement and returns an resource for use with maxdb_stmt_prepareProcedural style :
resource maxdb_stmt_init ( resource link )Object oriented style (property):
class maxdb {Allocates and initializes a statement resource suitable for maxdb_stmt_prepare().
Nota: Any subsequent calls to any maxdb_stmt function will fail until maxdb_stmt_prepare() was called.
(PECL)
maxdb_stmt_num_rows(no version information, might be only in CVS)
stmt->num_rows -- Return the number of rows in statements result setProcedural style :
int maxdb_stmt_num_rows ( resource stmt )Object oriented style (property):
class stmt {Returns the number of rows in the result set.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Number of rows: 25. |
(PECL)
maxdb_stmt_param_count(no version information, might be only in CVS)
stmt->param_count -- Returns the number of parameter for the given statementProcedural style:
int maxdb_stmt_param_count ( resource stmt )Object oriented style (property):
class stmt {maxdb_stmt_param_count() returns the number of parameter markers present in the prepared statement.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Statement has 2 markers. |
(PECL)
maxdb_stmt_prepare(no version information, might be only in CVS)
stmt->prepare -- Prepare a SQL statement for executionProcedure style:
bool maxdb_stmt_prepare ( resource stmt, string query )Object oriented style (method)
class stmt {maxdb_stmt_prepare() prepares the SQL query pointed to by the null-terminated string query. The statement resource has to be allocated by maxdb_stmt_init(). The query must consist of a single SQL statement.
Nota: You should not add a terminating semicolon or \g to the statement.
The parameter query can include one or more parameter markers in the SQL statement by embedding question mark (?) characters at the appropriate positions.
Nota: The markers are legal only in certain places in SQL statements. For example, they are allowed in the VALUES() list of an INSERT statement (to specify column values for a row), or in a comparison with a column in a WHERE clause to specify a comparison value.
However, they are not allowed for identifiers (such as table or column names), in the select list that names the columns to be returned by a SELECT statement), or to specify both operands of a binary operator such as the = equal sign. The latter restriction is necessary because it would be impossible to determine the parameter type. In general, parameters are legal only in Data Manipulation Languange (DML) statements, and not in Data Defination Language (DDL) statements.
The parameter markers must be bound to application variables using maxdb_stmt_bind_param() and/or maxdb_stmt_bind_result() before executing the statement or fetching rows.
maxdb_stmt_init(), maxdb_stmt_execute(), maxdb_stmt_fetch(), maxdb_stmt_bind_param(), maxdb_stmt_bind_result(), maxdb_stmt_close()
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Portland is in district OR |
(PECL)
maxdb_stmt_reset(no version information, might be only in CVS)
stmt->reset -- Resets a prepared statementProcedural style:
bool maxdb_stmt_reset ( resource stmt )Object oriented style (method):
class stmt {Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Procedural style:
resource maxdb_stmt_result_metadata ( resource stmt )Object oriented style (method):
class stmt {If a statement passed to maxdb_prepare() is one that produces a result set, maxdb_stmt_result_metadata() returns the result resource that can be used to process the meta information such as total number of fields and individual field information.
Nota: This result set pointer can be passed as an argument to any of the field-based functions that process result set metadata, such as:
The result set structure should be freed when you are done with it, which you can do by passing it to maxdb_free_result()
Nota: The result set returned by maxdb_stmt_result_metadata() contains only metadata. It does not contain any row results. The rows are obtained by using the statement handle with maxdb_fetch().
maxdb_stmt_result_metadata() returns a result resource or FALSE if an error occured.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Fieldname: ID |
(PECL)
maxdb_stmt_send_long_data(no version information, might be only in CVS)
stmt->send_long_data -- Send data in blocksProcedural style:
bool maxdb_stmt_send_long_data ( resource stmt, int param_nr, string data )Object oriented style (method)
class stmt {Allows to send parameter data to the server in pieces (or chunks). This function can be called multiple times to send the parts of a character or binary data value for a column, which must be one of the TEXT or BLOB datatypes.
param_nr indicates which parameter to associate the data with. Parameters are numbered beginning with 0. data is a string containing data to be sent.
Nota: For efficiency reasons, this function should be used after calling maxdb_execute(). In this case, the data is not stored on the client side. The end of the sequence must end with a call to maxdb_stmt_close_long_data().
Returns a string containing the SQLSTATE error code for the most recently invoked prepared statement function that can succeed or fail. The error code consists of five characters. '00000' means no error. The values are specified by ANSI SQL and ODBC.
Nota: Note that not all MaxDB errors are yet mapped to SQLSTATE's. The value HY000 (general error) is used for unmapped errors.
Returns a string containing the SQLSTATE error code for the last error. The error code consists of five characters. '00000' means no error.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Warning: maxdb_stmt_execute(): -4004 POS(23) Unknown table name:MYCITY [42000] <...> Error: 42000. |
(PECL)
maxdb_stmt_store_result(no version information, might be only in CVS)
maxdb->store_result -- Transfers a result set from a prepared statementProcedural style:
bool maxdb_stmt_store_result ( resource stmt )Object oriented style (method):
class maxdb {maxdb_stmt_store_result() has no functionally effect and should not be used for retrieving data from MaxDB server.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Number of rows: 25. |
(PECL)
maxdb_store_result(no version information, might be only in CVS)
maxdb->store_result -- Transfers a result set from the last queryProcedural style:
resource maxdb_store_result ( resource link )Object oriented style (method):
class maxdb {This function has no functionally effect.
(PECL)
maxdb_thread_id(no version information, might be only in CVS)
maxdb->thread_id -- Returns the thread ID for the current connectionProcedural style:
int maxdb_thread_id ( resource link )Object oriented style (property):
class maxdb {The maxdb_thread_id() function returns the thread ID for the current connection which can then be killed using the maxdb_kill() function. If the connection is lost and you reconnect with maxdb_ping(), the thread ID will be other. Therefore you should get the thread ID only when you need it.
Nota: The thread ID is assigned on a connection-by-connection basis. Hence, if the connection is broken and then re-established a new thread ID will be assigned.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Warning: maxdb_query(): -10821 Session not connected <...> Error: Session not connected |
(no version information, might be only in CVS)
maxdb_thread_safe -- Returns whether thread safety is given or notProcedural style:
bool maxdb_thread_safe ( void )maxdb_thread_safe() indicates whether the client library is compiled as thread-safe.
(PECL)
maxdb_use_result(no version information, might be only in CVS)
maxdb->use_result -- Initiate a result set retrievalProcedural style:
resource maxdb_use_result ( resource link )Object oriented style (method):
class maxdb {maxdb_use_result() has no effect.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
a |
(PECL)
maxdb_warning_count(no version information, might be only in CVS)
maxdb->warning_count -- Returns the number of warnings from the last query for the given linkProcedural style:
int maxdb_warning_count ( resource link )Object oriented style (property):
class maxdb {maxdb_warning_count() returns the number of warnings from the last query in the connection represented by the link parameter.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The above examples would produce the following output:
Warning: maxdb_query(): -8004 POS(62) Constant must be compatible with column type and length <...> Number of warning: 0 |
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: Questo modulo è stato spostato nel repository PECL e non sarà più rilascio con il PHP dalla versione 5.0.0.
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: Questo modulo non è disponibile su piattaforme Windows.
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].
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
mcal_append_event() stores the global event into an MCAL calendar for the stream mcal_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, PECL)
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 month month, taking into account if the considered 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, PECL)
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.
(PHP 3 >= 3.0.13, PHP 4, PECL)
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.
(PHP 3 >= 3.0.13, PHP 4, PECL)
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.
(PHP 3 >= 3.0.13, PHP 4, PECL)
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.
(PHP 3 >= 3.0.13, PHP 4, PECL)
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.
(PHP 3 >= 3.0.13, PHP 4, PECL)
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.
(PHP 3 >= 3.0.13, PHP 4, PECL)
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 reoccurring on a daily basis, ending at the given date.
(PHP 3 >= 3.0.13, PHP 4, PECL)
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 reoccurring on a monthly by month day basis, ending at the given date.
(PHP 3 >= 3.0.13, PHP 4, PECL)
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 reoccurring on a monthly by week basis, ending at the given date.
(PHP 3 >= 3.0.15, PHP 4, PECL)
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, PECL)
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 reoccurring on a weekly basis, ending at the given date.
(PHP 3 >= 3.0.13, PHP 4, PECL)
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 reoccurring on a yearly basis,ending at the given date.
(PHP 3 >= 3.0.13, PHP 4, PECL)
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.
(PHP 3 >= 3.0.13, PHP 4, PECL)
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.
(no version information, might be only in CVS)
mcal_expunge -- Deletes all events marked for being expungedmcal_expunge() deletes all events which have been previously marked for deletion.
(PHP 3 >= 3.0.13, PHP 4, PECL)
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, PECL)
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.
(PHP 3 >= 3.0.13, PHP 4, PECL)
mcal_list_events -- Return a list of IDs for a date or a range of datesReturns 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() 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 stream_id and event_id.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
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, PECL)
mcal_time_valid -- Returns TRUE if the given hour, minutes and seconds 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 http://mcrypt.sourceforge.net/ and follow the included installation instructions. Windows users will find all the needed compiled mcrypt binaries at http://ftp.emini.dk/pub/php/win32/mcrypt/.
As of PHP 5.0.0 you will need libmcrypt Version 2.5.6 or greater.
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.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. Mcrypt configuration options
Name | Default | Changeable | Changelog |
---|---|---|---|
mcrypt.algorithms_dir | NULL | PHP_INI_ALL | Available since PHP 4.0.2. |
mcrypt.modes_dir | NULL | PHP_INI_ALL | Available since PHP 4.0.2. |
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
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.
Esempio 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. The mode should be either MCRYPT_ENCRYPT or MCRYPT_DECRYPT.
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. The mode should be either MCRYPT_ENCRYPT or MCRYPT_DECRYPT.
This function should not be used anymore, see mcrypt_generic() and mdecrypt_generic() for replacements.
(PHP 3 >= 3.0.8, PHP 4, PHP 5)
mcrypt_create_iv -- Create an initialization vector (IV) from a random sourcemcrypt_create_iv() is used to create an IV.
Parameter size determines the size of the IV, parameter source (defaults to random value) 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). MCRYPT_RAND is the only one supported on Windows because Windows (of course) doesn't have /dev/random or /dev/urandom.
Nota: When using MCRYPT_RAND, remember to call srand() before mcrypt_create_iv() to initialize the random number generator; it is not seeded automatically like rand() is.
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 losing 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. The mode should be either MCRYPT_ENCRYPT or MCRYPT_DECRYPT.
This function is deprecated and should not be used anymore, see mcrypt_generic() and mdecrypt_generic() for replacements.
This function returns the name of the algorithm.
Esempio 1. mcrypt_enc_get_algorithms_name() example
Il precedente esempio visualizzerà:
|
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.
(PHP 4 >= 4.0.2, PHP 5)
mcrypt_enc_get_key_size -- Returns the maximum supported keysize of the opened modeThis 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, PHP 5)
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, PHP 5)
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. (e.g. FALSE for stream, and TRUE for cbc, cfb, ofb).
(PHP 4 >= 4.0.2, PHP 5)
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. (e.g. 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'.
Esempio 1. mcrypt_encrypt() Example
Il precedente esempio visualizzerà:
|
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().
Avvertimento |
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.
(PHP 4 >= 4.0.2, PHP 5)
mcrypt_generic_init -- This function initializes all buffers needed for encryptionThe 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, -3 when the key length was incorrect, -4 when there was a memory allocation problem and any other return value is an unknown error. If an error occurs a warning will be displayed accordingly. FALSE is returned if incorrect parameters were passed.
You need to call this function before every call to mcrypt_generic() or mdecrypt_generic().
See for an example mcrypt_module_open().
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.
If you want to store the encrypted data in a database make sure to store the entire string as returned by mcrypt_generic, or the string will not entirely decrypt properly. If your original string is 10 characters long and the block size is 8 (use mcrypt_enc_get_block_size() to determine the blocksize), you would need at least 16 characters in your database field. Note the string returned by mdecrypt_generic() will be 16 characters as well...use rtrim()($str, "\0") to remove the padding.
If you are for example storing the data in a MySQL database remember that varchar fields automatically have trailing spaces removed during insertion. As encrypted data can end in a space (ASCII 32), the data will be damaged by this removal. Store data in a tinyblob/tinytext (or larger) field instead.
The encryption handle should always 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).
It is more useful to use the mcrypt_enc_get_block_size() function as this uses the resource returned by mcrypt_module_open().
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(), mcrypt_enc_get_block_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, PHP 5)
mcrypt_get_iv_size -- Returns the size of the IV belonging to a specific cipher/mode combinationmcrypt_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 or one of "ecb", "cbc", "cfb", "ofb", "nofb" or "stream". The IV is ignored in ECB mode as this mode does not require it. You will need to have the same IV (think: starting point) both at encryption and decryption stages, otherwise your encryption will fail.
It is more useful to use the mcrypt_enc_get_iv_size() function as this uses the resource returned by mcrypt_module_open().
See also mcrypt_get_block_size(), mcrypt_enc_get_iv_size() and 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. It is more useful to use the mcrypt_enc_get_key_size() function as this uses the resource returned by mcrypt_module_open().
Esempio 1. mcrypt_get_block_size() example
|
See also: mcrypt_get_block_size(), mcrypt_end_get_key_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.
Esempio 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, PHP 5)
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, PHP 5)
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, PHP 5)
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, PHP 5)
mcrypt_module_is_block_algorithm_mode -- Returns if 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. (e.g. 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, PHP 5)
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, PHP 5)
mcrypt_module_is_block_mode -- Returns if the specified mode outputs blocks or notThis function returns TRUE if the mode outputs blocks of bytes or FALSE if it outputs just bytes. (e.g. 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, PHP 5)
mcrypt_module_open -- 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, e.g. "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 (usually /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 and mode, this only works when the extension is linked against libmcrypt 2.4.x or 2.5.x.
Esempio 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 and mode, 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().
(PHP 4 >= 4.0.2, PHP 5)
mcrypt_module_self_test -- This function runs a self test on the specified moduleThis 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. The mode should be either MCRYPT_ENCRYPT or MCRYPT_DECRYPT.
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.
Esempio 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 always 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 for Linux / Unix ( http://www.mainstreetsoftworks.com/ ). 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 clientele to the MCVE platform.
Nota: Questo modulo è stato spostato nel repository PECL e non sarà più rilascio con il PHP dalla versione 5.1.0.
Nota: Questo modulo non è disponibile su piattaforme Windows.
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.mainstreetsoftworks.com/.
Additional documentation about MCVE's PHP API can be found at http://www.mainstreetsoftworks.com/docs/phpapi.pdf. Main Street's documentation is complete and should be the primary reference for functions.
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.2.0, PHP 5)
mcve_completeauthorizations -- Number of complete authorizations in queue, returning an array of their identifiers
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.3.0, PHP 5)
mcve_connectionerror -- Get a textual representation of why a connection failed
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.2.0, PHP 5)
mcve_getcell -- Get a specific cell from a comma delimited response by column name
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.2.0, PHP 5)
mcve_getcellbynum -- Get a specific cell from a comma delimited response by column number
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.2.0, PHP 5)
mcve_getcommadelimited -- Get the RAW comma delimited data returned from MCVE
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.3.0, PHP 5)
mcve_maxconntimeout -- The maximum amount of time the API will attempt a connection to MCVE
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.2.0, PHP 5)
mcve_monitor -- Perform communication with MCVE (send/receive data) Non-blocking
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.2.0, PHP 5)
mcve_parsecommadelimited -- Parse the comma delimited response so mcve_getcell, etc will work
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.2.0, PHP 5)
mcve_preauthcompletion -- Complete a PREAUTHORIZATION, ready it for settlement
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.3.3, PHP 5)
mcve_setssl_files -- Set certificate key files and certificates if server requires client certificate verification
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.2.0, PHP 5)
mcve_transactionauth -- Get the authorization number returned for the transaction (alpha-numeric)
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.2.0, PHP 5)
mcve_transactionbatch -- Get the batch number associated with the transaction
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.2.0, PHP 5)
mcve_transactionitem -- Get the ITEM number in the associated batch for this transaction
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.2.0, PHP 5)
mcve_transactiontext -- Get verbiage (text) return from MCVE or processing institution
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.3.0, PHP 5)
mcve_verifyconnection -- Set whether or not to PING upon connect to verify connection
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.3.0, PHP 5)
mcve_verifysslcert -- Set whether or not to verify the server ssl certificate
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Memcache module provides handy procedural and object oriented interface to memcached, highly effective caching daemon, which was especially designed to decrease database load in dynamic web applications.
This module doesn't have native support of multiple servers, but you still can implement it yourself in your application. Establish several memcached connections, set priority level for each server etc.
More information about memcached can be found at http://www.danga.com/memcached/.
This module uses functions of zlib to support on-the-fly data compression. Zlib is required to install this module.
PHP 4.3.3 or newer is required to use the memcache extension.
This PECL extension is not bundled with PHP. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: http://pecl.php.net/package/memcache.
In order to use these functions you must compile PHP with Memcache support by using the --enable-memcache[=DIR] option.
Windows users will enable php_memcache.dll inside of php.ini in order to use these functions. You may download this PECL extension DLL from the PHP Downloads page or at http://snaps.php.net/.
Tabella 1. MemCache Constants
Name | Description |
---|---|
MEMCACHE_COMPRESSED (integer) | Used to turn on-the-fly data compression on with Memcache::set(), Memcache::add() e Memcache::replace(). |
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
There is only one resource type used in memcache module - it's the link identifier for a cache server connection.
Esempio 1. memcache extension overview example
|
In the above example, an object is being saved in the cache and then retrieved back. Object and other non-scalar types are serialized before saving, so it's impossible to store resources (i.e. connection identifiers and others) in the cache.
Memcache::add() stores variable var with key only if such key doesn't exist at the server yet. Memcache::add() returns FALSE if such key already exist. For the rest Memcache::add() behaves similarly to Memcache::set().
Also you can use memcache_add() function. See example below.
Memcache::add() returns TRUE on success or FALSE on failure.
See also Memcache::set(), Memcache::replace().
Memcache::close() closes connection to memcached server. This function doesn't close persistent connections, which are closed only during web-server shutdown/restart.
Also you can use memcache_close() function. See example below.
Esempio 1. Memcache::close() example
|
Memcache::close() returns FALSE if an error occured.
See also Memcache::connect(), Memcache::pconnect().
Memcache::connect() establishes a connection to the memcached server. Parameters host and port point to the host and port, where memcached is listening for connections. Parameter port is optional, it's default value is 11211. Also you can define a timeout (in seconds), which will be used when connecting to the daemon. Think twice before changing the default value - you can loose all the advantages of caching if your connection is too slow.
The connection, which was opened using Memcache::connect() will be automatically closed at the end of script execution. Also you can close it with Memcache::close().
Also you can use memcache_connect() function. See example below.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also Memcache::pconnect() and Memcache::close().
memcache_debug() turns on debug output if parameter on_off is equal to 1 and turns off if it's 0.
Nota: memcache_debug() is accessible only if PHP was built with --enable-debug option and always returns TRUE in this case. Otherwise, this function has no effect and always returns FALSE.
Memcache::decrement() decrements value of the item by value. Similarly to Memcache::increment(), current value of the item is being converted to numerical and after that value is substracted.
Parameter value is optional. It's default is 1.
Nota: New item's value will not be less than zero.
Nota: Do not use Memcache::decrement() with item, which was stored compressed, because consequent call to Memcache::get() will fail.
Also you can use memcache_decrement() function. See example below.
Esempio 1. Memcache::decrement() example
|
Memcache::decrement() does not create an item if it didn't exist.
Memcache::decrement() returns item's new value on success or FALSE on failure.
See also Memcache::increment(), Memcache::replace().
Memcache::delete() deletes item with the key. If parameter timeout is specified, the item will expire after timeout seconds.
Also you can use memcache_delete() function. See example below.
Esempio 1. Memcache::delete() example
|
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
(no version information, might be only in CVS)
Memcache::flush -- Flush all existing items at the serverMemcache::flush() immediately invalidates all existing items. Memcache::flush() doesn't actually free any resources, it only marks all the items as expired, so occupied memory will be overwritten by new items.
Also you can use memcache_flush() function. See example below.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Memcache::get() returns previously stored data if an item with such key exists on the server at this moment.
Esempio 1. Memcache::get() example
|
Memcache::get() returns FALSE on failure or if such key was not found.
Memcache::getStats() returns an associative array with server's statistics. Array keys correspond to stats parameters and values to parameter's values.
Also you can use memcache_get_stats() function.
Memcache::getStats() returns FALSE in case of an error.
See also Memcache::getVersion().
Memcache::getVersion() returns a string with server's version number.
Also you can use memcache_get_version() function. See example below.
Memcache::getVersion() returns FALSE if an error occured.
See also Memcache::getStats().
Memcache::increment() increments value of the item on the specified value. If item with key key was not numeric and cannot be converted to number, it will change it's value to value.
Parameter value is optional. It's default value is 1.
Nota: Do not use Memcache::increment() with item, which was stored compressed, because consequent call to Memcache::get() will fail.
Also you can use memcache_increment() function. See example below.
Esempio 1. Memcache::increment() example
|
Memcache::increment() returns new item's value on success or FALSE on failure.
Memcache::increment() does not create an item if it didn't exist.
See also Memcache::decrement(), Memcache::replace().
(no version information, might be only in CVS)
Memcache::pconnect -- Open memcached server persistent connectionMemcache::pconnect() is similar to Memcache::connect() with the difference, that the connection it establishes is persistent. This connection is not closed after the end of script execution and by Memcache::close() function.
Also you can use memcache_pconnect() function. See example below.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also Memcache::connect().
(no version information, might be only in CVS)
Memcache::replace -- Replace value of the existing itemMemcache::replace() should be used to replace value of existing item with key. In case if item with such key doesn't exists, Memcache::replace() returns FALSE. For the rest Memcache::replace() behaves similarly to Memcache::set().
Also you can use memcache_replace() function. See example below.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also Memcache::set(), Memcache::add().
Memcache::set() stores an item var with key on the memcached server. Parameter expire is expiration time in seconds. If it's 0, the item never expires (but memcached server doesn't guarantee this item to be stored all the time, it could be deleted from the cache to make place for other items).
You can use MEMCACHE_COMPRESSED constant as flag value if you want to use on-the-fly compression (uses zlib).
Also you can use memcache_set() function. See example below.
Nota: Remember that resource variables (i.e. file and connection descriptors) cannot be stored in the cache, because they cannot be adequately represented in serialized state.
Esempio 1. Memcache::set() example
|
Esempio 2. Memcache::set() example
|
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also Memcache::add(), Memcache::replace().
These functions are intended to work with mhash. Mhash can be used to create checksums, message digests, message authentication codes, and more.
This is an interface to the mhash library. mhash supports a wide variety of hash algorithms such as MD5, SHA1, GOST, and many others. For a complete list of supported hashes, refer to the documentation of mhash. The general rule is that you can access the hash algorithm from PHP with MHASH_HASHNAME. For example, to access TIGER you use the PHP constant MHASH_TIGER.
To use it, download the mhash distribution from its web site and follow the included installation instructions.
You need to compile PHP with the --with-mhash[=DIR] parameter to enable this extension. DIR is the mhash install directory.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Here is a list of hashes which are currently supported by mhash. If a hash is not listed here, but is listed by mhash as supported, you can safely assume that this documentation is outdated.
MHASH_ADLER32
MHASH_CRC32
MHASH_CRC32B
MHASH_GOST
MHASH_HAVAL128
MHASH_HAVAL160
MHASH_HAVAL192
MHASH_HAVAL256
MHASH_MD4
MHASH_MD5
MHASH_RIPEMD160
MHASH_SHA1
MHASH_SHA256
MHASH_TIGER
MHASH_TIGER128
MHASH_TIGER160
Esempio 1. Compute the MD5 digest and hmac and print it out as hex
This will produce:
|
mhash_count() returns the highest available hash id. Hashes are numbered from 0 to this hash id.
mhash_get_block_size() is used to get the size of a block of the specified hash.
mhash_get_block_size() takes one argument, the hash and returns the size in bytes or FALSE, if the hash does not exist.
mhash_get_hash_name() is used to get the name of the specified hash.
mhash_get_hash_name() takes the hash id as an argument and returns the name of the hash or FALSE, if the hash does not exist.
mhash_keygen_s2k() generates a key that is bytes long, from a user given password. This is the Salted S2K algorithm as specified in the OpenPGP document (RFC 2440). That algorithm will use the specified hash algorithm to create the key. The salt must be different and random enough for every key you generate in order to create different keys. That salt must be known when you check the keys, thus it is a good idea to append the key to it. Salt has a fixed length of 8 bytes and will be padded with zeros if you supply less bytes.
Keep in mind that user supplied passwords are not really suitable to be used as keys in cryptographic algorithms, since users normally choose keys they can write on keyboard. These passwords use only 6 to 7 bits per character (or less). It is highly recommended to use some kind of transformation (like this function) to the user supplied key.
mhash() applies a hash function specified by hash to the data and returns the resulting hash (also called digest). If the key is specified it will return the resulting HMAC. HMAC is keyed hashing for message authentication, or simply a message digest that depends on the specified key. Not all algorithms supported in mhash can be used in HMAC mode. In case of an error returns FALSE.
Avvertimento |
This extension has been deprecated as the PECL extension fileinfo provides the same functionality (and more) in a much cleaner way. |
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 derived from Apache mod_mime_magic, which is itself based on the file command maintained by Ian F. Darwin. See the source code for further historic and copyright information.
You must compile PHP with the configure switch --with-mime-magic to get support for mime-type functions. The extension needs a copy of the simplified magic file that is distributed with the Apache httpd.
Nota: The configure option has been changed from --enable-mime-magic to --with-mime-magic since PHP 4.3.2
Nota: This extension is not capable of handling the fully decorated magic file that generally comes with standard Linux distro's and is supposed to be used with recent versions of file command.
Note to Win32 Users: In order to use this module on a Windows environment, you must set the path to the bundled magic.mime file in your php.ini.
Remember to substitute the $PHP_INSTALL_DIR for your actual path to PHP in the above example. e.g. c:\php
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. Mimetype configuration options
Name | Default | Changeable | Changelog |
---|---|---|---|
mime_magic.debug | "0" | PHP_INI_SYSTEM | Available since PHP 5.0.0. |
mime_magic.magicfile | "/path/to/php/magic.mime" | PHP_INI_SYSTEM | Available since PHP 4.3.0. |
Breve descrizione dei parametri di configurazione.
Avvertimento |
Questo modulo è SPERIMENTALE. Ovvero, il comportamento di queste funzioni, i nomi di queste funzioni, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questo modulo è a vostro rischio. |
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.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Queste classi sono definite da questa estensione, e sono disponibili solo quando l'estensione è stata compilata nel PHP o caricata come modulo dinamico al runtime.
Ming introduces 13 new objects in PHP, all with matching methods and attributes. To use them, you need to know about objects.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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.
Esempio 1. swfaction() example
|
This simple example tracks down your mouse on the screen.
Esempio 2. swfaction() example
|
Same as above, but with nice colored balls...
Esempio 3. swfaction() example
|
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfbitmap->getheight() returns the bitmap's height in pixels.
See also swfbitmap->getwidth().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfbitmap->getwidth() returns the bitmap's width in pixels.
See also swfbitmap->getheight().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfbitmap() creates a new SWFBitmap object from the Jpeg or DBL file in file. alphafile is a MSK file to be used as an alpha mask for a Jpeg image. Both parameters can be fopen() resources or binary strings.
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.
Esempio 1. Import PNG files
|
And you can put an alpha mask on a jpeg fill.
Esempio 2. swfbitmap() example
|
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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)Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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)Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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)Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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)Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfbutton->setup() alias for addShape(shape, SWFBUTTON_UP).
See also swfbutton->addshape() and swfaction().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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.
Esempio 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.
Esempio 2. swfbutton->addaction() example
|
(no version information, might be only in CVS)
SWFDisplayItem->addColor -- Adds the given color to this item's color transformAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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 coordinatesAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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 coordinatesAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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 transformAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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 atmosphere to Halloween (use a landscape or bright picture).
Esempio 1. swfdisplayitem->multcolor() example
|
(no version information, might be only in CVS)
SWFDisplayItem->remove -- Removes the object from the movieAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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 coordinatesAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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 coordinatesAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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.
Esempio 1. swfdisplayitem->rotateto() example
|
See also swfdisplayitem->rotate().
(no version information, might be only in CVS)
SWFDisplayItem->scale -- Scales the object in relative coordinatesAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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 coordinatesAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfdisplayitem->setdepth() sets the object's z-order to depth. Depth defaults to the order in which instances are created (by adding 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().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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.
Esempio 1. swfdisplayitem->setname() example
|
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swffill->moveto() moves fill's origin to (x,y) in global coordinates.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swffill->rotateto() sets fill's rotation to degrees degrees.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swffill->scaleto() sets fill's scale to x in the x-direction, y in the y-direction.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swffill->skewxto() sets fill x-skew to x. For x is 1.0, it is a 45-degree forward slant. More is more forward, less is more backward.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swffill->skewyto() sets fill y-skew to y. For y is 1.0, it 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().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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 listAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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 reddish disc in its center.
Esempio 1. swfgradient() example
|
(no version information, might be only in CVS)
SWFMorph->getshape1 -- Gets a handle to the starting shapeAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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 shapeAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfmorph->getshape2() gets a handle to the morph's ending shape. swfmorph->getshape2() returns an swfshape() object.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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.
Esempio 1. swfmorph() example
|
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfmovie->add() adds instance to the current movie. instance is any type of data : Shapes, text, fonts, etc. must all be added 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 animationAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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 outAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfmovie->output() dumps your lovingly prepared movie out. In PHP, preceding this with the command
<?php header('Content-type: application/x-shockwave-flash'); ?> |
The compression level can be a value between 0 and 9, defining the swf compression similar to gzip compression.
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 listAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfmovie->remove() removes the object instance instance from the display list.
See also swfmovie->add().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfmovie->save() saves your movie to the file named filename.
The compression level can be a value between 0 and 9, defining the swf compression similar to gzip compression.
See also swfmovie->output().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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 heightAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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 animationAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfmovie->setframes() sets the total number of frames in the animation to numberofframes.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfmovie->streammp3() streams the mp3 file mp3File. 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. Parameter mp3File can be a fopen() resource or a binary string.
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.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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, SWFFILL_TILED_BITMAP, SWFFILL_LINEAR_GRADIENT or SWFFILL_RADIAL_GRADIENT. Default is SWFFILL_TILED_BITMAP for SWFBitmap and SWFFILL_LINEAR_GRADIENT for SWFGradient.
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.
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..
Esempio 1. SWFShape->addFill() example
|
See also SWFShape->setLeftFill() and SWFShape->setRightFill().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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.
With 6 parameters, it draws a cubic bezier to point (x+targetdx, x+targetdy) with control points (x+controldx, y+controldy) and (x+anchordx, y+anchordy).
See also swfshape->drawlineto(), swfshape->drawline(), swfshape->movepento() and swfshape->movepen().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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.
With 6 parameters, it draws a cubic bezier to point (targetx, targety) with control points (controlx, controly) and (anchorx, anchory).
See also swfshape->drawlineto(), swfshape->drawline(), swfshape->movepento() and swfshape->movepen().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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.
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.
Esempio 1. swfshape->setline() example
|
(no version information, might be only in CVS)
SWFShape->setRightFill -- Sets right rasterizing colorAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
See also swfshape->setleftfill().
Shortcut for swfshape->setrightfill($s->addfill($r, $g, $b [, $a]));.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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.
Esempio 1. swfshape() example
|
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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 animationAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfsprite->setframes() moves to the next frame of the animation.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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 animationAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swfsprite->setframes() sets the total number of frames in the animation to numberofframes.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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.
Esempio 1. swfsprite() example
|
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swftext->addstring() returns the rendered width of the string string at the text object's current font, scale, and spacing settings.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swftext->setspacing() changes the current text color. Default is black. I think. Color is represented using the RGB system.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swftext->setfont() sets the current font to font.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swftext->setheight() sets the current font height to height. Default is 240.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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.
Esempio 1. swftext() example
|
(no version information, might be only in CVS)
SWFTextField->addstring -- Concatenates the given string to the text fieldAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swftextfield->setname() concatenates the string string to the text field.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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 heightAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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 fieldAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swftextfield->setcolor() sets the color of the text field. Default is fully opaque black. Color is represented using RGB system.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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 fontAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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 lineAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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 fieldAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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 fieldAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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 fieldAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swftextfield->setmargins() set both margins at once, for the man on the go.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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 fieldAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
swftextfield->setrightmargin() sets the right margin width of the text field to width. Default is 0.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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().
These functions were placed here because none of the other categories seemed to fit.
Non è necessaria nessuna installazione per usare queste funzioni, esse fanno parte del core di PHP.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. Misc. Configuration Options
Name | Default | Changeable | Changelog |
---|---|---|---|
ignore_user_abort | "0" | PHP_INI_ALL | |
highlight.string | "#DD0000" | PHP_INI_ALL | |
highlight.comment | "#FF8000" | PHP_INI_ALL | |
highlight.keyword | "#007700" | PHP_INI_ALL | |
highlight.bg | "#FFFFFF" | PHP_INI_ALL | |
highlight.default | "#0000BB" | PHP_INI_ALL | |
highlight.html | "#000000" | PHP_INI_ALL | |
browscap | NULL | PHP_INI_SYSTEM |
Breve descrizione dei parametri di configurazione.
TRUE by default. If changed to FALSE scripts will be terminated as soon as they try to output something after a client has aborted their connection.
See also ignore_user_abort().
Colors for Syntax Highlighting mode. Anything that's acceptable in <font color="??????"> would work.
Name (e.g.: browscap.ini) and location of browser capabilities file. See also get_browser().
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Returns TRUE if client disconnected. See the Connection Handling description in the Features chapter for a complete explanation.
See also connection_status(), and ignore_user_abort().
Returns the connection status bitfield. See the Connection Handling description in the Features chapter for a complete explanation.
See also connection_aborted(), and ignore_user_abort().
Returns TRUE if script timed out.
Deprecated |
This function is deprecated, and doesn't even exist anymore as of 4.0.5. |
See the Connection Handling description in the Features chapter for a complete explanation.
See also connection_status().
constant() will return the value of the constant indicated by name.
constant() is useful if you need to retrieve the value of a constant, but do not know its name. I.e. it is stored in a variable or returned by a function.
This function works also with class constants.
Defines a named constant. See the section on constants for more details.
The name of the constant is given by name; the value is given by value.
The optional third parameter case_insensitive is also available. If the value TRUE is given, then the constant will be defined case-insensitive. The default behaviour is case-sensitive; i.e. CONSTANT and Constant represent different values.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also defined(), constant() and the section on Constants.
Returns TRUE if the named constant given by name has been defined, FALSE otherwise.
Nota: If you want to see if a variable exists, use isset() as defined() only applies to constants. If you want to see if a function exists, use function_exists().
See also define(), constant(), get_defined_constants(), function_exists(), and the section on Constants.
eval() evaluates the string given in code_str as PHP code. Among other things, this can be useful for storing code in a database text field for later execution.
There are some factors to keep in mind when using eval(). Remember that the string passed must be valid PHP code, including things like terminating statements with a semicolon so the parser doesn't die on the line after the eval(), and properly escaping things in code_str.
Also remember that variables given values under eval() will retain these values in the main script afterwards.
A return statement will terminate the evaluation of the string immediately. As of PHP 4, eval() returns NULL unless return is called in the evaluated code, in which case the value passed to return is returned. In case of a parse error in the evaluated code, eval() returns FALSE. In case of a fatal error in the evaluated code, the whole script exits. In PHP 3, eval() does not return a value.
Esempio 1. eval() example - simple text merge
Il precedente esempio visualizzerà:
|
Suggerimento: Come con qualsiasi cosa che invia il risultato direttamente al browser, è possibile utilizzare la funzione output-control per catturare l'uscita di questa funzione e salvarla - per esempio - in una stringa.
See also call_user_func().
Nota: This is not a real function, but a language construct.
Nota: PHP >= 4.2.0 does NOT print the status if it is an integer.
The exit() function terminates execution of the script. It prints status just before exiting.
If status is an integer, that value will also be used as the exit status. Exit statuses should be in the range 0 to 254, the exit status 255 is reserved by PHP and shall not be used. The status 0 is used to terminate the program successfully.
Nota: The die() function is an alias for exit().
See also: register_shutdown_function().
get_browser() attempts to determine the capabilities of the user's browser. This is done by looking up the browser's information in the browscap.ini file.
By default, the value of HTTP User-Agent header is used; however, you can alter this (i.e., look up another browser's info) by passing the optional user_agent parameter to get_browser(). You can bypass user_agent parameter with NULL value.
The information is returned in an object, which will contain various data elements representing, for instance, the browser's major and minor version numbers and ID string; TRUE/FALSE values for features such as frames, JavaScript, and cookies; and so forth.
As of PHP 4.3.2, if the optional parameter return_array is TRUE, this function will return an array instead of an object.
Esempio 1. Listing all information about the users browser
Il precedente esempio visualizzerà qualcosa simile a:
|
The cookies value simply means that the browser itself is capable of accepting cookies and does not mean the user has enabled the browser to accept cookies or not. The only way to test if cookies are accepted is to set one with setcookie(), reload, and check for the value.
Nota: In order for this to work, your browscap configuration setting in php.ini must point to the correct location of the browscap.ini file on your system.
browscap.ini is not bundled with PHP, but you may find an up-to-date php_browscap.ini file here.
While browscap.ini contains information on many browsers, it relies on user updates to keep the database current. The format of the file is fairly self-explanatory.
This function halts the execution of the compiler. This can be useful to embed data in PHP scripts, like the installation files. Byte position of the data start can be determined by the __COMPILER_HALT_OFFSET__ constant which is defined only if there is a __halt_compiler() presented in the file.
Nota: __halt_compiler() can only be used from the outermost scope.
Esempio 1. A __halt_compiler() example
|
The highlight_file() function prints out a syntax highlighted version of the code contained in filename using the colors defined in the built-in syntax highlighter for PHP.
If the second parameter return is set to TRUE then highlight_file() will return the highlighted code as a string instead of printing it out. If the second parameter is not set to TRUE then highlight_file() will return TRUE on success, FALSE on failure.
Nota: The return parameter became available in PHP 4.2.0. Before this time it behaved like the default, which is FALSE
Nota: Since PHP 4.2.1 this function is also affected by safe_mode and open_basedir.
Attenzione |
Care should be taken when using the highlight_file() function to make sure that you do not inadvertently reveal sensitive information such as passwords or any other type of information that might create a potential security risk. |
Many servers are configured to automatically highlight files with a phps extension. For example, example.phps when viewed will show the syntax highlighted source of the file. To enable this, add this line to the httpd.conf:
AddType application/x-httpd-php-source .phps |
See also highlight_string().
The highlight_string() function outputs a syntax highlighted version of str using the colors defined in the built-in syntax highlighter for PHP.
If the second parameter return is set to TRUE then highlight_string() will return the highlighted code as a string instead of printing it out. If the second parameter is not set to TRUE then highlight_string() will return TRUE on success, FALSE on failure.
Esempio 1. highlight_string() example
The above example will output (in PHP 4):
The above example will output (in PHP 5):
|
Nota: The return parameter became available in PHP 4.2.0. Before this time it behaved like the default, which is FALSE
See also highlight_file().
(PHP 3 >= 3.0.7, PHP 4, PHP 5)
ignore_user_abort -- Set whether a client disconnect should abort script executionThis function sets whether a client disconnect should cause a script to be aborted. It will return the previous setting and can be called without an argument to not change the current setting and only return the current setting. See the Connection Handling section in the Features chapter for a complete description of connection handling in PHP.
See also connection_aborted(), and connection_status().
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
Tabella 1. pack() format characters
Code | Description |
---|---|
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.
See also unpack().
For technical reasons, this function is deprecated and removed from PHP. Instead, use php -l somefile.php from the commandline.
The php_check_syntax() function performs a syntax (lint) check on the specified filename testing for scripting errors. This is similar to using php -l from the commandline except php_check_syntax() will execute (but not output) the checked file_name. For example, if a function is defined in file_name, this defined function will be available to the file that executed php_check_syntax(), but output from file_name will be suppressed.
The name of the file being checked.
If the error_message parameter is used, it will contain the error message generated by the syntax check. error_message is passed by reference.
Returns TRUE if the lint check passed, and FALSE if the link check failed or if file_name cannot be opened.
Versione | Descrizione |
---|---|
5.0.5 | This function was removed from PHP. |
5.0.3 | Calling exit() after php_check_syntax() resulted in a Segfault. |
5.0.1 | error_message is passed by reference. |
php -l somefile.php |
Il precedente esempio visualizzerà qualcosa simile a:
PHP Parse error: unexpected T_STRING in /tmp/somefile.php on line 81 |
Returns the PHP source code in filename with PHP comments and whitespace removed. This may be useful for determining the amount of actual code in your scripts compared with the amount of comments. This is similar to using php -w from the commandline.
Nota: This function works as described as of PHP 5.0.1. Before this it would only return an empty string. For more information on this bug and its prior behavior, see bug report #29606.
The stripped source code will be returned on success, or an empty string on failure.
Esempio 1. php_strip_whitespace() example
Il precedente esempio visualizzerà:
Notice the PHP comments are gone, as are the whitespace and newline after the first echo statement. |
The sleep() function delays program execution for the given number of seconds.
See also usleep() and set_time_limit()
Delays program execution for the given number of seconds and nanoseconds.
seconds must be a positive integer, and nanoseconds must be a positive integer less than 1 billion.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
If the delay was interrupted by a signal, an associative array will be returned with the components:
seconds - number of seconds remaining in the delay
nanoseconds - number of nanoseconds remaining in the delay
Esempio 1. time_nanosleep() example
|
Nota: Questa funzione non è implementata su piattaforme Windows
This function will make the script sleep until the specified timestamp. If the specified timestamp is in the past, time_sleep_until() will generate a E_WARNING and return FALSE.
Nota: Questa funzione non è implementata su piattaforme Windows
uniqid() returns a prefixed unique identifier based on the current time in microseconds. prefix is optional but can be useful, for instance, if you generate identifiers simultaneously on several hosts that might happen to generate the identifier at the same microsecond. Up until PHP 4.3.1, prefix could only be a maximum of 114 characters long.
If the optional more_entropy parameter is TRUE, uniqid() will add additional entropy (using the combined linear congruential generator) at the end of the return value, which should make the results more unique.
With an empty prefix, the returned string will be 13 characters long. If more_entropy is TRUE, it will be 23 characters.
Nota: The prefix parameter became optional in PHP 5.
If you need a unique identifier or token and you intend to give out that token to the user via the network (i.e. session cookies), it is recommended that you use something along these lines:
<?php // no prefix $token = md5(uniqid()); // better, difficult to guess $better_token = md5(uniqid(rand(), true)); ?> |
This will create a 32 character identifier (a 128 bit hex number) that is extremely difficult to predict.
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 /.
Attenzione |
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. |
See also pack() for an explanation of the format codes.
The usleep() function delays program execution for the given number of micro_seconds. A microsecond is one millionth of a second.
Nota: This function did not work on Windows systems until PHP 5.0.0
See also sleep() and set_time_limit().
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.org/.
Nota: Questo modulo è stato spostato nel repository PECL e non sarà più rilascio con il PHP dalla versione 5.1.0.
Nota: Questo modulo non è disponibile su piattaforme Windows.
Download mnoGosearch from http://www.mnogosearch.org/ 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.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
udm_add_search_limit() adds search restrictions. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
agent - a link to Agent, received after call to udm_alloc_agent().
var - defines parameter, indicating limit.
val - defines the value of the current parameter.
Possible var values:
UDM_LIMIT_URL - defines document URL limitations to limit the search through subsection of the database. It supports SQL % and _ LIKE wildcards, where % matches any number of characters, even zero characters, and _ matches exactly one character. E.g. http://www.example.___/catalog may stand for http://www.example.com/catalog and http://www.example.net/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 the document was modified.
Format of parameter value: a string with first character < or >, then with no space - date in unixtime format, for example:
If > character is used, then the search will be restricted to those documents having a modification date greater than entered, if <, then smaller.
udm_alloc_agent_array() will create an agent with multiple database connections. The array databases must contain one database URL per element, analog to the first parameter of udm_alloc_agent().
See also: udm_alloc_agent().
Returns a mnogosearch agent identifier on success, FALSE on failure. This function creates a session with database parameters.
dbaddr - URL-style database description, with options (type, host, database name, port, user and password) to connect to SQL database. Do not matter for built-in text files support. Format for dbaddr: DBType:[//[DBUser[:DBPass]@]DBHost[:DBPort]]/DBName/. Currently supported DBType values are: mysql, pgsql, msql, solid, mssql, oracle, and ibase. Actually, it does not matter for native libraries support, but ODBC users should specify one of the supported values. If your database type is not supported, you may use unknown instead.
dbmode - You may select the SQL database mode of words storage. Possible values of dbmode are: single, multi, crc, or crc-multi. 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 the database. If "crc" mode is selected, mnoGoSearch will store 32 bit integer word IDs calculated by CRC32 algorithm instead of words. This mode requires 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 in "multi" mode.
Nota: dbaddr and dbmode must match those used during indexing.
Nota: In fact this function does not open a connection to the database and thus does not check the entered login and password. Establishing a connection to the database and login/password verification is done by udm_find().
udm_api_version() returns the mnoGoSearch API version number. E.g. if mnoGoSearch 3.1.10 API is used, this function will return 30110.
This function allows the 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.
(PHP 4 >= 4.0.6, PHP 5 <= 5.0.4)
udm_cat_list -- Get all the categories on the same level with the current oneReturns an array listing all categories of the same level as the current category in the categories tree. agent is the agent identifier returned by a previous call to >udm_alloc_agent().
The function can be useful for developing categories tree browser.
The returned array consists of pairs. Elements with even index numbers contain the category paths, odd elements contain the 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 ... |
See also udm_cat_path().
Returns an array describing the path in the categories tree from the tree root to the current one, specified by category. agent is the agent identifier returned by a previous call to >udm_alloc_agent().
The returned array consists of pairs. Elements with even index numbers contain the category paths, odd elements contain the 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' |
Esempio 1. Specifying path to the current category in the following format: '> Root > Sport > Auto > Ferrari'
|
See also udm_cat_list().
(PHP 4 >= 4.2.0, PHP 5 <= 5.0.4)
udm_check_charset -- Check if the given charset is known to mnogosearch
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.0.5, PHP 5 <= 5.0.4)
udm_clear_search_limits -- Clear all mnoGoSearch search restrictionsudm_clear_search_limits() resets defined search limitations and returns TRUE.
See also udm_add_search_limit().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
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.
Returns a result link identifier on success, or FALSE on failure.
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.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
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.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
res - a link to result identifier, received after call to udm_find().
Freeing up memory allocated for results.
udm_get_doc_count() returns the number of documents in the 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_hash32() will take a string str and return a quite unique 32-bit hash number from it. Requires an allocated agent.
See also: udm_alloc_agent().
udm_load_ispell_data() loads ispell data. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
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 should 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().
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.
Esempio 2. udm_load_ispell_data() example
|
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.
<?php 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:
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Restituisce TRUE in caso di successo, FALSE in caso di fallimento. 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 aggregate 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 omitted, 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 crosswords 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.
Queste funzioni permettono di accedere ad un database MS SQL Server.
Requisiti per le piattaforme Win32
Per potere funzionare è richiesto che sia installato il MS SQL Client Tools sullo stesso sistema su cui è il installato il PHP. Il Client Tools può essere installato o dal cd di MS SQL Server, o copiando il file ntwdblib.dll dalla directory \winnt\system32 del server alla directory \winnt\system32 della macchina su cui è installato il PHP. La copia del file ntwdblib.dll permette solo l'accesso al database. La configurazione del client richiede comunque l'installazione di tutto il pacchetto MS SQL Client Tools.
Requisiti per le piattaforme Unix/Linux
Per potere utilizzare l'estensione MSSQl su piattaforme Unix/Linux, occorre compilare ed installare la libreria FreeTDS. Il codice sorgente e le istruzioni per l'installazione sono disponibili nel sito di FreeTDS: http://www.freetds.org/
Nota: Nella piattaforma Windows si utilizzano le DBLIB di Microsoft. Quindi le funzioni che restituiscono il nome della colonna si basano sulla funzione dbcolname() della DBLIB. La DBLIB è stata sviluppata per SQL Server 6.x che ammetteva nomi di colonna lunghi al massimo 30 caratteri. Per questo motivo il numero massimo di caratteri per il nome colonna ammessi sono 30. Nelle piattaforme in cui si utilizza FreeTDS (Linux) non si ha questo problema.
Il modulo MSSQL si abilita aggiungendo extension=php_mssql.dll al file di configurazione php.ini.
Per attivare queste funzionalità occorre compilare il PHP con --with-mssql[=DIR], dove DIR è la directory in cui è installato FreeTDS. Il pacchetto FreeTDS dovrebbe essere compilato utilizzando --enable-msdblib.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. Parametri di configurazione per il modulo MS SQL Server
Nome | Default | Modificabile | Log Variazioni |
---|---|---|---|
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 | Disponibile da PHP 4.1.0 |
mssql.textsize | "-1" | PHP_INI_ALL | |
mssql.textlimit | "-1" | PHP_INI_ALL | |
mssql.batchsize | "0" | PHP_INI_ALL | Disponibile da PHP 4.0.4 |
mssql.datetimeconvert | "1" | PHP_INI_ALL | Disponibile da PHP 4.2.0 |
mssql.secure_connection | "0" | PHP_INI_SYSTEM | Disponibile da PHP 4.3.0 |
mssql.max_procs | "25" | PHP_INI_ALL | Disponibile da PHP 4.3.0 |
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
(PHP 4 >= 4.1.0, PHP 5)
mssql_bind -- Aggiunge un parametro ad una procedura memorizzata (stored procedure) locale o remotaAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Vedere anche mssql_execute(), mssql_free_statement() e mssql_init().
La funzione mssql_close() chiude la connessione ad un database MS SQL Server che è associata all' argomento id_connessione. Se l' id_connessione non viene indicato, si fa riferimento all'ultima connessione aperta.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: solitamente non è necessario l'uso della funzione, dato che tutte le connessioni non-persistenti sono chiuse automaticamente al termine dell'esecuzione dello script.
mssql_close() non chiude i collegamenti persistenti aperti utilizzando mssql_pconnect().
Vedere anche: mssql_connect() e mssql_pconnect().
Restituisce: un identificativo di connessione MS SQL se l'operazione riesce, oppure FALSE se si verifica un errore.
La funzione mssql_connect() realizza una connessione con un server MS SQL. L' argomento nome_server deve essere un nome valido di server come definito nel file 'interfaces'.
Qualora la funzione mssql_connect() venga eseguita una seconda volta con i medesimi parametri, non viene realizzata una nuova connessione, ma, invece, viene restituito l'identificativo della connessione già aperta.
La connessione con il server verrà chiusa non appena lo script terminerà l'esecuzione, a meno che la connessione non sia già stata chiusa utilizzando la funzione mssql_close().
Vedere anche mssql_pconnect(), e mssql_close().
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
La funzione mssql_data_seek() sposta il puntatore di riga, interno al risultato associato all'identificativo di risultato, alla riga indicata dall'argomento numero_riga, la prima riga inzia con il numero 0. La chiamata successiva a mssql_fetch_row() restituirà la riga richiesta.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Nota: Se le stored procedure restituiscono parametri oppure valori, questi saranno disponibili successivamente all'esecuzione della funzione mssql_execute() a meno che non sia restituito più di un set di risultati. In questo caso occorre utilizzare mssql_next_result() per spostarsi tra i risultati. Una volta terminato lo scorrimento dei set di risultati, sia i parametri di output sia i valori di ritorno saranno disponibili.
Vedere anche mssql_bind(), mssql_free_statement() e mssql_init().
(PHP 3, PHP 4, PHP 5)
mssql_fetch_array -- Restituisce una riga in un array associativo, numerico o entrambiLa funzione restituisce: un array corrispondente alla riga estratta, oppure falso se non vi sono più righe.
La funzione mssql_fetch_array() è un' estensione della funzione mssql_fetch_row(). Oltre a memorizzare i dati in un array con indice numerico, la funzione memorizza i dati in un array associativo in cui la chiave è costituita dal nome del campo.
Un aspetto da notare è che la funzione mssql_fetch_array() NON è significativamente più lenta rispetto a mssql_fetch_row(), mentre nel contempo fornisce funzionalità maggiori.
Nota: I nomi dei campi restituiti da questa funzione sono case-sensitive.
Nota: This function sets NULL fields to PHP NULL value.
Per ulteriori dettagli vedere anche mssql_fetch_row().
(PHP 4 >= 4.2.0, PHP 5)
mssql_fetch_assoc -- Restituisce un array associativo con i dati di una riga dal set di risultati indicato da id_risultatoAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
La funzione restituisce un oggetto contenente le informazioni sul campo.
La funzione mssql_fetch_field() può essere utilizzata per ottenere informazioni sui campi presenti nel risultato di una certa query. Se non viene specificato l'argomento offset_campo, la funzione restituisce il campo successivo che non è ancora stato restituito da mssql_fetch_field().
Le proprietà dell'oggetto sono:
name - nome della colonna. Se la colonna è il risultato di una funzione, questa proprietà è valorizzata con "computed#N", dove #N è un numero progressivo.
column_source - tabella da cui sono ricavate le colonne
max_length - lunghezza massima della colonna
numeric - 1 se la colonna è numerica
type - tipo di colonna.
Vedere anche mssql_field_seek().
La funzione restituisce un oggetto le cui proprietà corrispondono alla riga estratta, oppure falso se non vi sono più righe.
La funzione mssql_fetch_object() è simile a mssql_fetch_array(), tranne che per una differenza, la prima restituisce un oggetto, la seconda un array. Indirettamente questo significa che si può accedere ai dati solo attraverso il nome dei campi e non tramite il loro offset (i numeri non sono dei validi nomi di proprietà).
Nota: I nomi dei campi restituiti da questa funzione sono case-sensitive.
Nota: This function sets NULL fields to PHP NULL value.
A livello di velocità il comportamento è simile a mssql_fetch_array(), e quasi veloce come mssql_fetch_row() (la differenza è insignificante ).
Vedere anche mssql_fetch_array() e mssql_fetch_row().
La funzione restituisce un array che corrisponde alla riga estratta, oppure falso se non vi sono più righe.
La funzione mssql_fetch_row() estrae una riga di dati dal risultato associato all'identificativo di risultato passato. La riga viene restituita in un array. Ciascuna colonna è memorizzata in un campo dell'array. Il primo ha indice 0.
Esecuzione successive di mssql_fetch_row() restituiscono le righe successive presenti nel risultato, oppure falso se non vi sono più righe.
Nota: This function sets NULL fields to PHP NULL value.
Vedere anche mssql_fetch_array(), mssql_fetch_object(), mssql_data_seek(), mssql_fetch_lengths() e mssql_result().
Questa funzione restituisce il valore del campo numero offset dalla query indicata da result. Se si omette offset la funzione resituisce il valore per il campo corrente.
Nota per gli utenti Win32: A causa delle limitazione delle sottostanti API utilizzate dal PHP (MS DbLib C API), la lunghezza dei campi VARCHAR è limitata a 255. Se si ha necessità di memorizzare maggiori informazioni, utilizzare il tipo TEXT
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Si posiziona sul campo richiesto. Eseguendo successivamente la funzione mssql_fetch_field() senza indicare alcun campo, quest'ultima restituirà il campo richiesto tramite mssql_fetch_field().
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere anche mssql_fetch_field().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
E' necessario l'utilizzo della funzione mssql_free_result() solo quando si è preoccupati dell'occupazione di memoria durante l'esecuzione dello script. Normalmente tutti i dati verranno rimossi automaticamente dalla memoria al termine dell'esecuzione dello script.E' tuttavia possibile eseguire mssql_free_result(), per liberare la memoria occupata dai dati indicati dal parametro id_risultato
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()
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.1.0, PHP 5)
mssql_guid_string -- Converte il GUID dal formato binario a 16 bit al formato stringaAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Vedere anche: mssql_bind(), mssql_execute() e mssql_free_statement()
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Nel caso in cui si eseguano più di una istruzione SQL al server, oppure si eseguano delle procedure memorizzate (stored procedure) con possibilità di molteplici risultati, il server restituirà un set di diversi risultati. Questa funzione verifica se esistono ulteriori risultati dal server. Se effettivamente esiste un'altro risultato, questa funzione libera la memoria dal risultato corrente e si predispone per la ricezione del risultato successivo. La funzione restituisce TRUE se è disponibile un'altro risultato, FALSE in caso contrario.
Esempio 1. mssql_next_result() Esempio di utilizzo
|
La funzione mssql_num_fields() restituisce il numero di campi presenti in un risultato.
Vedere anche: mssql_query(), mssql_fetch_field() e mssql_num_rows().
La funzione mssql_num_rows() restituisce il numero di righe presenti in un risultato.
Vedere anche: mssql_query() e mssql_fetch_row().
La funzione restituisce: o un identificativo di connessione persistente, o FALSE se si verifica un errore.
La funzione mssql_pconnect() agisce come mssql_connect() tranne che per due differenze.
Prima differenza, quando si cerca di stabilire la connessione, la funzione per prima cosa cerca di trovare una connessione (persistente) già aperta verso lo stesso server, con i medesimi utenti e password. Se ne viene trovata una, la funzione restituisce l'identificativo di quella connessione, invece di stabilirne una nuova.
Seconda differenza, la connessione con il server SQL non verrà chiusa al termine dello script. Il collegamento resterà aperto per utilizzi futuri (la funzione mssql_close() non chiude i collegamenti aperti da mssql_pconnect()).
Per questo motivo questo tipo di collegamento viene definito 'persistente'.
La funzione restituisce un identificativo di risultato in caso di esecuzione corretta, TRUE se non sono restituite reighe, oppure falso in caso di errore.
La funzione mssql_query() invia una query al database attivo sul server attraverso la connessione specificata da id_connessione. Se l'argomento id_connessione non viene fornito, si utilizza l'ultima connessione aperta in ordine di tempo. Se non vi sono connessioni aperte, la funzione tenta di stabilire una connessione, come se fosse utilizzata la funzione mssql_connect(), e utilizza quella.
Vedere anche: mssql_select_db() e mssql_connect().
La funzione mssql_result() restituisce il contenuto di una cella da un risultato di una query a MS SQL. L'argomento campo può essere la posizione di un campo, oppure il suo nome, oppure nome tabella punto nome campo ( nome_tabella.nome_campo ). Se il nome della colonna ha un sostituto, ('select foo as bar from...'), usare quello anzichè il nome originale.
Quando si lavora con risultati abbastanza grossi, si dovrebbe considerare l'utilizzo di funzioni che restituiscono l'intera riga ( indicate di seguito ), dato che queste restituiscono il contenuto di molte celle in una chiamata sola. Pertanto sono MOLTO più veloci di mssql_result(). Da notare inoltre, che specificando la posizione per l'argomento campo, la funzione è molto più veloce rispetto al caso in cui si indica il nome del campo o della tabella.
Le alternative più veloci raccomandate sono: mssql_fetch_row(), mssql_fetch_array(), e mssql_fetch_object().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
La funzione mssql_select_db() setta il database attivo sul server attraverso la connessione specificata da id_connessione. Se l'argomento id_connessione non viene fornito, si utilizza l'ultima connessione aperta in ordine di tempo. Se non vi sono connessioni aperte, la funzione tenta di stabilire una connessione, come se fosse utilizzata la funzione mssql_connect(), e utilizza quella.
Ciascuna esecuzione di mssql_query() sarà fatta sul database attivo.
Per potere selezionare un database contenente un nome o un trattivo ("-") nel nome occorre racchiudere il nome stesso tra parantesi quadre, come illustrato nell'esempio seguente:
Vedere anche: mssql_connect(), mssql_pconnect(), e mssql_query()
Avvertimento |
Questo modulo è SPERIMENTALE. Ovvero, il comportamento di queste funzioni, i nomi di queste funzioni, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questo modulo è a vostro rischio. |
On Windows, you should use the PDO_ODBC driver to connect to Microsoft SQL Server and Sybase databases, as the native Windows DB-LIB is ancient, thread un-safe and no longer supported by Microsoft.
(no version information, might be only in CVS)
PDO_DBLIB DSN -- Connecting to Microsoft SQL Server and Sybase databasesThe PDO_DBLIB Data Source Name (DSN) is composed of the following elements:
The DSN prefix is sybase: if PDO_DBLIB was linked against the FreeTDS libraries, mssql: if PDO_DBLIB was linked against the Microsoft SQL Server libraries, or dblib: if linked against any other variety of DB-lib.
The hostname on which the database server resides.
The name of the database.
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://devel.mohawksoft.com/msession.html.
Nota: Questo modulo non è disponibile su piattaforme Windows.
To enable Msession support configure PHP --with-msession[=DIR], where DIR is the Msession install directory.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Returns an associative array of value/session for all sessions with a variable named name.
Used for searching sessions with common attributes.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.2.0, PHP 5)
msession_plugin -- Call an escape function within the msession personality pluginAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
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/msql3.
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)
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. mSQL configuration options
Name | Default | Changeable | Changelog |
---|---|---|---|
msql.allow_persistent | "1" | PHP_INI_ALL | |
msql.max_persistent | "-1" | PHP_INI_ALL | |
msql.max_links | "-1" | PHP_INI_ALL |
Breve descrizione dei parametri di configurazione.
There are two resource types used in the mSQL module. The first one is the link identifier for a database connection, the second a resource which holds the result of a query.
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
This simple example shows how to connect, execute a query, print resulting rows and disconnect from a mSQL database.
Esempio 1. mSQL usage example
|
Returns number of affected rows by the last SELECT, UPDATE or DELETE query associated with result.
The result resource that is being evaluated. This result comes from a call to msql_query().
msql_close() closes the non-persistent connection to the mSQL server that's associated with the specified link identifier.
Using msql_close() isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution. See also freeing resources.
The mSQL connection. If not specified, the last link opened by msql_connect() is assumed. If no such link is found, the function will try to establish a link as if msql_connect() was called, and use it.
msql_connect() establishes a connection to a mSQL server.
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().
The hostname can also include a port number. e.g. hostname,port.
If not specified, the connection is established by the means of a Unix domain socket, being then more efficient then a localhost TCP socket connection.
Nota: While this function will accept a colon (:) as a host/port separator, a comma (,) is the preferred method.
msql_create_db() attempts to create a new database on the mSQL server.
The name of the mSQL database.
The mSQL connection. If not specified, the last link opened by msql_connect() is assumed. If no such link is found, the function will try to establish a link as if msql_connect() was called, and use it.
msql_data_seek() moves the internal row pointer of the mSQL result associated with the specified query identifier to point to the specified row number. The next call to msql_fetch_row() would return that row.
The result resource that is being evaluated. This result comes from a call to msql_query().
The seeked row number.
msql_db_query() selects a database and executes a query on it.
The name of the mSQL database.
The SQL query.
The mSQL connection. If not specified, the last link opened by msql_connect() is assumed. If no such link is found, the function will try to establish a link as if msql_connect() was called, and use it.
msql_drop_db() attempts to drop (remove) a database from the mSQL server.
The name of the database.
The mSQL connection. If not specified, the last link opened by msql_connect() is assumed. If no such link is found, the function will try to establish a link as if msql_connect() was called, and use it.
msql_error() returns the last issued error by the mSQL server. Note that only the last error message is accessible with msql_error().
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.
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.
The result resource that is being evaluated. This result comes from a call to msql_query().
A constant that can take the following values: MSQL_ASSOC, MSQL_NUM, and MSQL_BOTH with MSQL_BOTH being the default.
Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.
Esempio 1. msql_fetch_array() example
|
msql_fetch_field() can be used in order to obtain information about fields in a certain query result.
The result resource that is being evaluated. This result comes from a call to msql_query().
The field offset. If not specified, the next field that wasn't yet retrieved by msql_fetch_field() is retrieved.
Returns an object containing field information. 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
unique - 1 if the column is a unique key
type - the type of the column
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).
Speed-wise, the function is identical to msql_fetch_array(), and almost as quick as msql_fetch_row() (the difference is insignificant).
The result resource that is being evaluated. This result comes from a call to msql_query().
Returns an object with properties that correspond to the fetched row, or FALSE if there are no more rows.
Esempio 1. msql_fetch_object() example
|
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.
The result resource that is being evaluated. This result comes from a call to msql_query().
Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.
Esempio 1. msql_fetch_row() example
|
msql_field_flags() returns the field flags of the specified field.
The result resource that is being evaluated. This result comes from a call to msql_query().
The numerical field offset. The field_offset starts at 1.
Returns a string containing the field flags of the specified key. This can be: primary key not null, not null, primary key, unique not null or unique.
msql_field_len() returns the length of the specified field.
The result resource that is being evaluated. This result comes from a call to msql_query().
The numerical field offset. The field_offset starts at 1.
msql_field_name() gets the name of the specified field index.
The result resource that is being evaluated. This result comes from a call to msql_query().
The numerical field offset. The field_offset starts at 1.
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.
The result resource that is being evaluated. This result comes from a call to msql_query().
The numerical field offset. The field_offset starts at 1.
Returns the name of the table that the specified field is in.
The result resource that is being evaluated. This result comes from a call to msql_query().
The numerical field offset. The field_offset starts at 1.
msql_field_type() gets the type of the specified field index.
The result resource that is being evaluated. This result comes from a call to msql_query().
The numerical field offset. The field_offset starts at 1.
The type of the field. One of int, char, real, ident, null or unknown. This functions will return FALSE on failure.
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.
The result resource that is being evaluated. This result comes from a call to msql_query().
msql_list_tables() lists the databases available on the specified link_identifier.
The mSQL connection. If not specified, the last link opened by msql_connect() is assumed. If no such link is found, the function will try to establish a link as if msql_connect() was called, and use it.
Returns a result set which may be traversed with any function that fetches result sets, such as msql_fetch_array(). On failure, this function will return FALSE.
msql_list_fields() returns information about the given table.
The name of the database.
The name of the table.
The mSQL connection. If not specified, the last link opened by msql_connect() is assumed. If no such link is found, the function will try to establish a link as if msql_connect() was called, and use it.
Returns a result set which may be traversed with any function that fetches result sets, such as msql_fetch_array(). On failure, this function will return FALSE.
msql_list_tables() lists the tables on the specified database.
The name of the database.
The mSQL connection. If not specified, the last link opened by msql_connect() is assumed. If no such link is found, the function will try to establish a link as if msql_connect() was called, and use it.
Returns a result set which may be traversed with any function that fetches result sets, such as msql_fetch_array(). On failure, this function will return FALSE.
msql_num_fields() returns the number of fields in a result set.
The result resource that is being evaluated. This result comes from a call to msql_query().
msql_num_rows() returns the number of rows in a result set.
The result resource that is being evaluated. This result comes from a call to msql_query().
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 this function).
The hostname can also include a port number. e.g. hostname,port.
If not specified, the connection is established by the means of a Unix domain socket, being then more efficient then a localhost TCP socket connection.
Nota: While this function will accept a colon (:) as a host/port separator, a comma (,) is the preferred method.
msql_query() sends a query to the currently active database on the server that's associated with the specified link identifier.
The SQL query.
The mSQL connection. If not specified, the last link opened by msql_connect() is assumed. If no such link is found, the function will try to establish a link as if msql_connect() was called, and use it.
Esempio 1. msql_query() example
|
msql_result() returns the contents of one cell from a mSQL result set.
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 are often much quicker than msql_result().
Recommended high-performance alternatives: msql_fetch_row(), msql_fetch_array(), and msql_fetch_object().
The result resource that is being evaluated. This result comes from a call to msql_query().
The row offset.
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.
Nota: Specifying a numeric field offset is much quicker than specifying a fieldname or tablename.fieldname.
Returns the contents of the cell at the row and offset in the specified mSQL result set.
msql_select_db() sets the current active database on the server that's associated with the specified link_identifier.
Subsequent calls to msql_query() will be made on the active database.
The database name.
The mSQL connection. If not specified, the last link opened by msql_connect() is assumed. If no such link is found, the function will try to establish a link as if msql_connect() was called, and use it.
While there are many languages in which every necessary character can be represented by a one-to-one mapping to a 8-bit value, there are also several languages which require so many characters for written communication that cannot be contained within the range a mere byte can code. Multibyte character encoding schemes were developed to express that many (more than 256) characters in the regular bytewise coding system.
When you manipulate (trim, split, splice, etc.) strings encoded in a multibyte encoding, you need to use special functions since two or more consecutive bytes may represent a single character in such encoding schemes. Otherwise, if you apply a non-multibyte-aware string function to the string, it probably fails to detect the beginning or ending of the multibyte character and ends up with a corrupted garbage string that most likely loses its original meaning.
mbstring provides these multibyte specific string functions that help you deal with multibyte encodings in PHP, which is basically supposed to be used with single byte encodings. In addition to that, mbstring handles character encoding conversion between the possible encoding pairs.
mbstring is also designed to handle Unicode-based encodings such as UTF-8 and UCS-2 and many single-byte encodings for convenience (listed below), whereas mbstring was originally developed for use in Japanese web pages.
Encodings of the following types are safely used with PHP.
A singlebyte encoding,
which has ASCII-compatible (ISO646 compatible) mappings for the characters in range of 00h to 7fh.
A multibyte encoding,
which has ASCII-compatible mappings for the characters in range of 00h to 7fh.
which don't use ISO2022 escape sequences.
which don't use a value from 00h to 7fh in any of the compounded bytes that represents a single character.
These are examples of character encodings that are unlikely to work with PHP.
Although PHP scripts written in any of those encodings might not work, especially in the case where encoded strings appear as identifiers or literals in the script, you can almost avoid using these encodings by setting up the mbstring's transparent encoding filter function for incoming HTTP queries.
Nota: It's highly discouraged to use SJIS, BIG5, CP936, CP949 and GB18030 for the internal encoding unless you are familiar with the parser, the scanner and the character encoding.
Nota: If you have some database connected with PHP, it is recommended that you use the same character encoding for both database and the internal encoding for ease of use and better performance.
If you are using PostgreSQL, the character encoding used in the database and the one used in the PHP may differ as it supports automatic character set conversion between the backend and the frontend.
mbstring is a non-default extension. This means it is not enabled by default. You must explicitly enable the module with the configure option. See the Install section for details.
The following configure options are related to the mbstring module.
--enable-mbstring=LANG: Enable mbstring functions. This option is required to use mbstring functions.
As of PHP 4.3.0, mbstring extension provides enhanced support for Simplified Chinese, Traditional Chinese, Korean, and Russian in addition to Japanese. To enable that feature, you will have to supply either one of the following options to the LANG parameter; --enable-mbstring=cn for Simplified Chinese support, --enable-mbstring=tw for Traditional Chinese support, --enable-mbstring=kr for Korean support, --enable-mbstring=ru for Russian support, and --enable-mbstring=ja for Japanese support.
Also --enable-mbstring=all is convenient for you to enable all the supported languages listed above.
Nota: Japanese language support is also enabled by --enable-mbstring without any options for the sake of backwards compatibility.
--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 was eliminated and replaced with the runtime setting 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.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. mbstring configuration options
Name | Default | Changeable | Changelog |
---|---|---|---|
mbstring.language | "neutral" | PHP_INI_PERDIR | Available since PHP 4.3.0. |
mbstring.detect_order | NULL | PHP_INI_ALL | Available since PHP 4.0.6. |
mbstring.http_input | "pass" | PHP_INI_ALL | Available since PHP 4.0.6. |
mbstring.http_output | "pass" | PHP_INI_ALL | Available since PHP 4.0.6. |
mbstring.internal_encoding | NULL | PHP_INI_ALL | Available since PHP 4.0.6. |
mbstring.script_encoding | NULL | PHP_INI_ALL | Available since PHP 4.3.0. |
mbstring.substitute_character | NULL | PHP_INI_ALL | Available since PHP 4.0.6. |
mbstring.func_overload | "0" | PHP_INI_PERDIR | PHP_INI_SYSTEM in PHP <= 4.2.3. Available since PHP 4.2.0. |
mbstring.encoding_translation | "0" | PHP_INI_PERDIR | Available since PHP 4.3.0. |
Breve descrizione dei parametri di configurazione.
The default national language setting (NLS) used in mbstring. Note that this option automagically defines mbstring.internal_encoding and mbstring.internal_encoding should be placed after mbstring.language in php.ini
Enables the transparent character encoding filter for the incoming HTTP queries, which performs detection and conversion of the input encoding to the internal character encoding.
Defines the default internal character encoding.
Defines the default HTTP input character encoding.
Defines the default HTTP output character encoding.
Defines default character code detection order. See also mb_detect_order().
Defines character to substitute for invalid character encoding.
Overloads a set of single byte functions by the mbstring counterparts. See Function overloading for more information.
According to the HTML 4.01 specification, Web browsers are allowed to encode a form being submitted with a character encoding different from the one used for the page. See mb_http_input() to detect character encoding used by browsers.
Although popular browsers are capable of giving a reasonably accurate guess to the character encoding of a given HTML document, it would be better to set the charset parameter in the Content-Type HTTP header to the appropriate value by header() or default_charset ini setting.
Esempio 1. php.ini setting examples
|
Esempio 2. php.ini setting for EUC-JP users
|
Esempio 3. php.ini setting for SJIS users
|
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
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.
Nota: In PHP 4.3.2 or earlier versions, there was a limitation in this functionality that mbstring does not perform character encoding conversion in POST data if the enctype attribute in the form element is set to multipart/form-data. So you have to convert the incoming data by yourself in this case if necessary.
Beginning with PHP 4.3.3, if enctype for HTML form is set to multipart/form-data and mbstring.encoding_translation is set to On in php.ini the POST'ed variables and the names of uploaded files will be converted to the internal character encoding as well. However, the conversion isn't applied to the query keys.
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 those settings in each Virtual Host directive 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: PHP3-i18n users should note that mbstring's output conversion differs from PHP3-i18n. Character encoding is converted using output buffer.
Currently the following character encodings are supported by the mbstring module. Any of those Character encodings can be specified in the encoding parameter of mbstring functions.
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
UTF-16
UTF-16BE
UTF-16LE
UTF-7
UTF7-IMAP
UTF-8
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
HTML-ENTITIES
7bit
8bit
EUC-CN
CP936
HZ
EUC-TW
CP950
BIG-5
EUC-KR
UHC (CP949)
ISO-2022-KR
Windows-1251 (CP1251)
Windows-1252 (CP1252)
CP866 (IBM866)
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 the list of encodings defined per the NLS. For instance, if the NLS is set to Japanese, the value is assumed to be "ASCII,JIS,UTF-8,EUC-JP,SJIS".
See also mb_detect_order()
You might often find it difficult to get an existing PHP application work in a given multibyte environment. That's mostly because lots of PHP applications out there are written with the standard string functions such as substr(), which are known to not properly handle multibyte-encoded strings.
mbstring supports 'function overloading' feature which enables you to add multibyte awareness to such an application without code modification by overloading multibyte counterparts on the standard string functions. For example, mb_substr() is called instead of substr() if function overloading is enabled. This feature makes it easy to port applications that only support single-byte encodings to a multibyte environment in many cases.
To use the function overloading, set mbstring.func_overload in php.ini to a positive value that represents a combination of bitmasks specifying the categories of functions to be overloaded. It should be set to 1 to overload the mail() function. 2 for string functions, 4 for regular expression functions. For example, if is set for 7, mail, strings and regular expression functions should be overloaded. The list of overloaded functions are shown below.
Tabella 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() |
Nota: It is not recommended to use the function overloading option in the per-directory context, because it's not confirmed yet to be stable enough in a production environment and may lead to undefined behaviour.
It is often said quite hard to figure out how Japanese texts are handled in the computer. This is not only because Japanese characters can only be represented by multibyte encodings, but because different encoding standards are adopted for different purposes / platforms. Moreover, not a few character set standards are used there, which are slightly different from one another. Those facts have often led developers to inevitable mess-up.
To create a working web application that would be put in the Japanese environment, it is important to use the proper character encoding and character set for the task in hand.
Storage for a character can be up to six bytes
Most of multibyte characters often appear twice as wide as a single-byte character on display. Those characters are called "zen-kaku" in Japanese which means "full width", and the other (narrower) characters are called "han-kaku" - means half width. However the graphical properties of the characters depend on the glyphs of the type faces used to display them or print them out.
Some character encodings use shift(escape) sequences defined in ISO2022 to switch the code map of the specific code area (00h to 7fh).
ISO-2022-JP should be used in SMTP/NNTP, and headers and entities should be reencoded as per RFC requirements. Although those are not requisites, it's still a good idea because several popular user agents cannot recognize any other encoding methods.
Webpages created for mobile phone services such as i-mode, Vodafone live!, or EZweb are supposed to use Shift_JIS.
Multibyte character encoding schemes and the related issues are very complicated. There should be too few space to cover in sufficient details. Please refer to the following URLs and other resources for further readings.
Unicode materials
Japanese/Korean/Chinese character information
Summaries of supported encodings
Name in the IANA character set registry: ISO-10646-UCS-4
Underlying character set: ISO 10646
Description: The Universal Character Set with 31-bit code space, standardized as UCS-4 by ISO/IEC 10646. It is kept synchronized with the latest version of the Unicode code map.
Additional note: If this name is used in the encoding conversion facility, the converter attempts to identify by the preceding BOM (byte order mark)in which endian the subsequent bytes are represented.
Name in the IANA character set registry: ISO-10646-UCS-4
Underlying character set: UCS-4
Description: See above.
Additional note: In contrast to UCS-4, strings are always assumed to be in big endian form.
Name in the IANA character set registry: ISO-10646-UCS-4
Underlying character set: UCS-4
Description: See above.
Additional note: In contrast to UCS-4, strings are always assumed to be in little endian form.
Name in the IANA character set registry: ISO-10646-UCS-2
Underlying character set: UCS-2
Description: The Universal Character Set with 16-bit code space, standardized as UCS-2 by ISO/IEC 10646. It is kept synchronized with the latest version of the unicode code map.
Additional note: If this name is used in the encoding conversion facility, the converter attempts to identify by the preceding BOM (byte order mark)in which endian the subsequent bytes are represented.
Name in the IANA character set registry: ISO-10646-UCS-2
Underlying character set: UCS-2
Description: See above.
Additional note: In contrast to UCS-2, strings are always assumed to be in big endian form.
Name in the IANA character set registry: ISO-10646-UCS-2
Underlying character set: UCS-2
Description: See above.
Additional note: In contrast to UCS-2, strings are always assumed to be in little endian form.
Name in the IANA character set registry: UTF-32
Underlying character set: Unicode
Description: Unicode Transformation Format of 32-bit unit width, whose encoding space refers to the Unicode's codeset standard. This encoding scheme wasn't identical to UCS-4 because the code space of Unicode were limited to a 21-bit value.
Additional note: If this name is used in the encoding conversion facility, the converter attempts to identify by the preceding BOM (byte order mark)in which endian the subsequent bytes are represented.
Name in the IANA character set registry: UTF-32BE
Underlying character set: Unicode
Description: See above
Additional note: In contrast to UTF-32, strings are always assumed to be in big endian form.
Name in the IANA character set registry: UTF-32LE
Underlying character set: Unicode
Description: See above
Additional note: In contrast to UTF-32, strings are always assumed to be in little endian form.
Name in the IANA character set registry: UTF-16
Underlying character set: Unicode
Description: Unicode Transformation Format of 16-bit unit width. It's worth a note that UTF-16 is no longer the same specification as UCS-2 because the surrogate mechanism has been introduced since Unicode 2.0 and UTF-16 now refers to a 21-bit code space.
Additional note: If this name is used in the encoding conversion facility, the converter attempts to identify by the preceding BOM (byte order mark)in which endian the subsequent bytes are represented.
Name in the IANA character set registry: UTF-16BE
Underlying character set: Unicode
Description: See above.
Additional note: In contrast to UTF-16, strings are always assumed to be in big endian form.
Name in the IANA character set registry: UTF-16BE
Underlying character set: Unicode
Description: See above.
Additional note: In contrast to UTF-16, strings are always assumed to be in big endian form.
Name in the IANA character set registry: UTF-8
Underlying character set: Unicode / UCS
Description: Unicode Transformation Format of 8-bit unit width.
Additional note: none
Name in the IANA character set registry: UTF-7
Underlying character set: Unicode
Description: A mail-safe transformation format of Unicode, specified in RFC2152.
Additional note: none
Name in the IANA character set registry: (none)
Underlying character set: Unicode
Description: A variant of UTF-7 which is specialized for use in the IMAP protocol.
Additional note: none
Name in the IANA character set registry: US-ASCII (preferred MIME name) / iso-ir-6 / ANSI_X3.4-1986 / ISO_646.irv:1991 / ASCII / ISO646-US / us / IBM367 / CP367 / csASCII
Underlying character set: ASCII / ISO 646
Description: American Standard Code for Information Interchange is a commonly-used 7-bit encoding. Also standardized as an international standard, ISO 646.
Additional note: (none)
Name in the IANA character set registry: EUC-JP (preferred MIME name) / Extended_UNIX_Code_Packed_Format_for_Japanese / csEUCPkdFmtJapanese
Underlying character set: Compound of US-ASCII / JIS X0201:1997 (hankaku kana part) / JIS X0208:1990 / JIS X0212:1990
Description: As you see the name is derived from an abbreviation of Extended UNIX Code Packed Format for Japanese, this encoding is mostly used on UNIX or alike platforms. The original encoding scheme, Extended UNIX Code, is designed on the basis of ISO 2022.
Additional note: The character set referred to by EUC-JP is different to IBM932 / CP932, which are used by OS/2® and Microsoft® Windows®. For information interchange with those platforms, use EUCJP-WIN instead.
Name in the IANA character set registry: Shift_JIS (preferred MIME name) / MS_Kanji / csShift_JIS
Underlying character set: Compound of JIS X0201:1997 / JIS X0208:1997
Description: Shift_JIS was developed in early 80's, at the time personal Japanese word processors were brought into the market, in order to maintain compatiblities with the legacy encoding scheme JIS X 0201:1976. According to the IANA definition the codeset of Shift_JIS is slightly different to IBM932 / CP932. However, the names "SJIS" / "Shift_JIS" are often wrongly used to refer to these codesets.
Additional note: For the CP932 codemap, use SJIS-WIN instead.
Name in the IANA character set registry: (none)
Underlying character set: Compound of JIS X0201:1997 / JIS X0208:1997 / IBM extensions / NEC extensions
Description: While this "encoding" uses the same encoding scheme as EUC-JP, the underlying character set is different. That is, some code points map to different characters than EUC-JP.
Additional note: none
Name in the IANA character set registry: Windows-31J / csWindows31J
Underlying character set: Compound of JIS X0201:1997 / JIS X0208:1997 / IBM extensions / NEC extensions
Description: While this "encoding" uses the same encoding scheme as Shift_JIS, the underlying character set is different. That means some code points map to different characters than Shift_JIS.
Additional note: (none)
Name in the IANA character set registry: ISO-2022-JP (preferred MIME name) / csISO2022JP
Underlying character set: US-ASCII / JIS X0201:1976 / JIS X0208:1978 / JIS X0208:1983
Description: RFC1468
Additional note: (none)
Name in the IANA character set registry: JIS
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: ISO-8859-1
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: ISO-8859-2
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: ISO-8859-3
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: ISO-8859-4
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: ISO-8859-5
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: ISO-8859-6
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: ISO-8859-7
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: ISO-8859-8
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: ISO-8859-9
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: ISO-8859-10
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: ISO-8859-13
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: ISO-8859-14
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: ISO-8859-15
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: byte2be
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: byte2le
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: byte4be
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: byte4le
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: BASE64
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: HTML-ENTITIES
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: 7bit
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: 8bit
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: EUC-CN
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: CP936
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: HZ
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: EUC-TW
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: CP950
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: BIG-5
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: EUC-KR
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: UHC (CP949)
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: ISO-2022-KR
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: Windows-1251 (CP1251)
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: Windows-1252 (CP1252)
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: CP866 (IBM866)
Underlying character set:
Description:
Additional note:
Name in the IANA character set registry: KOI8-R
Underlying character set:
Description:
Additional note:
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/.
Esempio 1. mb_convert_case() example
|
See also mb_strtolower(), mb_strtoupper(), strtolower(), strtoupper(), ucfirst() e ucwords()
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.
Esempio 1. mb_convert_encoding() example
|
See also mb_detect_order().
(PHP 4 >= 4.0.6, PHP 5)
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.
Specify with combination of following options. Default value is KV.
Tabella 1. Applicable Conversion Options
Option | Meaning |
---|---|
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.
convmap is array to specifies code area to convert.
encoding is character encoding. If it is omitted, internal character encoding is used.
Esempio 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.
Esempio 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 an 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.
Esempio 2. mb_detect_order() examples
|
See also mb_internal_encoding(), mb_http_input(), mb_http_output() and mb_send_mail().
mb_encode_mimeheader() encodes a given string str by the MIME header encoding scheme. Returns a converted version of the string represented in ASCII.
charset specifies the name of the character set in which str is represented in. The default value is determined by the current NLS setting (mbstring.language).
transfer_encoding specifies the scheme of MIME encoding. It should be either "B" (Base64) or "Q" (Quoted-Printable). Falls back to "B" if not given.
linefeed specifies the EOL (end-of-line) marker with which mb_encode_mime_header() performs line-folding (a RFC term, the act of breaking a line longer than a certain length into multiple lines. The length is currently hard-coded to 74 characters). Falls back to "\r\n" (CRLF) if not given.
Nota: This function isn't designed to break lines at higher-level contextual break points (word boundaries, etc.). This behaviour may clutter up the original string with unexpected spaces.
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.
convmap is array specifies code area to convert.
encoding is character encoding.
Esempio 1. convmap example
|
Esempio 2. mb_encode_numericentity() example
|
See also mb_decode_numericentity().
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.
See also: mb_regex_encoding(), mb_ereg().
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.
See also: mb_regex_encoding(), mb_eregi_replace().
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.
See also: mb_regex_encoding(), mb_ereg_search_setpos().
(PHP 4 >= 4.2.0)
mb_ereg_search_getregs -- Retrieve the result from the last multibyte regular expression matchmb_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.
See also: mb_regex_encoding(), mb_ereg_search_init().
(PHP 4 >= 4.2.0)
mb_ereg_search_init -- Setup string and regular expression for multibyte regular expression matchmb_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.
See also: mb_regex_encoding(), mb_ereg_search_regs().
(PHP 4 >= 4.2.0)
mb_ereg_search_pos -- Return position and length of matched part of multibyte regular expression for predefined multibyte stringmb_ereg_search_pos() returns an array including position of matched part for multibyte regular expression. The first element of the array will be the beginning 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(). If 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.
See also: mb_regex_encoding(), mb_ereg_search_init().
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.
See also: mb_regex_encoding(), mb_ereg_search_init().
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.
See also: mb_regex_encoding(), mb_ereg_search_init().
(PHP 4 >= 4.2.0)
mb_ereg_search -- Multibyte regular expression match for predefined multibyte stringmb_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.
See also: mb_regex_encoding(), mb_ereg_search_init().
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 the array regs will contain the substring of matched string. The functions returns 1 if it matches with the empty string. If no matches 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.
See also: mb_regex_encoding(), mb_eregi()
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. option has the same meaning as in mb_ereg_replace().
The internal encoding or the character encoding specified in mb_regex_encoding() will be used as character encoding.
See also: mb_regex_encoding(), mb_ereg_replace().
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 the array regs will contain the substring of matched string. The functions returns 1 if it matches with the empty string. If no matches 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.
See also: mb_regex_encoding(), mb_ereg().
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, "S" for string, "L" for list, "I" for whole list (will return array). 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() and 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_list_encodings() returns an array with all supported encodings.
Esempio 1. mb_list_encodings() example
Il precedente esempio visualizzerà:
|
(PHP 4 >= 4.0.6, PHP 5)
mb_output_handler -- Callback function converts character encoding in output buffermb_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 handler 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.
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.
See also: mb_internal_encoding(), mb_ereg()
mb_regex_set_options() sets the default options described by options for multibyte regex functions.
Returns the previous options. If options is omitted, it returns the string that describes the current options.
See also mb_split(), mb_ereg() and 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").
Nota: Content-Type and Content-Transfer-Encoding headers can be redefined as of PHP 5.0.0. In PHP 4, values defined by mb_language() are always used.
additional_parameter is a MTA command line parameter. It is useful when setting the correct Return-Path header when using sendmail.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also mail(), mb_encode_mimeheader(), and mb_language().
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.
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() and 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_strrpos(), 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() and 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() and mb_convert_case().
mb_strwidth() returns width of string str.
Multi-byte character usually twice of width compare to single byte character.
Tabella 1. Characters width
Chars | Width |
---|---|
U+0000 - U+0019 | 0 |
U+0020 - U+1FFF | 1 |
U+2000 - U+FF60 | 2 |
U+FF61 - U+FF9F | 1 |
U+FFA0 - | 2 |
encoding is character encoding. If it is omitted, internal encoding is used.
See also: mb_strimwidth(), mb_internal_encoding().
mb_substitute_character() 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_convert_encoding(), mb_convert_variables(), mb_output_handler(), 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().
Avvertimento |
Questo modulo è SPERIMENTALE. Ovvero, il comportamento di queste funzioni, i nomi di queste funzioni, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questo modulo è a vostro rischio. |
(4.0.5 - 4.2.3 only, PECL)
muscat_close -- Shuts down the muscat session and releases any memory back to PHPAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
[Not back to the system, note!]
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione può restituire il Booleano FALSE, ma può anche restituire un valore non-Booleano valutato come FALSE, come ad esempio 0 o "". Per favore fare riferimento alla sezione Booleans per maggiori informazioni. Usare l'operatore === per controllare il valore restituito da questa funzione. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
muscat_setup_net() creates a new muscat session and returns the handle.
muscat_host is the hostname to connect to. port is the port number to connect to.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
size is the amount 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.
Queste funzioni consentono l'accesso ai server di database MySQL. Maggiori informazioni riguardo MySQL possono essere trovate su http://www.mysql.com/.
La documentazione su MySQL può essere trovata su http://dev.mysql.com/doc/.
Al fine di rendere queste funzioni disponibili, si deve compilare PHP con il supporto MySQL.
Usando l'opzione di configurazione --with-mysql[=DIR] si abilita PHP l'accesso ai database MySQL.
In PHP 4, il parametro --with-mysql è abilitato per default. Per disabilitarlo si può utilizzare --without-mysql . Inoltre in PHP 4, se si abilita MySql senza indicare il percorso directory di installazione di MySql, il PHP utilizzerà le librerie incluse nella distribuzione. In Windows non vi sono DLL, è semplicemente compilato nel PHP. Gli utenti che eseguano altre applicazioni basate su MySql (come, ad esempio, auth-mysql), non dovrebbero utilizzare le librerie allegate al PHP, ma, piuttosto, indicare il percorso alla directory di instalalzione di MySQL, come, ad esempio; --with-mysql=/percorso/a/mysql. Questo forzerà PHP ad usare le librerie client installate da MySQL evitando ogni conflitto.
In PHP 5, MySQL non sarà più abilitato per default, e nè la libreria MySQL sarà allegata al PHP. Per maggiori dettagli sul perchè leggere: FAQ.
Questo modulo di interfaccia a MySQL non supporta completamente le tutte le funzioni presenti nelle versioni di MySQL successive alla 4.1.0. Per avere il pieno supporto a queste vedere MySQLi.
Se si desidera installare sia il modulo mysql sia il modulo mysqli utilizzare la stessa libreria client per evitare conflitti.
Avvertimento |
Problemi di blocco e di avvio di PHP possono essere riscontrati quando si carica questa estensione insieme ad estensioni recode. Vedere anche l'estensione recode per maggiori informazioni. |
Nota: Se occorre utilizzare set di caratteri differenti rispetto al latin (il default), si deve installare la libreria esterna (non allegata al PHP) libmysql compilata con il supporto dei set di caratteri.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. Opzioni di configurazione di MySQL
Nome | Predefinito | Modificabile in |
---|---|---|
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 |
Breve descrizione dei parametri di configurazione.
Determina se consentire le connessioni persistenti a MySQL.
Il numero massimo di connessioni persistenti MySQL per processo.
Il numero massimo di connessioni MySQL per processo, incluse le connessioni persistenti.
Il numero di porta TCP predefinito da usare per connettersi ad un server di database se nessuna altra porta viene specificata. Se nessun valore predefinito e specificato, la porta sarà ottenuta dalla variabile d'ambiente MYSQL_TCP_PORT, dalla voce mysql-tcp in /etc/services o dalla costante MYSQL_PORT in fase di compilazione, in questo ordine. Win32 userà solo la costante MYSQL_PORT.
Il nome del socket predefinito da usare per connettersi ad un server di database locale se nessun altro nome di socket viene specificato.
L'host di default del server da usare per connettersi al server di database se nessun altro host viene specificato. Non si applica in safe mode.
Il nome utente predefinito da usare per connettersi al server di database se nessun altro nome viene specificato. Non si applica in safe mode.
La password predefinita da usare per connettrsi al server di database se nessuna altra password viene specificata. Non si appplica in safe mode.
Timeout di connessione in secondi. Per Linux questo timeout è usato anche per attendere la prima risposta dal server.
Ci sono due tipi di risorsa usati nel modulo MySQL. Il primo è l'identificativo di connessione per una connessione ad un database, del secondo tipo sono le risorse che contengono i risultati di una query.
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Fin dal PHP 4.3.0 è possibile specificare flag addizionali per il client per le funzioni mysql_connect() e mysql_pconnect(). Sono definite le seguenti costanti:
Tabella 2. Costanti client MySQL
Costante | Descrizione |
---|---|
MYSQL_CLIENT_COMPRESS | Usa la compressione del protocollo |
MYSQL_CLIENT_IGNORE_SPACE | Consente lo spazio dopo i nomi delle funzioni |
MYSQL_CLIENT_INTERACTIVE | Lascia trascorrere interactive_timeout secondi (anziché wait_timeout) di inattività prima di chiudere la connessione |
La funzione mysql_fetch_array() usa una costante per i diversi tipi di array risultato. Sono definite le seguenti costanti:
Tabella 3. Costanti caricamento MySQL
Costante | Descrizione |
---|---|
MYSQL_ASSOC | Le colonne sono restituite in un array avente il nome del campo come indice dell'array |
MYSQL_BOTH | Le colonne sono restituite in un array avente sia un indice numerico sia un indice costituito dal nome del campo |
MYSQL_NUM | Le colonne sono restituite in un array avente un indice numerico per i campi. Questo indice inizia da 0, il primo campo nel risultato |
Questo esempio mostra come connettersi, eseguire una query, stampare le righe risultanti e disconnettersi dal database MySQL.
Esempio 1. Esempio dell'estensione MySQL
|
(PHP 3, PHP 4, PHP 5)
mysql_affected_rows -- Ottiene il numero di righe coinvolte nelle precedenti operazioni MySQLmysql_affected_rows() restituisce il numero di righe coinvolte nell'ultima query INSERT, UPDATE o DELETE associata a identificativo_connessione. Se l'identificativo di connessione non è specificato, viene considerata l'ultima connessione aperta con mysql_connect().
Nota: Se sono usate le transazioni, è necessario richiamare mysql_affected_rows() dopo le query INSERT, UPDATE, o DELETE e non dopo il commit.
Se l'ultima query era una query DELETE senza clausola WHERE, tuti i record saranno cancellati dalla tabella ma questa funzione restituirà zero.
Nota: Usando UPDATE, MySQL non aggiornerà le colonne nelle quali il nuovo valore è uguale al vecchio valore. Questo crea la possibilità che mysql_affected_rows() può non uguagliare realmente il numero di righe corrispondenti ma solo il numero di righe effettivamente coinvolte dalla query.
mysql_affected_rows() non funziona con l'istruzione SELECT ma solo con le istruzioni che modificano i record. Per ricavare il numero di righe restituite da SELECT, usare mysql_num_rows().
Se l'ultima query fallisce, questa funzione restituisce -1.
Esempio 1. Query di eliminazione
L'esempio riportato sopra dovrebbe produrre il seguente output:
|
Esempio 2. Query di aggiornamento
L'esempio riportato sopra dovrebbe produrre il seguente output:
|
Vedere anche: mysql_num_rows(), mysql_info().
mysql_change_user() cambia l'utente dell'attuale connessione attiva o della connessione specificata dal parametro opzionale identificativo_connessione. Se un database is specificato, questo sarà il database corrente dopo che l'utente è stato cambiato. Se l'autorizzazione del nuovo utente e password falllisce, l'attuale utente connesso rimane attivo. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: Questa funzione è stata introdotta nel PHP 3.0.13 e richiede MySQL 3.23.3 o successivo. Non è disponibile nel PHP 4.
mysql_client_encoding() restituisce il nome del set di caratteri predefinito per l'attuale connessione.
Esempio 1. Esempio di mysql_client_encoding()
L'esempio riportato sopra produce il seguente output:
|
Vedere anche: mysql_real_escape_string()
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
mysql_close() chiude la connessione al server MySQL associata all'identificativo di connessione specificato. Se identificativo_connessione non è specificato, viene usata l'ultima connessione aperta.
L'uso di mysql_close() non è normalmente necessario, dal momento che le connessioni non persistenti sono chiuse automaticamente alla fine dell'esecuzione dello script. Vedere anche freeing resources.
Nota: mysql_close() non chiude le connessioni persistenti create da mysql_pconnect().
Vedere anche: mysql_connect(), e mysql_pconnect().
Restituisce un identificativo di connessione MySQL in caso di successo oppure FALSE in caso di fallimento.
mysql_connect() stabilice una connessione ad un server MySQL. I seguenti valore predefiniti sono assunti per i parametri opzionali mancanti: server = 'localhost:3306', nome_utente = nome dell'utente proprietario del processo server e password = password vuota.
Il parametro server può anche includere un numero di porta. Es. "hostname:porta" o un percorso ad un socket es. ":/percorso/al/socket" per il localhost.
Nota: il supporto per ":porta" è stato aggiunto nel PHP 3.0B4.
Il supporto per ":/percorso/al/socket" è stato aggiunto nel PHP 3.0.10.
Si può eliminare il messaggio di errore nel caso di fallimento aggiungendo il prefisso @ al un nome della funzione.
Se si fa una seconda chiamata a mysql_connect() con gli stessi argomenti, nessuna nuova connessione sarà stabilita, ma sarà restituito l'identificativo della connessione già aperta. Il paramentro nuova_connessione modifica questo comportamento e fa sì che mysql_connect() apra sempre una nuova connessione, anche se mysql_connect() era stata chiamata prima con gli stessi parametri. il parametro client_flags può essere combinato con le costanti MYSQL_CLIENT_COMPRESS, MYSQL_CLIENT_IGNORE_SPACE o MYSQL_CLIENT_INTERACTIVE.
Nota: Il paramentro nuova_connessione è stato indrodotto dal PHP 4.2.0
Il parametro client_flags è stato introdotto dal PHP 4.3.0
La connessione al server sarà chiusa prima della fine dell'esecuzione dello script, a meno che questa non sia precedentemente chiusa esplicitamente richiamando mysql_close().
Vedere anche mysql_pconnect() e mysql_close().
mysql_create_db() tenta di creare un nuovo database nel server associato all'identificativo di conmnessione specificato.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Esempio 1. Esempio creazione database MySQL
|
Per motivi di compatibilità con il passato, anche mysql_createdb() può essere usata. Questo è comunque sconsigliato.
Nota: La funzione mysql_create_db() è sconsigliata. Al suo posto è preferibile usare mysql_query() per inviare un'istruzione SQL CREATE DATABASE.
Vedere anche: mysql_drop_db(), mysql_query().
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
mysql_data_seek() muove il puntatore di riga interno del risultato MySQL associato all'identificativo specificato per puntare ad un determinato numero di riga. La successiva chiamata a mysql_fetch_row() dovrebbe restituire questa riga.
numero_riga inizia da 0. numero_riga dovrebbe essere un valore nell'intervallo che va da 0 a mysql_num_rows - 1.
Nota: La funzione mysql_data_seek() può essere usata solo insieme a mysql_query(), non con mysql_unbuffered_query().
Esempio 1. Esempio seek dati MySQL
|
Vedere anche: mysql_query(), mysql_num_rows().
mysql_db_name() accetta come primo paramentro il puntatore al risultato dalla chiamata a mysql_list_dbs(). Il parametro riga è un indice compreso nell'intervallo del risultato.
Se intercorre un errore, viene restituito FALSE. Usare mysql_errno() e mysql_error() per determinare la natura dell'errore.
Per motivi di compatibilità con il passato, anche mysql_dbname() è è accettata. Questo comunque è sconsigliato.
Restituisce una risorsa risultato della query se è stato possibile eseguire quest'ultima, oppure FALSE in caso d'errore. La funzione restituisce TRUE/FALSE anche per le query INSERT/UPDATE/DELETE per indicarne il successo/fallimento.
mysql_db_query() seleziona un database ed esegue una query su di esso. Se l'identificativo di connessione opzionale non è specificato, la funzione proverà a cercare una connessione aperta al server MySQL e se tale connessione non viene trovata cercherà di crearne una come se mysql_connect() fosse chiamata senza argomenti.
Si informa che questa funzione NON commuta al database al quale si era connessi prima. in altre parole, non si può usare questa funzione per eseguire temporaneamente una query sql su un altro database, si deve commutare manualmente. Gli utenti sono fortemente incoraggiati ad usare la sintassi database.tabella nelle loro query sql in questa funzione.
Vedere anche mysql_connect() e mysql_query().
Nota: Questa funzione è stata sconsigliata a partire dal PHP 4.0.6. Non usare questa funzione.Usare invece mysql_select_db() e mysql_query().
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
mysql_drop_db() tenta di eliminare (cancellare) un intero database dal server associato all'identificativo di connessione specificato.
Per motivi di compatibilità con il passato, anche mysql_dropdb() può essere usato. Questa è comunque sconsigliato.
Nota: La funzione mysql_drop_db() è sconsigliata. Al suo posto è preferibile usare mysql_query() per inviare una istruzione SQL DROP DATABASE.
Vedere anche: mysql_create_db(), mysql_query().
(PHP 3, PHP 4, PHP 5)
mysql_errno -- Restituisce il valore numerico del messaggio di errore della precedente operazione MySQLRestituisce il numero di errore dall'ultima funzione MySQL, oppure 0 (zero) se nessun errore è intercorso.
Gli errori ritornano dal database MySQL senza visualizzare i messaggi di avvertimento. Usando invece mysql_errno() si recupera il codice di errore. Notare che questa funzione restituisce solo il codice errore della più recente funzione MySQL eseguita (ad esclusione di mysql_error() e mysql_errno()), quindi se la si vuole usare, assicurarsi di controllare il valore prima di richiamare un'altra funzione MySQL.
Esempio 1. Esempio di mysql_errno
L'esempio riportato sopra dovrebbe produrre il seguente output:
|
Nota: Se l'argomento opzionale è specificato la connessione indicata viene usata per recuperare il codice d'erroe. Altrimenti viene usata l'ultima connessione aperta.
Vedere anche: mysql_error()
(PHP 3, PHP 4, PHP 5)
mysql_error -- Restituisce il testo del messagio di errore della precedente operazione MySQLRestituisce il testo dell'errore dall'ultima funzione MySQL, oppure '' (la stringa vuota) se nessun errore intercorre.
Gli errori ritornano dal database MySQL senza visualizzare i messaggi di avvertimento. Si usa invece mysql_error() per recuperare il testo dell'errore. Notare che questa funzione restituisce solo il testo dell'errore della più recente funzione MySQL eseguita (ad esclusione di mysql_error() e mysql_errno()), quindi se la si vuole usare, assicurarsi di controllare il valore prima di richiamare un'altra funzione MySQL.
Esempio 1. mysql_error Example
L'esempio riportato sopra dovrebbe produrre il seguente output:
|
Nota: Se l'argomento opzionale è specificato la connessione indicata viene usata per recuperare il codice d'erroe. Altrimenti viene usata l'ultima connessione aperta.
Vedere anche: mysql_errno()
(PHP 4 >= 4.0.3, PHP 5)
mysql_escape_string -- Aggiunge le sequenze di escape in una stringa per l'uso in mysql_query.Questa funzione aggiunge le sequenze di escape a stringa_senza_escape, in modo che sia sicuro usarla in mysql_query().
Nota: mysql_escape_string() non aggiunge le sequenze di escape a % ed a _.
Questa funzione è identica a mysql_real_escape_string() eccetto che mysql_real_escape_string() accetta un identificativo di connessione ed aggiunge le sequenze di escape alla stringa in base al set di caratteri corrente. mysql_escape_string() non accetta come argomento un identificativo di connessione e non rispetta le impostazioni del corrente set di caratteri.
Esempio 1. Esempio di mysql_escape_string()
L'esempio riportato sopra dovrebbe produrre il seguente output:
|
Vedere anche: mysql_real_escape_string(), addslashes(), e la direttiva magic_quotes_gpc .
(PHP 3, PHP 4, PHP 5)
mysql_fetch_array -- Carica una riga del risultato come un array associativo, un array numerico o entrambi.Restituisce un array che corrisponde alla riga caricata o FALSE se non ci sono più righe.
mysql_fetch_array() è una versione estesa di mysql_fetch_row(). Oltre a memorizzare i dati del risultato in array con indice numerico, questa li memorizza anche con indici associativi usando i nomi dei campi come chiavi.
Se due o più colonne del risultato hanno gli stessi nomi di campo, l'ultima colonna avrà la precedenza. Per accedere alle altre colonne con lo stesso nome, si deve usare l'indice numerico della colonna o farne un alias. Per le colonne-alias, non si può accedere al contenuto con il nome della colonna originale (in questo esempio si usa 'campo').
Una cosa importante da notare è che l'uso di mysql_fetch_array() non è significativamente più lento dell'uso di mysql_fetch_row(); questo fornisce un significativo valore aggiunto.
Il secondo argomento opzionale tipo_risultato in mysql_fetch_array() è una costante e può assumere i seguenti valori: MYSQL_ASSOC, MYSQL_NUM e MYSQL_BOTH. Questa caratteristica è stata aggiunta nel PHP 3.0.7. MYSQL_BOTH è il valore predefinito per questo argomento.
Usando MYSQL_BOTH, si ottiene un array con entrambe gli indici (associativo e numerico). Usando MYSQL_ASSOC, si ottengono solo gli indici associativi (stesso funzionamento di mysql_fetch_assoc()), usando MYSQL_NUM, si ottengono solo gli indici numerici (stesso funzionamento di mysql_fetch_row()).
Nota: I nomi dei campi restituiti da questa funzione sono case-sensitive.
Esempio 2. mysql_fetch_array() con MYSQL_NUM
|
Esempio 3. mysql_fetch_array() con MYSQL_ASSOC
|
Esempio 4. mysql_fetch_array() con MYSQL_BOTH
|
Per maggiori dettagli, vedere anche mysql_fetch_row() e mysql_fetch_assoc().
Restituisce un array associativo che corrisponde alla riga caricata o FALSE se non ci sono più righe.
mysql_fetch_assoc() è equivalente alla chiamata di mysql_fetch_array() con MYSQL_ASSOC come secondo parametro opzionale. Questa restituisce solo un array associativo. Questo è il modo incui mysql_fetch_array() funzionava originalmente. Se è necessario l'indice numerico al posto di quello associativo, usare mysql_fetch_array().
Se due o più colonne del risultato hanno gli stessi nomi di campo, l'ultima colonna avrà la precedenza. Per accedere alle altre colonne con lo stesso nome, si deve accedere al risultato con l'indice numerico usando mysql_fetch_row() oppure aggiunger degli alias. Vedere l'esempio nella descrizione di mysql_fetch_array() per quanto concerne gli alias.
Una cosa importante da notare è che l'uso di mysql_fetch_assoc() non è significativamente più lento dell'uso di mysql_fetch_row(); questo fornisce un significativo valore aggiunto.
Esempio 1. Un esteso esempio di mysql_fetch_assoc()
|
Vedere anche mysql_fetch_row(), mysql_fetch_array(), mysql_query() e mysql_error().
(PHP 3, PHP 4, PHP 5)
mysql_fetch_field -- Ottiene informazioni sulla colonna da un risultato e le restituisce come oggettoRestituisce un oggetto contenente le informazioni di un campo.
mysql_fetch_field() può essere usata al fine di ottenere informazioni circa i campi di un determinato risultato di una query. Se l'indice del campo non è specificato, il successivo campo non ancora recuperato da mysql_fetch_field() viene considerato.
Le proprietà dell'oggetto sono:
name - nome della colonna
table - nome della tabella a cui appartiene la colonna
max_length - massima lunghezza della colonna
not_null - 1 se la colonna non può essere NULL
primary_key - 1 se la colonna è una chiave primaria
unique_key - 1 se la colonna è una chiave unica
multiple_key - 1 se la colonna è una chiave non-unica
numeric - 1 se la colonna è numerica
blob - 1 se la colonna è un BLOB
type - il tipo della colonna
unsigned - 1 se la colonna è senza segno
zerofill - 1 se la colonna è completata da zeri
Esempio 1. mysql_fetch_field()
|
Vedere anche mysql_field_seek().
Restituisce un array che corrisponde alle lunghezze di ogni campo nell'ultima riga caricata da mysql_fetch_row() oppure FALSE in caso di errore.
mysql_fetch_lengths() memorizza le lunghezze di ogni colonna dell'ultima riga restituita da mysql_fetch_row(), mysql_fetch_array() e mysql_fetch_object() in un array, iniziando con un indice pari a 0.
Vedere anche: mysql_fetch_row().
Restituisce un oggetto con proprietà che corrispondono alla riga caricata oppure FALSE se non ci sono più righe.
mysql_fetch_object() è simile a mysql_fetch_array(), con una differenza - viene restituito un oggetto invece che un array. Indirettamente, questo significa che si ha solo accesso ai dati attraverso i nomi dei campi e non attraverso il loro indice (i mumeri sono nomi di proprietà illeciti).
<?php /* questo è valido */ echo $riga->campo; /* questo non è valido */ echo $riga->0; ?> |
In termini di velocità, la funzione è identica a mysql_fetch_array() e quasi veloce come mysql_fetch_row() (la differenza è insignificante).
Esempio 1. Esempio di mysql_fetch_object()
|
Vedere anche: mysql_fetch_array() e mysql_fetch_row().
Restituisce un array che corrisponde ad una riga caricata oppure FALSE se non ci sono più righe.
mysql_fetch_row() carica una riga di dati dal risultato associato all'identificativo specificato. La riga è restituita com un array. Ogni colonna del risultato è memorizzata in un indice dell'array, partendo dall'indice 0.
La susseguente chiamata a mysql_fetch_row() restituisce la successiva riga nell'intervallo del risultato oppure FALSE se non ci sono più righe.
Vedere anche: mysql_fetch_array(), mysql_fetch_object(), mysql_data_seek(), mysql_fetch_lengths() e mysql_result().
(PHP 3, PHP 4, PHP 5)
mysql_field_flags -- Ottine i flag associati al campo specificato di un risultatomysql_field_flags() restituisce i flag del campo specificato. I flag sono restituiti come singole parole per flag separate da un singolo spazio, in modo che sia possibile suddividere il valore restituito usando explode().
I seguenti flag sono restituiti, se la versione di MySQL è abbastanza aggiornata da supportarli: "not_null", "primary_key", "unique_key", "multiple_key", "blob", "unsigned", "zerofill", "binary", "enum", "auto_increment", "timestamp".
Per motivi di compatibilità con il passato, anche mysql_fieldflags() può essere usata. Questo comunque è sconsigliato.
mysql_field_len() restituisce la lunghezza del campo specificato.
Per motivi di compatibilità con il passato, anche mysql_fieldlen() può essere usata. Questo comunque è sconsigliato.
mysql_field_name() restituisce il nome del campo specificato dall'indice. risultato deve essere un identificativo di risultato valido e indice_campo è lo spiazzamento numerico del campo.
Nota: indice_campo inizia da 0.
Es. L'indice del terzo campo è in realtà 2, l'indice del quarto campo è 3 e così via.
Esempio 1. Esempio di mysql_field_name()
L'esempio riportato sopra dovrebbe produrre il seguente output:
|
Per motivi di compatibilità con il passato, anche mysql_fieldname() può essere usata. Questo comunque è sconsigliato.
(PHP 3, PHP 4, PHP 5)
mysql_field_seek -- Imposta il puntatore al risultato ad un determinato indice di campoEsegue il seek ad uno specifico indice di campo. Se la successiva chiamata a mysql_fetch_field() non include un indice di campo, quello specificato in mysql_field_seek() viene restituito.
Vedere anche: mysql_fetch_field().
(PHP 3, PHP 4, PHP 5)
mysql_field_table -- Ottiene il nome della tabella in cui si trova il campo specificatoOttiene il nome della tabella in cui si trova il campo specificato.
Per motivi di compatibilità con il passato, anche mysql_fieldtable() può essere usata. Questo comunque è sconsigliato.
mysql_field_type() è simile alla funzione mysql_field_name(). Gli argomenti sono identici, ma viene restituito il tipo del campo. Il tipo del campo sarà uno dei seguenti: "int", "real", "string", "blob" ed altri come dettagliati nella Documentazione di MySQL.
Esempio 1. Tipi di campo MySQL
L'esempio riportato sopra dovrebbe produrre il seguente output:
|
Per motivi di compatibilità con il passato, anche mysql_fieldtype() può essere usata. Questo comunque è sconsigliato.
mysql_free_result() libera utuuta la memoria associata all'identificativo del risultato risultato.
mysql_free_result() deve essere richiamata solo se si è preoccupati sulla quantità di memoria usata dalle query che restituiscono dei grandi risultati. Tutta la memoria associata al risultato è automaticamente liberata al termine dell'esecuzione dello script.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Per motivi di compatibilità con il passato, anche mysql_freeresult() può essere usata. Questo comunque è sconsigliato.
mysql_get_client_info() restituisce una stringa che rappresenta la versione della libraria client.
Vedere anche: mysql_get_host_info(), mysql_get_proto_info() e mysql_get_server_info().
mysql_get_host_info() restituisce una stringa che descrive il tipo di connessione in uso per identificativo_connessione, includendo il nome dell'host del server. Se identificativo_connessione è omesso, sarà usata l'ultima connessione aperta.
Esempio 1. Esempio di mysql_get_host_info
L'esempio riportato sopra dovrebbe produrre il seguente output:
|
Vedere anche: mysql_get_client_info(), mysql_get_proto_info() e mysql_get_server_info().
mysql_get_proto_info() restituisce la versione del protocollo usata dalla connessione identificativo_connessione. Se identificativo_connessione è omesso, sarà usata l'ultima connessione aperta.
Esempio 1. Esempio di mysql_get_proto_info
L'esempio riportato sopra dovrebbe produrre il seguente output:
|
Vedere anche: mysql_get_client_info(), mysql_get_host_info() e mysql_get_server_info().
mysql_get_server_info() restituisce la versione del server usato dalla connessione identificativo_connessione. Se identificativo_connessione è omesso, sarà usata l'ultima connessione aperta.
Esempio 1. Esempio di mysql_get_server_info
L'esempio riportato sopra dovrebbe produrre il seguente output:
|
Vedere anche: mysql_get_client_info(), mysql_get_host_info() e mysql_get_proto_info().
mysql_info() restituisce informazioni dettagliate relative all'ultima query usando lo specifico identificativo_connessione. Se identificativo_connessione non è specificato, viene considerata l'ultima connessione aperta.
mysql_info() restituisce una stringa per tutte le istruzioni elencate di seguito. Per tutte le altre restituisce FALSE. Il formato della stringa dipende dall'istruzione data.
Esempio 1. Istruzioni MySQL significative
|
Nota: mysql_info() restituisce un valore non FALSE per le istruzioni INSERT ... VALUES solo se nell'istruzione sono specificate liste di valori multipli.
Vedere anche: mysql_affected_rows()
(PHP 3, PHP 4, PHP 5)
mysql_insert_id -- Ottiene l'identificativo generato dalla precedente operazione INSERTmysql_insert_id() restituisce l'identificativo generato per una colonna AUTO_INCREMENT dal precedente query INSERT usando lo specifico identificativo_connessione. Se identificativo_connessione non è specificato, viene considerata l'ultima connessione aperta.
mysql_insert_id() restituisce 0 se la precedente query non ha generato un valore AUTO_INCREMENT. Se è necessario salvare il valore per usarlo in seguito, assicurarsi di richiamare mysql_insert_id() immediatamente dopo la query che ha generato il valore.
Nota: Il valore della funzione SQL LAST_INSERT_ID() di MySQL contiene sempre il più recente valore AUTO_INCREMENT generato e non è azzerato dalle query.
Avvertimento |
mysql_insert_id() converte il tipo restituito dalla funzione nativa dell'API C di MySQL mysql_insert_id() al tipo long (chiamata int nel PHP). Se la colonna AUTO_INCREMENT è del tipo BIGINT, il valore restituito da mysql_insert_id() sarà inesatto. In questo caso si usi la funzione SQL di MySQL LAST_INSERT_ID() in una query SQL. |
Esempio 1. Esempio di mysql_insert_id
|
Vedere anche: mysql_query().
mysql_list_dbs() restituirà un risultato puntatore contenete i database resi disponibili dal demone mysql. Usare la funzione mysql_tablename() per esplorare questo risultato puntatore o qualsiasi funzione per i risultati delle tabelle, come mysql_fetch_array().
Esempio 1. Esempio di mysql_list_dbs()
L'esempio riportato sopra dovrebbe produrre il seguente output:
|
Nota: Il codice riportato sopra dovrebbe funzionare facilmente con mysql_fetch_row() o altre funzioni simili.
Per motivi di compatibilità con il passato, anche mysql_listdbs() può essere usata. Questo comunque è sconsigliato.
Vedere anche mysql_db_name().
mysql_list_fields() recupera le informazioni relative ad una data tabella. Gli argomenti sono il nome del database ed il nome della tabella. Viene restituito un risultato puntatore che può essere usato con mysql_field_flags(), mysql_field_len(), mysql_field_name() e mysql_field_type().
Esempio 1. Esempio di mysql_list_fields()
L'esempio riportato sopra dovrebbe produrre il seguente output:
|
Per motivi di compatibilità con il passato, anche mysql_listfields() può essere usata. Questo comunque è sconsigliato.
mysql_list_processes() restituisce un risultato puntatore che descrive i thread attuali del server.
Esempio 1. Esempio di mysql_list_processes()
L'esempio riportato sopra dovrebbe produrre il seguente output:
|
Vedere anche: mysql_thread_id()
mysql_list_tables() accetta un nome di database e restituisce un risultato puntatore in modo molto simile alla funzione mysql_query(). Usare la funzione mysql_tablename() per esplorare questo risultato puntatore o qualsiasi funzione per i risultati delle tabelle, come mysql_fetch_array().
Il parametro database è il nome del database da cui recuperare la lista di tabelle. in caso di errore, mysql_list_tables() restituisce FALSE.
Per motivi di compatibilità con il passato, anche mysql_listtables() può essere usata. Questo comunque è sconsigliato.
Esempio 1. mysql_list_tables() example
|
Vedere anche: mysql_list_dbs() e mysql_tablename().
mysql_num_fields() restituisce il numero di campi in un risultato.
Vedere anche: mysql_select_db(), mysql_query(), mysql_fetch_field() e mysql_num_rows().
Per motivi di compatibilità con il passato, anche mysql_numfields() può essere usata. Questo comunque è sconsigliato.
mysql_num_rows() restituisce il numero di righe in un risultato. Questo comando è valido solo per le istruzioni SELECT. Per recuperare il numero di righe coinvolte dalle query INSERT, UPDATE o DELETE, usare mysql_affected_rows().
Esempio 1. Esempio di mysql_num_rows()
|
Nota: Se si usa mysql_unbuffered_query(), mysql_num_rows() non restituirà il valore corretto finché non sono recuperate tutte le righe del risultato.
Vedere anche: mysql_affected_rows(), mysql_connect(), mysql_data_seek(), mysql_select_db() e mysql_query().
Per motivi di compatibilità con il passato, anche mysql_numrows() può essere usata. Questo comunque è sconsigliato.
Restituisce un identificativo di connessione MySQL valido in caso di successo oppure FALSE in caso di errore.
mysql_pconnect() stabilisce una connessione ad un server MySQL. I seguenti valori predefiniti sono usati per i parametri opzionali mancanti: server = 'localhost:3306', nome_utente = nome dell'utente prprietario del processo server e password = password vuota. Il parametro flag_client può essere una combinatione delle costanti MYSQL_CLIENT_COMPRESS, MYSQL_CLIENT_IGNORE_SPACE o MYSQL_CLIENT_INTERACTIVE.
Il parametro server può includere una numero di porta. Es. "hostname:porta" o un percorso ad un socket es. ":/percorso/a/socket" per il localhost.
Nota: Il supporto per ":porta" è stato aggiunto nel PHP 3.0B4.
Il supportp per ":/percorso/a/socket" è stato aggiunto nel PHP 3.0.10.
mysql_pconnect() agisce in modo molto simile a mysql_connect() con due differenze principali.
Primo, quando si connette, la funzione tenta innanzitutto di trovare una connessione (persistente) già aperta avente gli stessi host, username e password. Se viene trovata una connessione, viene restituito un identificativo a questa anziché aprirne una nuova.
Secondo, la connessione al server SQL non sarà chiusa quando l'esecuzione dello script termina. La connessione rimane invece aperta per usi futuri (mysql_close() non chiuderà le connessioni stabilite da mysql_pconnect()).
Il parametro opzionale flag_client è diventato disponibile nel PHP 4.3.0.
Questo tipo di link è perciò chiamato 'persistente'.
Nota: Notare che questo tipo di connessione funziona solo se si usa PHP come modulo. Vedere la sezione Persistent Database Connections per maggiori informazioni.
Avvertimento |
L'uso di connessioni persistenti può richiedere un po' di messa a punto delle configurazioni di Apache e MySQL per assicurarsi di non eccedere il numero di connessioni consentite da MySQL. |
(PHP 4 >= 4.3.0, PHP 5)
mysql_ping -- Esegue un ping su una connessione al server o riconnette se non non esiste la connessionemysql_ping() controlla se una connessione al server funziona o meno. Se questa è caduta, viene tentata una riconnessione automatica. Questa funzione può essere usata dagli script che rimangono inattivi per un lungo periodo per controllare se il server ha chiuso la connessione o meno e riconnettersi se necessario. mysql_ping() restituisce TRUE se la connessione al server è funzionante, altrimenti FALSE.
Vedere anche: mysql_thread_id() e mysql_list_processes().
mysql_query() invia una query al database attualmente attivo sul server associato all'identificativo di conmnessione specificato. Se identificativo_connessione non è specificato, viene considerata l'ultima connessione aperta. Se nessuna connessione è aperta, la funzione prova a stabilire una connessione come se mysql_connect() fosse richiamata senza argomenti ed usa questa.
Il paramentro opzionale modo_risultato può essere MYSQL_USE_RESULT e MYSQL_STORE_RESULT. Il valore predefinito MYSQL_STORE_RESULT, così il risultato è bufferato. Vedere anche mysql_unbuffered_query() per la controparte di questo comportamento.
Nota: La stringa della query non dovrebbe terminare con un punto e virgola.
Solo per le istruzioni SELECT, SHOW, EXPLAIN o DESCRIBE mysql_query() restituisce un identificativo di risorsa o FALSE se la query non è stata eseguita correttamente. Per altri tipi di istruzioni SQL, mysql_query() restituisce TRUE in caso di successo e FALSE in caso di errore. Un valore restituito diverso da FALSE indica che la query era lecita ed è stata eseguita dal server. Questo non indica niente riguardo il numero di righe coinvolte o restituite. è assolutamente possibile che una query abbia successo ma che non coinvolga o restituisca nessuna riga.
La seguente query non è valida sintatticamente, quindi mysql_query() fallisce e restituisce FALSE:
La seguente query non è semanticamente valida se mia_colonna non è una colonna della tabella mia_tabella, quindi mysql_query() fallisce e retituisce FALSE:
mysql_query() fallisce e restituisce FALSE anche se non si hanno i permessi per accedere alle tabelle cui la query fa riferimento.
Assumendo che la query abbia succeesso, si può richiamare mysql_num_rows() per scoprire quante righe sono state restituite da un'istruzione SELECT o mysql_affected_rows() per scoprire quante righe sono state coinvolte da un'istruzione DELETE, INSERT, REPLACE o UPDATE.
Solo per le istruzioni SELECT, SHOW, DESCRIBE o EXPLAIN, mysql_query() restituisce un nuovo identificativo di risultato che si può passare a mysql_fetch_array() e ad altre funzioni che si occupano dei risultati delle tabelle. Quando si conclude il trattamento del risultato, si possono liberare le risorse associate ad esso richiamando mysql_free_result(). Comunqe la memoria sarà liberata automaticamente Al termnine dell'esecuzione dello script.
Vedere anche: 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() e mysql_connect().
(PHP 4 >= 4.3.0, PHP 5)
mysql_real_escape_string -- Aggiunge le sequenze di escape ai caratteri speciali in una stringa per l'uso in una istruzione SQL, tenendo conto dell'attuale set di caratteri della connessione.Questa funzione aggiunge le sequenza di escape ai caratteri speciali in stringa_senza_escape, tenendo conto dell'attuale set di caratteri della connessione in modo che sia sicuro usarla in mysql_query().
Nota: mysql_real_escape_string() non aggiunge le sequenze di escape a % ed a _.
Esempio 1. Esempio di mysql_real_escape_string()
L'esempio riportato sopra dovrebbe produrre il seguente output:
|
Vedere anche : mysql_escape_string() e mysql_character_set_name().
mysql_result() restituisce i contenuti di una cella da un risultato MySQL. L'argomento campo può essere l'indice o il nome del campo oppure il nome della tabella ed il nome del campo separati da un punto (nome_tabella.nome_campo). Se il nome della colonna ha un alias ('select foo as bar from...'), usare l'alias al posto del nome della colonna.
Quando si lavora con un risultato di grandi dimensioni, si dovrebbero considerare l'uso delle funzioni che caricano l'intera riga (specificate di seguito). Poiché queste funzioni restituiscono i contenuti di celle multiple in una chiamata a funzione, sono MOLTO più veloci di mysql_result(). Notare anche che specificare un indice numerico per l'argomento campo è molto più veloce che specificare un argomento del tipo nome_di_campo o nome_tabella.nome_campo.
Le chiamate a mysql_result() non dovrebbero esserse mescolate con chiamate ad altre funzioni che hanno a che fare con i risultati.
Alternative raccomandate per alte prestazioni: mysql_fetch_row(), mysql_fetch_array() e mysql_fetch_object().
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
mysql_select_db() imposta il database attualmente attivo sul server associato all'identificativo di connessione specificato. Se nessin identificativo di connesione è specificato, viene considerata l'ultima connessione aperta. Se nessuna connessione è aperta, la funzione proverà a stabilire una connessione come se mysql_connect() fosse richiamata senza argomenti ed userà questa.
Ogni chiamata successiva a mysql_query() sarà fatta sul database attivo.
Vedere anche: mysql_connect(), mysql_pconnect() e mysql_query().
Per motivi di compatibilità con il passato, anche mysql_selectdb() può essere usata. Questo comunque è sconsigliato.
mysql_stat() restituisce l'attuale stato del server.
Nota: mysql_stat() attualmente restituisce solo le seguenti informazioni: uptime, thread, query, tabelle aperte, tabelle svuotate e query al secondo. Per una lista completa delle altre variabili di stato si usi il comando SQL SHOW STATUS.
Esempio 1. mysql_stat() example
L'esempio riportato sopra dovrebbe produrre il seguente output:
|
mysql_tablename() prende il puntatore risultato dalla funzione mysql_list_tables() come un indice intero e restituisce il nome di una tabella. La funzione mysql_num_rows() può essere usata per determinare il numero di tabelle nel risultato puntatore. Usare la funzione mysql_tablename() per esplorare questo risultato puntatore o qualsiasi funzione per i risultati delle tabelle, come mysql_fetch_array().
Vedere anche: mysql_list_tables().
mysql_thread_id() restituisce l'attuale thread ID. Se La connessione è persa a ci si riconnette con mysql_ping(), il thread ID cambia. Questo significa che non si dovrebbe ottenere il thread ID e memorizzarlo per impieghi successivi. Si dovrebbe rilevare il thread ID quando è necessario.
Esempio 1. Esempio di mysql_thread_id()
L'esempio riportato sopra dovrebbe produrre il seguente output:
|
Vedere anche: mysql_ping() e mysql_list_processes().
(PHP 4 >= 4.0.6, PHP 5)
mysql_unbuffered_query -- Invia una query SQL a MySQL senza caricare e bufferare le righe risultantimysql_unbuffered_query() invia una query SQL query a MySQL senza caricare e bufferare le righe risultanti automaticamente come fa mysql_query(). Da una parte, questo risparmia un considerevole quantità di memoria con le query SQL che producono risulati di grandi dimensioni. Dall'altra parte, si può iniziare l'elaborazione dei risultati immediatamente dopo che la prima riga è stata recuperata: non si deve attendere finché la query SQL sia completamente eseguita. Quando si usano diverse connessioni a database, si deve specificare il paramentro opzionale identificativo_connessione.
Il parametro opzionale modo_risultato può essere MYSQL_USE_RESULT e MYSQL_STORE_RESULT. Il valore predefinito è MYSQL_USE_RESULT, quindi il risultato non è bufferato. Vedere anche mysql_query() per la controparte di questo comportamento.
Nota: I benefici di mysql_unbuffered_query() hanno un costo: non si può usare mysql_num_rows() su un risultato restituito da mysql_unbuffered_query(). Inoltre si debbono caricare tutte le righe risultanti da una query SQL non bufferata prima di poter inviare una nuova query SQL a MySQL.
vedere anche: mysql_query().
PDO_MYSQL is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to MySQL 3.x and 4.x databases.
PDO_MYSQL will take advantage of native prepared statement support present in MySQL 4.1 and higher. If you're using an older version of the mysql client libraries, PDO will emulate them for you.
Avvertimento |
Beware: MySQL tables do not support transactions by default. When writing transactional database code, MySQL will pretend that a transaction was initiated successfully, even when no transactional support is present. In addition, any DDL queries issued will implicitly commit any pending transactions. |
The constants below are defined by this driver, and will only be available when the extension has been either compiled into PHP or dynamically loaded at runtime. In addition, these driver-specific constants should only be used if you are using this driver. Using mysql-specific attributes with the postgres driver may result in unexpected behaviour. PDO::getAttribute() may be used to obtain the PDO_ATTR_DRIVER_NAME attribute to check the driver, if your code can run against multiple drivers.
If this attribute is set to TRUE on a PDOStatement, the MySQL driver will use the buffered versions of the MySQL API. If you're writing portable code, you should use PDOStatement::fetchAll() instead.
Esempio 1. Forcing queries to be buffered in mysql
|
The mysqli extension allows you to access the functionality provided by MySQL 4.1 and above. More information about the MySQL Database server can be found at http://www.mysql.com/
Documentation for MySQL can be found at http://dev.mysql.com/doc/.
Parts of this documentation included from MySQL manual with permissions of MySQL AB.
In order to have these functions available, you must compile PHP with support for the mysqli extension.
Nota: The mysqli extension is designed to work with the version 4.1.3 or above of MySQL. For previous versions, please see the MySQL extension documentation.
To install the mysqli extension for PHP, use the --with-mysqli=mysql_config_path/mysql_config configuration option where mysql_config_path represents the location of the mysql_config program that comes with MySQL versions greater than 4.1.
If you would like to install the mysql extension along with the mysqli extension you have to use the same client library to avoid any conflicts.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. MySQLi Configuration Options
Name | Default | Changeable | Changelog |
---|---|---|---|
mysqli.max_links | "-1" | PHP_INI_SYSTEM | Available since PHP 5.0.0. |
mysqli.default_port | "3306" | PHP_INI_ALL | Available since PHP 5.0.0. |
mysqli.default_socket | NULL | PHP_INI_ALL | Available since PHP 5.0.0. |
mysqli.default_host | NULL | PHP_INI_ALL | Available since PHP 5.0.0. |
mysqli.default_user | NULL | PHP_INI_ALL | Available since PHP 5.0.0. |
mysqli.default_pw | NULL | PHP_INI_ALL | Available since PHP 5.0.0. |
For further details and definitions of the above PHP_INI_* constants, see the chapter on configuration changes.
Breve descrizione dei parametri di configurazione.
The maximum number of MySQL connections per process.
The default TCP port number to use when connecting to the database server if no other port is specified. If no default is specified, the port will be obtained from the MYSQL_TCP_PORT environment variable, the mysql-tcp entry in /etc/services or the compile-time MYSQL_PORT constant, in that order. Win32 will only use the MYSQL_PORT constant.
The default socket name to use when connecting to a local database server if no other socket name is specified.
The default server host to use when connecting to the database server if no other host is specified. Doesn't apply in safe mode.
The default user name to use when connecting to the database server if no other name is specified. Doesn't apply in safe mode.
The default password to use when connecting to the database server if no other password is specified. Doesn't apply in safe mode.
Represents a connection between PHP and a MySQL database.
autocommit - turns on or off auto-commiting database modifications
change_user - changes the user of the specified database connection
character_set_name - returns the default character set for the database connection
close - closes a previously opened connection
commit - commits the current transaction
connect - opens a new connection to MySQL database server
debug - performs debugging operations
dump_debug_info - dumps debug information
get_client_info - returns client version
get_host_info - returns type of connection used
get_server_info - returns version of the MySQL server
get_server_version - returns version of the MySQL server
init - initializes mysqli object
info - retrieves information about the most recently executed query
kill - asks the server to kill a mysql thread
multi_query - performs multiple queries
more_results - check if more results exist from currently executed multi-query
next_result - reads next result from currently executed multi-query
options - set options
ping - pings a server connection or reconnects if there is no connection
prepare - prepares a SQL query
query - performs a query
real_connect - attempts to open a connection to MySQL database server
escape_string - escapes special characters in a string for use in a SQL statement, taking into account the current charset of the connection
rollback - rolls back the current transaction
select_db - selects the default database
set_charset - sets the default client character set
ssl_set - sets ssl parameters
stat - gets the current system status
stmt_init- initializes a statement for use with mysqli_stmt_prepare
store_result - transfers a resultset from last query
use_result - transfers an unbuffered resultset from last query
thread_safe - returns whether thread safety is given or not
affected_rows - gets the number of affected rows in a previous MySQL operation
client_info - returns the MySQL client version as a string
client_version - returns the MySQL client version as an integer
errno - returns the error code for the most recent function call
error - returns the error string for the most recent function call
field_count - returns the number of columns for the most recent query
host_info - returns a string representing the type of connection used
info - retrieves information about the most recently executed query
insert_id - returns the auto generated id used in the last query
protocol_version - returns the version of the MySQL protocol used
server_info - returns a string that represents the server version number
server_version - returns the version number of the server as an integer
sqlstate - returns a string containing the SQLSTATE error code for the last error
thread_id - returns the thread ID for the current connection
warning_count - returns the number of warnings generated during execution of the previous SQL statement
Represents a prepared statement.
bind_param - binds variables to a prepared statement
bind_result - binds variables to a prepared statement for result storage
close - closes a prepared statement
data_seek - seeks to an arbitrary row in a statement result set
execute - executes a prepared statement
fetch - fetches result from a prepared statement into bound variables
free_result - frees stored result memory for the given statement handle
result_metadata - retrieves a resultset from a prepared statement for metadata information
prepare - prepares a SQL query
send_long_data - sends data in chunks
reset - resets a prepared statement
store_result - buffers complete resultset from a prepared statement
affected_rows - returns affected rows from last statement execution
errno - returns errorcode for last statement function
error - returns errormessage for last statement function
field_count - returns the number of columns in a result set
id - returns the statement identifier
insert_id - returns the value generated for an AUTO_INCREMENT column by the prepared statement
num_rows - returns the number of rows in the result set
param_count - returns number of parameter for a given prepare statement
sqlstate - returns a string containing the SQLSTATE error code for the last statement function
Represents the result set obtained from a query against the database.
close - closes resultset
data_seek - moves internal result pointer
fetch_field - gets column information from a resultset
fetch_fields - gets information for all columns from a resulset
fetch_field_direct - gets column information for specified column
fetch_array - fetches a result row as an associative array, a numeric array, or both.
fetch_assoc - fetches a result row as an associative array
fetch_object - fetches a result row as an object
fetch_row - gets a result row as an enumerated array
close - frees result memory
field_seek - set result pointer to a specified field offset
current_field - returns offset of current fieldpointer
field_count - returns number of fields in resultset
lengths - returns an array of columnlengths
num_rows - returns number of rows in resultset
type - returns MYSQLI_STORE_RESULT or MYSQLI_USE_RESULT
Tabella 2. MySQLi Constants
Name | Description |
---|---|
MYSQLI_READ_DEFAULT_GROUP (integer) | Read options from the named group from `my.cnf' or the file specified with MYSQLI_READ_DEFAULT_FILE |
MYSQLI_READ_DEFAULT_FILE (integer) | Read options from the named option file instead of from my.cnf |
MYSQLI_OPT_CONNECT_TIMEOUT (integer) | Connect timeout in seconds |
MYSQLI_OPT_LOCAL_INFILE (integer) | Enables command LOAD LOCAL INFILE |
MYSQLI_INIT_COMMAND (integer) | Command to execute when connecting to MySQL server. Will automatically be re-executed when reconnecting. |
MYSQLI_CLIENT_SSL (integer) | Use SSL (encrypted protocol). This option should not be set by application programs; it is set internally in the MySQL client library |
MYSQLI_CLIENT_COMPRESS (integer) | Use compression protocol |
MYSQLI_CLIENT_INTERACTIVE (integer) | Allow interactive_timeout seconds (instead of wait_timeout seconds) of inactivity before closing the connection. The client's session wait_timeout variable will be set to the value of the session interactive_timeout variable. |
MYSQLI_CLIENT_IGNORE_SPACE (integer) | Allow spaces after function names. Makes all functions names reserved words. |
MYSQLI_CLIENT_NO_SCHEMA (integer) | Don't allow the db_name.tbl_name.col_name syntax. |
MYSQLI_CLIENT_MULTI_QUERIES (integer) | |
MYSQLI_STORE_RESULT (integer) | For using buffered resultsets |
MYSQLI_USE_RESULT (integer) | For using unbuffered resultsets |
MYSQLI_ASSOC (integer) | Columns are returned into the array having the fieldname as the array index. |
MYSQLI_NUM (integer) | Columns are returned into the array having an enumerated index. |
MYSQLI_BOTH (integer) | Columns are returned into the array having both a numerical index and the fieldname as the associative index. |
MYSQLI_NOT_NULL_FLAG (integer) | Indicates that a field is defined as NOT NULL |
MYSQLI_PRI_KEY_FLAG (integer) | Field is part of a primary index |
MYSQLI_UNIQUE_KEY_FLAG (integer) | Field is part of a unique index. |
MYSQLI_MULTIPLE_KEY_FLAG (integer) | Field is part of an index. |
MYSQLI_BLOB_FLAG (integer) | Field is defined as BLOB |
MYSQLI_UNSIGNED_FLAG (integer) | Field is defined as UNSIGNED |
MYSQLI_ZEROFILL_FLAG (integer) | Field is defined as ZEROFILL |
MYSQLI_AUTO_INCREMENT_FLAG (integer) | Field is defined as AUTO_INCREMENT |
MYSQLI_TIMESTAMP_FLAG (integer) | Field is defined as TIMESTAMP |
MYSQLI_SET_FLAG (integer) | Field is defined as SET |
MYSQLI_NUM_FLAG (integer) | Field is defined as NUMERIC |
MYSQLI_PART_KEY_FLAG (integer) | Field is part of an multi-index |
MYSQLI_GROUP_FLAG (integer) | Field is part of GROUP BY |
MYSQLI_TYPE_DECIMAL (integer) | Field is defined as DECIMAL |
MYSQLI_TYPE_TINY (integer) | Field is defined as TINYINT |
MYSQLI_TYPE_SHORT (integer) | Field is defined as INT |
MYSQLI_TYPE_LONG (integer) | Field is defined as INT |
MYSQLI_TYPE_FLOAT (integer) | Field is defined as FLOAT |
MYSQLI_TYPE_DOUBLE (integer) | Field is defined as DOUBLE |
MYSQLI_TYPE_NULL (integer) | Field is defined as DEFAULT NULL |
MYSQLI_TYPE_TIMESTAMP (integer) | Field is defined as TIMESTAMP |
MYSQLI_TYPE_LONGLONG (integer) | Field is defined as BIGINT |
MYSQLI_TYPE_INT24 (integer) | Field is defined as MEDIUMINT |
MYSQLI_TYPE_DATE (integer) | Field is defined as DATE |
MYSQLI_TYPE_TIME (integer) | Field is defined as TIME |
MYSQLI_TYPE_DATETIME (integer) | Field is defined as DATETIME |
MYSQLI_TYPE_YEAR (integer) | Field is defined as YEAR |
MYSQLI_TYPE_NEWDATE (integer) | Field is defined as DATE |
MYSQLI_TYPE_ENUM (integer) | Field is defined as ENUM |
MYSQLI_TYPE_SET (integer) | Field is defined as SET |
MYSQLI_TYPE_TINY_BLOB (integer) | Field is defined as TINYBLOB |
MYSQLI_TYPE_MEDIUM_BLOB (integer) | Field is defined as MEDIUMBLOB |
MYSQLI_TYPE_LONG_BLOB (integer) | Field is defined as LONGBLOB |
MYSQLI_TYPE_BLOB (integer) | Field is defined as BLOB |
MYSQLI_TYPE_VAR_STRING (integer) | Field is defined as VARCHAR |
MYSQLI_TYPE_STRING (integer) | Field is defined as CHAR |
MYSQLI_TYPE_GEOMETRY (integer) | Field is defined as GEOMETRY |
MYSQLI_NEED_DATA (integer) | More data available for bind variable |
MYSQLI_NO_DATA (integer) | No more data available for bind variable |
MYSQLI_DATA_TRUNCATED (integer) | Data truncation occurred. Available since PHP 5.1.0 and MySQL 5.0.5. |
All Examples in the MySQLI documentation use the world database from MySQL AB. The world database can be found at http://dev.mysql.com/get/Downloads/Manual/world.sql.gz/from/pick
(PHP 5)
mysqli_affected_rows(no version information, might be only in CVS)
mysqli->affected_rows -- Gets the number of affected rows in a previous MySQL operationProcedural style:
int mysqli_affected_rows ( mysqli link )Object oriented style (property):
class mysqli {mysqli_affected_rows() returns the number of rows affected by the last INSERT, UPDATE, or DELETE query associated with the provided link parameter. If the last query was invalid, this function will return -1.
Nota: For SELECT statements mysqli_affected_rows() works like mysqli_num_rows().
The mysqli_affected_rows() function only works with queries which modify a table. In order to return the number of rows from a SELECT query, use the mysqli_num_rows() function instead.
An integer greater than zero indicates the number of rows affected or retrieved. Zero indicates that no records where updated for an UPDATE statement, no rows matched the WHERE clause in the query or that no query has yet been executed. -1 indicates that the query returned an error.
Nota: If the number of affected rows is greater than maximal int value, the number of affected rows will be returned as a string.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Affected rows (INSERT): 984 Affected rows (UPDATE): 168 Affected rows (DELETE): 815 Affected rows (SELECT): 169 |
(PHP 5)
mysqli_autocommit(no version information, might be only in CVS)
mysqli->autocommit -- Turns on or off auto-commiting database modificationsProcedural style:
bool mysqli_autocommit ( mysqli link, bool mode )Object oriented style (method)
class mysqli {mysqli_autocommit() is used to turn on or off auto-commit mode on queries for the database connection represented by the link object.
Nota: mysqli_autocommit() doesn't work with non transactional table types (like MyISAM or ISAM).
To determine the current state of autocommit use the SQL command 'SELECT @@autocommit'.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Autocommit is 1 |
This function is an alias of mysqli_stmt_bind_param(). For a detailled descripton see description of mysqli_stmt_bind_param().
Nota: mysqli_bind_param() is deprecated and will be removed.
This function is an alias of mysqli_stmt_bind_result(). For a detailled descripton see description of mysqli_stmt_bind_result().
Nota: mysqli_bind_result() is deprecated and will be removed.
(PHP 5)
mysqli_change_user(no version information, might be only in CVS)
mysqli->change_user -- Changes the user of the specified database connectionProcedural style:
bool mysqli_change_user ( mysqli link, string user, string password, string database )Object oriented style (method):
class mysqli {mysqli_change_user() is used to change the user of the specified database connection as given by the link parameter and to set the current database to that specified by the database parameter.
If desired, the NULL value may be passed in place of the database parameter resulting in only changing the user and not selecting a database. To select a database in this case use the mysqli_select_db() function.
In order to successfully change users a valid username and password parameters must be provided and that user must have sufficient permissions to access the desired database. If for any reason authorization fails, the current user authentication will remain.
Nota: Using this command will always cause the current database connection to behave as if was a completely new database connection, regardless of if the operation was completed successfully. This reset includes performing a rollback on any active transactions, closing all temporary tables, and unlocking all locked tables.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Default database: world Value of variable a is NULL |
(PHP 5)
mysqli_character_set_name(no version information, might be only in CVS)
mysqli->character_set_name -- Returns the default character set for the database connectionProcedural style:
string mysqli_character_set_name ( mysqli link )Object oriented style (method):
class mysqli {Returns the current character set for the database connection specified by the link parameter.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Current character set is latin1_swedish_ci |
This function is an alias of mysqli_character_set_name(). For a detailled descripton see description of mysqli_character_set_name().
(PHP 5)
mysqli_close(no version information, might be only in CVS)
mysqli->close -- Closes a previously opened database connectionProcedural style:
bool mysqli_close ( mysqli link )Object oriented style (method):
class mysqli {The mysqli_close() function closes a previously opened database connection specified by the link parameter.
(PHP 5)
mysqli_commit(no version information, might be only in CVS)
mysqli->commit -- Commits the current transactionProcedural style:
bool mysqli_commit ( mysqli link )Object oriented style (method)
class mysqli {Commits the current transaction for the database connection specified by the link parameter.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
The mysqli_connect_errno() function will return the last error code number for last call to mysqli_connect(). If no errors have occured, this function will return zero.
Nota: Client error message numbers are listed in the MySQL errmsg.h header file, server error message numbers are listed in mysqld_error.h. In the MySQL source distribution you can find a complete list of error messages and error numbers in the file Docs/mysqld_error.txt.
An error code value for the last call to mysqli_connect(), if it failed. zero means no error occurred.
mysqli_connect(), mysqli_connect_error(), mysqli_errno(), mysqli_error() e mysqli_sqlstate().
The mysqli_connect_error() function is identical to the corresponding mysqli_connect_errno() function in every way, except instead of returning an integer error code the mysqli_connect_error() function will return a string representation of the last error to occur for the last mysqli_connect() call. If no error has occured, this function will return an empty string.
mysqli_connect(), mysqli_connect_errno(), mysqli_errno(), mysqli_error() e mysqli_sqlstate().
(PHP 5)
mysqli_connect(no version information, might be only in CVS)
mysqli() -- Open a new connection to the MySQL serverProcedural style
mysqli mysqli_connect ( [string host [, string username [, string passwd [, string dbname [, int port [, string socket]]]]]] )Object oriented style (constructor):
class mysqli {The mysqli_connect() function attempts to open a connection to the MySQL Server running on host which can be either a host name or an IP address. Passing the NULL value or the string "localhost" to this parameter, the local host is assumed. When possible, pipes will be used instead of the TCP/IP protocol. If successful, the mysqli_connect() will return an object representing the connection to the database, or FALSE on failure.
The username and password parameters specify the username and password under which to connect to the MySQL server. If the password is not provided (the NULL value is passed), the MySQL server will attempt to authenticate the user against those user records which have no password only. This allows one username to be used with different permissions (depending on if a password as provided or not).
The dbname parameter if provided will specify the default database to be used when performing queries.
The port and socket parameters are used in conjunction with the host parameter to further control how to connect to the database server. The port parameter specifies the port number to attempt to connect to the MySQL server on, while the socket parameter specifies the socket or named pipe that should be used.
Nota: Specifying the socket parameter will not explicitly determine the type of connection to be used when connecting to the MySQL server. How the connection is made to the MySQL database is determined by the host parameter.
Returns a object which represents the connection to a MySQL Server or FALSE if the connection failed.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Host information: Localhost via UNIX socket |
(PHP 5)
mysqli_data_seek(no version information, might be only in CVS)
result->data_seek -- Adjusts the result pointer to an arbitary row in the resultProcedural style:
bool mysqli_data_seek ( mysqli_result result, int offset )Object oriented style (method):
class mysqli_result {The mysqli_data_seek() function seeks to an arbitrary result pointer specified by the offset in the result set represented by result. The offset parameter must be between zero and the total number of rows minus one (0..mysqli_num_rows() - 1).
Nota: This function can only be used with buffered results attained from the use of the mysqli_store_result() or mysqli_query() functions.
mysqli_store_result(), mysqli_fetch_row(), mysqli_fetch_array(), mysqli_fetch_assoc(), mysqli_fetch_object(), mysqli_query() e mysqli_num_rows().
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
City: Benin City Countrycode: NGA |
The mysqli_debug() function is used to perform debugging operations using the Fred Fish debugging library. The debug parameter is a string representing the debugging operation to perform.
Nota: To use the mysqli_debug() function you must complile the MySQL client library to support debugging.
(PHP 5)
mysqli_disable_reads_from_master(no version information, might be only in CVS)
mysqli->disable_reads_from_master -- Disable reads from masterProcedural style:
bool mysqli_disable_reads_from_master ( mysqli link )Object oriented style (method):
class mysqli {Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 5)
mysqli_dump_debug_info(no version information, might be only in CVS)
mysqli->dump_debug_info -- Dump debugging information into the logThis function is designed to be executed by an user with the SUPER privilege and is used to dump debugging information into the log for the MySQL Server relating to the connection specified by the link parameter.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 5)
mysqli_errno(no version information, might be only in CVS)
mysqli->errno -- Returns the error code for the most recent function callProcedural style:
int mysqli_errno ( mysqli link )Object oriented style (property):
class mysqli {The mysqli_errno() function will return the last error code for the most recent MySQLi function call that can succeed or fail with respect to the database link defined by the link parameter. If no errors have occured, this function will return zero.
Nota: Client error message numbers are listed in the MySQL errmsg.h header file, server error message numbers are listed in mysqld_error.h. In the MySQL source distribution you can find a complete list of error messages and error numbers in the file Docs/mysqld_error.txt.
An error code value for the last call, if it failed. zero means no error occurred.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Errorcode: 1193 |
Procedural style:
string mysqli_error ( mysqli link )Object oriented style (property)
class mysqli {The mysqli_error() function is identical to the corresponding mysqli_errno() function in every way, except instead of returning an integer error code the mysqli_error() function will return a string representation of the last error to occur for the database connection represented by the link parameter. If no error has occured, this function will return an empty string.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Errormessage: Unknown system variable 'a' |
This function is an alias of mysqli_stmt_execute(). For a detailled descripton see description of mysqli_stmt_execute().
Nota: mysqli_execute() is deprecated and will be removed.
(PHP 5)
mysqli_fetch_array(no version information, might be only in CVS)
result->fetch_array -- Fetch a result row as an associative, a numeric array, or bothProcedural style:
mixed mysqli_fetch_array ( mysqli_result result [, int resulttype] )Object oriented style (method):
class mysqli_result {Returns an array that corresponds to the fetched row or NULL if there are no more rows for the resultset represented by the result parameter.
mysqli_fetch_array() is an extended version of the mysqli_fetch_row() function. In addition to storing the data in the numeric indices of the result array, the mysqli_fetch_array() function can also store the data in associative indices, using the field names of the result set as keys.
Nota: I nomi dei campi restituiti da questa funzione sono case-sensitive.
Nota: This function sets NULL fields to PHP NULL value.
If two or more columns of the result have the same field names, the last column will take precedence and overwrite the earlier data. In order to access multiple columns with the same name, the numerically indexed version of the row must be used.
The optional second argument resulttype is a constant indicating what type of array should be produced from the current row data. The possible values for this parameter are the constants MYSQLI_ASSOC, MYSQLI_NUM, or MYSQLI_BOTH. By default the mysqli_fetch_array() function will assume MYSQLI_BOTH for this parameter.
By using the MYSQLI_ASSOC constant this function will behave identically to the mysqli_fetch_assoc(), while MYSQLI_NUM will behave identically to the mysqli_fetch_row() function. The final option MYSQLI_BOTH will create a single array with the attributes of both.
Returns an array that corresponds to the fetched row or NULL if there are no more rows in resultset.
mysqli_fetch_assoc(), mysqli_fetch_row(), mysqli_fetch_object(), mysqli_query() e mysqli_data_seek().
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Kabul (AFG) Qandahar (AFG) Herat (AFG) |
(PHP 5)
mysqli_fetch_assoc(no version information, might be only in CVS)
mysqli->fetch_assoc -- Fetch a result row as an associative arrayProcedural style:
array mysqli_fetch_assoc ( mysqli_result result )Object oriented style (method):
class mysqli_result {Returns an associative array that corresponds to the fetched row or NULL if there are no more rows.
The mysqli_fetch_assoc() function is used to return an associative array representing the next row in the result set for the result represented by the result parameter, where each key in the array represents the name of one of the result set's columns.
If two or more columns of the result have the same field names, the last column will take precedence. To access the other column(s) of the same name, you either need to access the result with numeric indices by using mysqli_fetch_row() or add alias names.
Nota: I nomi dei campi restituiti da questa funzione sono case-sensitive.
Nota: This function sets NULL fields to PHP NULL value.
Returns an array that corresponds to the fetched row or NULL if there are no more rows in resultset.
mysqli_fetch_array(), mysqli_fetch_row(), mysqli_fetch_object(), mysqli_query() e mysqli_data_seek().
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Pueblo (USA) Arvada (USA) Cape Coral (USA) Green Bay (USA) Santa Clara (USA) |
(PHP 5)
mysqli_fetch_field_direct(no version information, might be only in CVS)
result->fetch_field_direct -- Fetch meta-data for a single fieldProcedural style:
object mysqli_fetch_field_direct ( mysqli_result result, int fieldnr )Object oriented style (method):
class mysqli_result {mysqli_fetch_field_direct() returns an object which contains field definition informations from specified resultset. The value of fieldnr must be in the range from 0 to number of fields - 1.
Returns an object which contains field definition information or FALSE if no field information for specified fieldnr is available.
Tabella 1. Object attributes
Attribute | Description |
---|---|
name | The name of the column |
orgname | Original column name if an alias was specified |
table | The name of the table this field belongs to (if not calculated) |
orgtable | Original table name if an alias was specified |
def | The default value for this field, represented as a string |
max_length | The maximum width of the field for the result set. |
flags | An integer representing the bit-flags for the field. |
type | The data type used for this field |
decimals | The number of decimals used (for integer fields) |
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Name: SurfaceArea Table: Country max. Len: 10 Flags: 32769 Type: 4 |
(PHP 5)
mysqli_fetch_field(no version information, might be only in CVS)
result->fetch_field -- Returns the next field in the result setProcedural style:
object mysqli_fetch_field ( mysqli_result result )Object oriented style (method):
class mysqli_result {The mysqli_fetch_field() returns the definition of one column of a result set as an object. Call this function repeatedly to retrieve information about all columns in the result set. mysqli_fetch_field() returns FALSE when no more fields are left.
Returns an object which contains field definition information or FALSE if no field information is available.
Tabella 1. Object properties
Property | Description |
---|---|
name | The name of the column |
orgname | Original column name if an alias was specified |
table | The name of the table this field belongs to (if not calculated) |
orgtable | Original table name if an alias was specified |
def | The default value for this field, represented as a string |
max_length | The maximum width of the field for the result set. |
flags | An integer representing the bit-flags for the field. |
type | The data type used for this field |
decimals | The number of decimals used (for integer fields) |
mysqli_num_fields(), mysqli_fetch_field_direct(), mysqli_fetch_fields() e mysqli_field_seek().
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Name: Name Table: Country max. Len: 11 Flags: 1 Type: 254 Name: SurfaceArea Table: Country max. Len: 10 Flags: 32769 Type: 4 |
(PHP 5)
mysqli_fetch_fields(no version information, might be only in CVS)
result->fetch_fields -- Returns an array of objects representing the fields in a result setProcedural Style:
array mysqli_fetch_fields ( mysqli_result result )Object oriented style (method):
class mysqli_result {This function serves an identical purpose to the mysqli_fetch_field() function with the single difference that, instead of returning one object at a time for each field, the columns are returned as an array of objects.
Returns an array of objects which contains field definition information or FALSE if no field information is available.
Tabella 1. Object properties
Property | Description |
---|---|
name | The name of the column |
orgname | Original column name if an alias was specified |
table | The name of the table this field belongs to (if not calculated) |
orgtable | Original table name if an alias was specified |
def | The default value for this field, represented as a string |
max_length | The maximum width of the field for the result set. |
flags | An integer representing the bit-flags for the field. |
type | The data type used for this field |
decimals | The number of decimals used (for integer fields) |
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Name: Name Table: Country max. Len: 11 Flags: 1 Type: 254 Name: SurfaceArea Table: Country max. Len: 10 Flags: 32769 Type: 4 |
(PHP 5)
mysqli_fetch_lengths(no version information, might be only in CVS)
result->lengths -- Returns the lengths of the columns of the current row in the result setProcedural style:
array mysqli_fetch_lengths ( mysqli_result result )Object oriented style (property):
class mysqli_result {The mysqli_fetch_lengths() function returns an array containing the lengths of every column of the current row within the result set represented by the result parameter. If successful, a numerically indexed array representing the lengths of each column is returned or FALSE on failure.
An array of integers representing the size of each column (not including any terminating null characters). FALSE if an error occurred.
mysqli_fetch_lengths() is valid only for the current row of the result set. It returns FALSE if you call it before calling mysqli_fetch_row/array/object or after retrieving all rows in the result.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Field 1 has Length 3 Field 2 has Length 5 Field 3 has Length 13 Field 4 has Length 9 Field 5 has Length 6 Field 6 has Length 1 Field 7 has Length 6 Field 8 has Length 4 Field 9 has Length 6 Field 10 has Length 6 Field 11 has Length 5 Field 12 has Length 44 Field 13 has Length 7 Field 14 has Length 3 Field 15 has Length 2 |
(PHP 5)
mysqli_fetch_object(no version information, might be only in CVS)
result->fetch_object -- Returns the current row of a result set as an objectProcedural style:
mixed mysqli_fetch_object ( mysqli_result result )Object oriented style (method):
class mysqli_result {The mysqli_fetch_object() will return the current row result set as an object where the attributes of the object represent the names of the fields found within the result set. If no more rows exist in the current result set, NULL is returned.
Returns an object that corresponds to the fetched row or NULL if there are no more rows in resultset.
Nota: I nomi dei campi restituiti da questa funzione sono case-sensitive.
Nota: This function sets NULL fields to PHP NULL value.
mysqli_fetch_array(), mysqli_fetch_assoc(), mysqli_fetch_row(), mysqli_query() e mysqli_data_seek().
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Pueblo (USA) Arvada (USA) Cape Coral (USA) Green Bay (USA) Santa Clara (USA) |
(PHP 5)
mysqli_fetch_row(no version information, might be only in CVS)
result->fetch_row -- Get a result row as an enumerated arrayProcedural style:
mixed mysqli_fetch_row ( mysqli_result result )Object oriented style (method):
class mysqli_result {Returns an array that corresponds to the fetched row, or NULL if there are no more rows.
mysqli_fetch_row() fetches one row of data from the result set represented by result and returns it as an enumerated array, where each column is stored in an array offset starting from 0 (zero). Each subsequent call to the mysqli_fetch_row() function will return the next row within the result set, or FALSE if there are no more rows.
mysqli_fetch_row() returns an array that corresponds to the fetched row or NULL if there are no more rows in result set.
Nota: This function sets NULL fields to PHP NULL value.
mysqli_fetch_array(), mysqli_fetch_assoc(), mysqli_fetch_object(), mysqli_query() e mysqli_data_seek().
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Pueblo (USA) Arvada (USA) Cape Coral (USA) Green Bay (USA) Santa Clara (USA) |
This function is an alias of mysqli_stmt_fetch(). For a detailled descripton see description of mysqli_stmt_fetch().
Nota: mysqli_fetch() is deprecated and will be removed.
(PHP 5)
mysqli_field_count(no version information, might be only in CVS)
mysqli->field_count -- Returns the number of columns for the most recent queryProcedural style:
int mysqli_field_count ( mysqli link )Object oriented style (method):
class mysqli_result {Returns the number of columns for the most recent query on the connection represented by the link parameter. This function can be useful when using the mysqli_store_result() function to determine if the query should have produced a non-empty result set or not without knowing the nature of the query.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
(PHP 5)
mysqli_field_seek(no version information, might be only in CVS)
result->field_seek -- Set result pointer to a specified field offsetProcedural style:
bool mysqli_field_seek ( mysqli_result result, int fieldnr )Object oriented style (method):
class mysqli_result {Sets the field cursor to the given offset. The next call to mysqli_fetch_field() will retrieve the field definition of the column associated with that offset.
Nota: To seek to the beginning of a row, pass an offset value of zero.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Name: SurfaceArea Table: Country max. Len: 10 Flags: 32769 Type: 4 |
(PHP 5)
mysqli_field_tell(no version information, might be only in CVS)
result->current_field -- Get current field offset of a result pointerProcedural style:
int mysqli_field_tell ( mysqli_result result )Object oriented style (property):
class mysqli_result {Returns the position of the field cursor used for the last mysqli_fetch_field() call. This value can be used as an argument to mysqli_field_seek().
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Column 1: Name: Name Table: Country max. Len: 11 Flags: 1 Type: 254 Column 2: Name: SurfaceArea Table: Country max. Len: 10 Flags: 32769 Type: 4 |
(PHP 5)
mysqli_free_result(no version information, might be only in CVS)
result->free -- Frees the memory associated with a resultProcedural style:
void mysqli_free_result ( mysqli_result result )Object oriented style (method):
class mysqli_result {The mysqli_free_result() function frees the memory associated with the result represented by the result parameter, which was allocated by mysqli_query(), mysqli_store_result() or mysqli_use_result().
Nota: You should always free your result with mysqli_free_result(), when your result object is not needed anymore.
mysqli_query(), mysqli_stmt_store_result(), mysqli_store_result() e mysqli_use_result().
The mysqli_get_client_info() function is used to return a string representing the client version being used in the MySQLi extension.
A number that represents the MySQL client library version in format: main_version*10000 + minor_version *100 + sub_version. For example, 4.1.0 is returned as 40100.
This is useful to quickly determine the version of the client library to know if some capability exits.
(PHP 5)
mysqli_get_host_info(no version information, might be only in CVS)
mysqli->get_host_info -- Returns a string representing the type of connection usedProcdural style:
string mysqli_get_host_info ( mysqli link )Object oriented style (property):
class mysqli {The mysqli_get_host_info() function returns a string describing the connection represented by the link parameter is using (including the server host name).
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Host info: Localhost via UNIX socket |
This function is an alias of mysqli_stmt_result_metadata(). For a detailled descripton see description of mysqli_stmt_result_metadata().
Nota: mysqli_get_metadata() is deprecated and will be removed.
(PHP 5)
mysqli_get_proto_info(no version information, might be only in CVS)
mysqli->protocol_version -- Returns the version of the MySQL protocol usedProcedural style:
int mysqli_get_proto_info ( mysqli link )Object oriented style (property):
class mysqli {Returns an integer representing the MySQL protocol version used by the connection represented by the link parameter.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Protocol version: 10 |
(PHP 5)
mysqli_get_server_info(no version information, might be only in CVS)
mysqli->server_info -- Returns the version of the MySQL serverProcedural style:
string mysqli_get_server_info ( mysqli link )Object oriented style (property):
class mysqli {Returns a string representing the version of the MySQL server that the MySQLi extension is connected to (represented by the link parameter).
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Server version: 4.1.2-alpha-debug |
Procedural style:
int mysqli_get_server_version ( mysqli link )Object oriented style (property):
class mysqli {The mysqli_get_server_version() function returns the version of the server connected to (represented by the link parameter) as an integer.
The form of this version number is main_version * 10000 + minor_version * 100 + sub_version (i.e. version 4.1.0 is 40100).
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Server version: 40102 |
(PHP 5)
mysqli_info(no version information, might be only in CVS)
mysqli->info -- Retrieves information about the most recently executed queryProcedural style:
string mysqli_info ( mysqli link )Object oriented style (property)
class mysqli {The mysqli_info() function returns a string providing information about the last query executed. The nature of this string is provided below:
Tabella 1. Possible mysqli_info return values
Query type | Example result string |
---|---|
INSERT INTO...SELECT... | Records: 100 Duplicates: 0 Warnings: 0 |
INSERT INTO...VALUES (...),(...),(...) | Records: 3 Duplicates: 0 Warnings: 0 |
LOAD DATA INFILE ... | Records: 1 Deleted: 0 Skipped: 0 Warnings: 0 |
ALTER TABLE ... | Records: 3 Duplicates: 0 Warnings: 0 |
UPDATE ... | Rows matched: 40 Changed: 40 Warnings: 0 |
Nota: Queries which do not fall into one of the above formats are not supported. In these situations, mysqli_info() will return an empty string.
A character string representing additional information about the most recently executed query.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Records: 150 Duplicates: 0 Warnings: 0 |
Allocates or initializes a MYSQL object suitable for mysqli_options() and mysqli_real_connect().
Nota: Any subsequent calls to any mysqli function (except mysqli_options()) will fail until mysqli_real_connect() was called.
(PHP 5)
mysqli_insert_id(no version information, might be only in CVS)
mysqli->insert_id -- Returns the auto generated id used in the last queryProcedural style:
int mysqli_insert_id ( mysqli link )Object oriented style (property):
class mysqli {The mysqli_insert_id() function returns the ID generated by a query on a table with a column having the AUTO_INCREMENT attribute. If the last query wasn't an INSERT or UPDATE statement or if the modified table does not have a column with the AUTO_INCREMENT attribute, this function will return zero.
Nota: Performing an INSERT or UPDATE statement using the LAST_INSERT_ID() function will also modify the value returned by the mysqli_insert_id() function.
The value of the AUTO_INCREMENT field that was updated by the previous query. Returns zero if there was no previous query on the connection or if the query did not update an AUTO_INCREMENT value.
Nota: If the number is greater than maximal int value, mysqli_insert_id() will return a string.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
New Record has id 1. |
(PHP 5)
mysqli_kill(no version information, might be only in CVS)
mysqli->kill -- Asks the server to kill a MySQL threadProcedural style:
bool mysqli_kill ( mysqli link, int processid )Object oriented style (method)
class mysqli {This function is used to ask the server to kill a MySQL thread specified by the processid parameter. This value must be retrieved by calling the mysqli_thread_id() function.
Nota: To stop a running query you should use the SQL command KILL QUERY processid.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Error: MySQL server has gone away |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 5)
mysqli_more_results(no version information, might be only in CVS)
mysqli->more_results -- Check if there any more query results from a multi querymysqli_more_results() indicates if one or more result sets are available from a previous call to mysqli_multi_query().
mysqli_multi_query(), mysqli_next_result(), mysqli_store_result() e mysqli_use_result().
(PHP 5)
mysqli_multi_query(no version information, might be only in CVS)
mysqli->multi_query -- Performs a query on the databaseProcedural style:
bool mysqli_multi_query ( mysqli link, string query )Object oriented style (method):
class mysqli {The mysqli_multi_query() executes one or multiple queries which are concatenated by a semicolon.
To retrieve the resultset from the first query you can use mysqli_use_result() or mysqli_store_result(). All subsequent query results can be processed using mysqli_more_results() and mysqli_next_result().
mysqli_multi_query() only returns FALSE if the first statement failed. To retrieve subsequent errors from other statements you have to call mysqli_next_result() first.
mysqli_use_result(), mysqli_store_result(), mysqli_next_result() e mysqli_more_results().
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
my_user@localhost ----------------- Amersfoort Maastricht Dordrecht Leiden Haarlemmermeer |
(PHP 5)
mysqli_next_result(no version information, might be only in CVS)
mysqli->next_result -- Prepare next result from multi_querymysqli_next_result() prepares next result set from a previous call to mysqli_multi_query() which can be retrieved by mysqli_store_result() or mysqli_use_result().
mysqli_multi_query(), mysqli_more_results(), mysqli_store_result() e mysqli_use_result().
(PHP 5)
mysqli_num_fields(no version information, might be only in CVS)
result->field_count -- Get the number of fields in a resultProcedural style:
int mysqli_num_fields ( mysqli_result result )Object oriented style (property):
class mysqli_result {mysqli_num_fields() returns the number of fields from specified result set.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Result set has 5 fields. |
Procedural style:
int mysqli_num_rows ( mysqli result )Object oriented style (property):
class mysqli {Returns the number of rows in the result set.
The use of mysqli_num_rows() depends on whether you use buffered or unbuffered result sets. In case you use unbuffered resultsets mysqli_num_rows() will not correct the correct number of rows until all the rows in the result have been retrieved.
Returns number of rows in the result set.
Nota: If the number of rows is greater than maximal int value, the number will be returned as a string.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Result set has 239 rows. |
Procedural style:
bool mysqli_options ( mysqli link, int option, mixed value )Object oriented style (method)
class mysqli {mysqli_options() can be used to set extra connect options and affect behavior for a connection.
This function may be called multiple times to set several options.
mysqli_options() should be called after mysqli_init() and before mysqli_real_connect().
The parameter option is the option that you want to set, the value is the value for the option. The parameter option can be one of the following values:
Tabella 1. Valid options
Name | Description |
---|---|
MYSQLI_OPT_CONNECT_TIMEOUT | connection timeout in seconds |
MYSQLI_OPT_LOCAL_INFILE | enable/disable use of LOAD LOCAL INFILE |
MYSQLI_INIT_CMD | command to execute after when connecting to MySQL server |
MYSQLI_READ_DEFAULT_FILE | Read options from named option file instead of my.cnf |
MYSQLI_READ_DEFAULT_GROUP | Read options from the named group from my.cnf or the file specified with MYSQL_READ_DEFAULT_FILE. |
This function is an alias of mysqli_stmt_param_count(). For a detailled descripton see description of mysqli_stmt_param_count().
Nota: mysqli_param_count() is deprecated and will be removed.
(PHP 5)
mysqli_ping(no version information, might be only in CVS)
mysqli->ping -- Pings a server connection, or tries to reconnect if the connection has gone downProcedural style:
bool mysqli_ping ( mysqli link )Object oriented style (method):
class mysqli {Checks whether the connection to the server is working. If it has gone down, and global option mysqli.reconnect is enabled an automatic reconnection is attempted.
This function can be used by clients that remain idle for a long while, to check whether the server has closed the connection and reconnect if necessary.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Our connection is ok! |
(PHP 5)
mysqli_prepare(no version information, might be only in CVS)
mysqli->prepare -- Prepare a SQL statement for executionProcedure style:
mysqli_stmt mysqli_prepare ( mysqli link, string query )Object oriented style (method)
class mysqli {mysqli_prepare() prepares the SQL query pointed to by the null-terminated string query, and returns a statement handle to be used for further operations on the statement. The query must consist of a single SQL statement.
Nota: You should not add a terminating semicolon or \g to the statement.
The parameter query can include one or more parameter markers in the SQL statement by embedding question mark (?) characters at the appropriate positions.
Nota: The markers are legal only in certain places in SQL statements. For example, they are allowed in the VALUES() list of an INSERT statement (to specify column values for a row), or in a comparison with a column in a WHERE clause to specify a comparison value.
However, they are not allowed for identifiers (such as table or column names), in the select list that names the columns to be returned by a SELECT statement, or to specify both operands of a binary operator such as the = equal sign. The latter restriction is necessary because it would be impossible to determine the parameter type. It's not allowed to compare marker with NULL by ? IS NULL too. In general, parameters are legal only in Data Manipulation Languange (DML) statements, and not in Data Defination Language (DDL) statements.
The parameter markers must be bound to application variables using mysqli_stmt_bind_param() and/or mysqli_stmt_bind_result() before executing the statement or fetching rows.
mysqli_stmt_execute(), mysqli_stmt_fetch(), mysqli_stmt_bind_param(), mysqli_stmt_bind_result() e mysqli_stmt_close().
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Amersfoort is in district Utrecht |
(PHP 5)
mysqli_query(no version information, might be only in CVS)
mysqli->query -- Performs a query on the databaseProcedural style:
mixed mysqli_query ( mysqli link, string query [, int resultmode] )Object oriented style (method):
class mysqli {The mysqli_query() function is used to simplify the act of performing a query against the database represented by the link parameter.
Functionally, using this function is identical to calling mysqli_real_query() followed either by mysqli_use_result() or mysqli_store_result() where query is the query string itself and resultmode is either the constant MYSQLI_USE_RESULT or MYSQLI_STORE_RESULT depending on the desired behavior. By default, if the resultmode is not provided MYSQLI_STORE_RESULT is used.
If you execute mysqli_query() with resultmode MYSQLI_USE_RESULT all subsequent calls will return error Commands out of sync unless you call mysqli_free_result().
Restituisce TRUE in caso di successo, FALSE in caso di fallimento. For SELECT, SHOW, DESCRIBE or EXPLAIN mysqli_query() will return a result object.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Table myCity successfully created. Select returned 10 rows. Error: Commands out of sync; You can't run this command now |
(PHP 5)
mysqli_real_connect(no version information, might be only in CVS)
mysqli->real_connect -- Opens a connection to a mysql serverProcedural style
bool mysqli_real_connect ( mysqli link [, string hostname [, string username [, string passwd [, string dbname [, int port [, string socket [, int flags]]]]]]] )Object oriented style (method)
class mysqli {mysqli_real_connect() attempts to establish a connection to a MySQL database engine running on hostname.
This function differs from mysqli_connect():
mysqli_real_connect() needs a valid object which has to be created by function mysqli_init()
With function mysqli_options() you can set various options for connection.
With the parameter flags you can set different connection options:
Tabella 1. Supported flags
Name | Description |
---|---|
MYSQLI_CLIENT_COMPRESS | Use compression protocol |
MYSQLI_CLIENT_FOUND_ROWS | return number of matched rows, not the number of affected rows |
MYSQLI_CLIENT_IGNORE_SPACE | Allow spaces after function names. Makes all function names reserved words. |
MYSQLI_CLIENT_INTERACTIVE | Allow interactive_timeout seconds (instead of wait_timeout seconds) of inactivity before closing the connection |
MYSQLI_CLIENT_SSL | Use SSL (encryption) |
Nota: For security reasons the MULTI_STATEMENT flag is not supported in PHP. If you want to execute multiple queries use the mysqli_multi_query() function.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Connection: Localhost via UNIX socket |
(PHP 5)
mysqli_real_escape_string(no version information, might be only in CVS)
mysqli->real_escape_string -- Escapes special characters in a string for use in a SQL statement, taking into account the current charset of the connectionProcedural style:
string mysqli_real_escape_string ( mysqli link, string escapestr )Object oriented style (method):
class mysqli {This function is used to create a legal SQL string that you can use in a SQL statement. The string escapestr is encoded to an escaped SQL string, taking into account the current character set of the connection.
Characters encoded are NUL (ASCII 0), \n, \r, \, ', ", and Control-Z.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Error: 42000 1 Row inserted. |
(PHP 5)
mysqli_real_query(no version information, might be only in CVS)
mysqli->real_query -- Execute an SQL queryProcedural style
bool mysqli_real_query ( mysqli link, string query )Object oriented style (method):
class mysqli {The mysqli_real_query() function is used to execute only a query against the database represented by the link whose result can then be retrieved or stored using the mysqli_store_result() or mysqli_use_result() functions.
Nota: In order to determine if a given query should return a result set or not, see mysqli_field_count().
mysqli_report() is a powerful function to improve your queries and code during development and testing phase. Depending on the flags it reports errors from mysqli function calls or queries which don't use an index (or use a bad index).
Esempio 1. Object oriented style
|
(PHP 5)
mysqli_rollback(no version information, might be only in CVS)
mysqli->rollback -- Rolls back current transactionRollbacks the current transaction for the database specified by the link parameter.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
0 rows in table myCity. 50 rows in table myCity (after rollback). |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 5)
mysqli_rpl_query_type(no version information, might be only in CVS)
mysqli->rpl_query_type -- Returns RPL query typeProcedural style:
int mysqli_rpl_query_type ( mysqli link, string query )Object oriented style (method)
class mysqli {Returns MYSQLI_RPL_MASTER, MYSQLI_RPL_SLAVE or MYSQLI_RPL_ADMIN depending on a query type. INSERT, UPDATE and similar are master queries, SELECT is slave, and FLUSH, REPAIR and similar are admin.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 5)
mysqli_select_db(no version information, might be only in CVS)
mysqli->select_db -- Selects the default database for database queriesThe mysqli_select_db() function selects the default database (specified by the dbname parameter) to be used when performing queries against the database connection represented by the link parameter.
Nota: This function should only be used to change the default database for the connection. You can select the default database with 4th parameter in mysqli_connect().
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Default database is test. Default database is world. |
This function is an alias of mysqli_stmt_send_long_data(). For a detailled descripton see description of mysqli_stmt_send_long_data().
Nota: mysqli_send_long_data() is deprecated and will be removed.
(PHP 5)
mysqli_send_query(no version information, might be only in CVS)
mysqli->send_query -- Send the query and returnProcedural style:
bool mysqli_send_query ( mysqli link, string query )Object oriented style (method)
class mysqli {Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 5 >= 5.1.0RC1)
mysqli_set_charset(no version information, might be only in CVS)
mysqli->set_charset -- Sets the default client character setThe mysqli_set_charset() function sets the default character set (specified by the charset parameter) to be used when sending data from and to the database server represented by the link parameter.
Nota: To use this function on a Windows platform you need MySQL client library version 4.1.11 or above (for MySQL 5.0 you need 5.0.6 or above)
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Current character set: utf8 |
(PHP 5)
mysqli_sqlstate(no version information, might be only in CVS)
mysqli->sqlstate -- Returns the SQLSTATE error from previous MySQL operationProcedural style:
string mysqli_sqlstate ( mysqli link )Object oriented style (property):
class mysqli {Returns a string containing the SQLSTATE error code for the last error. The error code consists of five characters. '00000' means no error. The values are specified by ANSI SQL and ODBC. For a list of possible values, see http://dev.mysql.com/doc/mysql/en/error-handling.html.
Nota: Note that not all MySQL errors are yet mapped to SQLSTATE's. The value HY000 (general error) is used for unmapped errors.
Returns a string containing the SQLSTATE error code for the last error. The error code consists of five characters. '00000' means no error.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Error - SQLSTATE 42S01. |
(PHP 5)
mysqli_ssl_set(no version information, might be only in CVS)
mysqli->ssl_set -- Used for establishing secure connections using SSLProcedural style:
bool mysqli_ssl_set ( mysqli link, string key, string cert, string ca, string capath, string cipher )Object oriented style (method):
class mysqli {The function mysqli_ssl_set() is used for establishing secure connections using SSL. It must be called before mysqli_real_connect(). This function does nothing unless OpenSSL support is enabled.
key is the pathname to the key file. cert is the pathname to the certificate file. ca is the pathname to the certificate authority file. capath is the pathname to a directory that contains trusted SSL CA certificates in pem format. cipher is a list of allowable ciphers to use for SSL encryption. Any unused SSL parameters may be given as NULL
This function always returns TRUE value. If SSL setup is incorrect mysqli_real_connect() will return an error when you attempt to connect.
(PHP 5)
mysqli_stat(no version information, might be only in CVS)
mysqli->stat -- Gets the current system statusProcedural style:
string mysqli_stat ( mysqli link )Object oriented style (method):
class mysqli {mysqli_stat() returns a string containing information similar to that provided by the 'mysqladmin status' command. This includes uptime in seconds and the number of running threads, questions, reloads, and open tables.
Il precedente esempio visualizzerà:
System status: Uptime: 272 Threads: 1 Questions: 5340 Slow queries: 0 Opens: 13 Flush tables: 1 Open tables: 0 Queries per second avg: 19.632 Memory in use: 8496K Max memory used: 8560K |
(PHP 5)
mysqli_stmt_affected_rows(no version information, might be only in CVS)
mysqli_stmt->affected_rows -- Returns the total number of rows changed, deleted, or inserted by the last executed statementProcedural style :
int mysqli_stmt_affected_rows ( mysqli_stmt stmt )Object oriented style (property):
class mysqli_stmt {mysqli_stmt_affected_rows() returns the number of rows affected by INSERT, UPDATE, or DELETE query. If the last query was invalid, this function will return -1.
The mysqli_stmt_affected_rows() function only works with queries which update a table. In order to return the number of rows from a SELECT query, use the mysqli_stmt_num_rows() function instead.
An integer greater than zero indicates the number of rows affected or retrieved. Zero indicates that no records where updated for an UPDATE/DELETE statement, no rows matched the WHERE clause in the query or that no query has yet been executed. -1 indicates that the query has returned an error.
Nota: If the number of affected rows is greater than maximal PHP int value, the number of affected rows will be returned as a string value.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
rows inserted: 17 |
(PHP 5)
mysqli_stmt_bind_param(no version information, might be only in CVS)
stmt->bind_param -- Binds variables to a prepared statement as parametersProcedural style:
bool mysqli_stmt_bind_param ( mysqli_stmt stmt, string types, mixed &var1 [, mixed &...] )Object oriented style (method):
class mysqli_stmt {mysqli_stmt_bind_param() is used to bind variables for the parameter markers in the SQL statement that was passed to mysqli_prepare(). The string types contains one or more characters which specify the types for the corresponding bind variables
Tabella 1. Type specification chars
Character | Description |
---|---|
i | corresponding variable has type integer |
d | corresponding variable has type double |
s | corresponding variable has type string |
b | corresponding variable is a blob and will be send in packages |
Nota: If data size of a variable exceeds max. allowed package size (max_allowed_package), you have to specify b in types and use mysqli_stmt_send_long_data() to send the data in packages.
The number of variables and length of string types must match the parameters in the statement.
mysqli_stmt_bind_result(), mysqli_stmt_execute(), mysqli_stmt_fetch(), mysqli_prepare(), mysqli_stmt_send_long_data(), mysqli_stmt_errno() e mysqli_stmt_error().
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
1 Row inserted. 1 Row deleted. |
(PHP 5)
mysqli_stmt_bind_result(no version information, might be only in CVS)
stmt->bind_result -- Binds variables to a prepared statement for result storageProcedural style:
bool mysqli_stmt_bind_result ( mysqli_stmt stmt, mixed &var1 [, mixed &...] )Object oriented style (method):
class mysqli_stmt {mysqli_stmt_bind_result() is used to associate (bind) columns in the result set to variables. When mysqli_stmt_fetch() is called to fetch data, the MySQL client/server protocol places the data for the bound columns into the specified variables var1, ....
Nota: Note that all columns must be bound prior to calling mysqli_stmt_fetch(). Depending on column types bound variables can silently change to the corresponding PHP type.
A column can be bound or rebound at any time, even after a result set has been partially retrieved. The new binding takes effect the next time mysqli_stmt_fetch() is called.
mysqli_stmt_bind_param(), mysqli_stmt_execute(), mysqli_stmt_fetch(), mysqli_prepare(), mysqli_stmt_prepare(), mysqli_stmt_init(), mysqli_stmt_errno() e mysqli_stmt_error().
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
AFG Afghanistan ALB Albania DZA Algeria ASM American Samoa AND Andorra |
(PHP 5)
mysqli_stmt_close(no version information, might be only in CVS)
mysqli_stmt->close -- Closes a prepared statementProcedural style:
bool mysqli_stmt_close ( mysqli_stmt stmt )Object oriented style (method):
class mysqli_stmt {Closes a prepared statement. mysqli_stmt_close() also deallocates the statement handle pointed to by stmt. If the current statement has pending or unread results, this function cancels them so that the next query can be executed.
(PHP 5)
mysqli_stmt_data_seek(no version information, might be only in CVS)
stmt->data_seek -- Seeks to an arbitray row in statement result setProcedural style:
void mysqli_stmt_data_seek ( mysqli_stmt statement, int offset )Object oriented style (method):
class mysqli_stmt {The mysqli_stmt_data_seek() function seeks to an arbitrary result pointer specified by the offset in the statement result set represented by statement. The offset parameter must be between zero and the total number of rows minus one (0..mysqli_stmt_num_rows() - 1).
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
City: Benin City Countrycode: NGA |
(PHP 5)
mysqli_stmt_errno(no version information, might be only in CVS)
mysqli_stmt->errno -- Returns the error code for the most recent statement callProcedural style :
int mysqli_stmt_errno ( mysqli_stmt stmt )Object oriented style (property):
class mysqli_stmt {For the statement specified by stmt, mysqli_stmt_errno() returns the error code for the most recently invoked statement function that can succeed or fail.
Nota: Client error message numbers are listed in the MySQL errmsg.h header file, server error message numbers are listed in mysqld_error.h. In the MySQL source distribution you can find a complete list of error messages and error numbers in the file Docs/mysqld_error.txt.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Error: 1146. |
(PHP 5)
mysqli_stmt_error(no version information, might be only in CVS)
mysqli_stmt->error -- Returns a string description for last statement errorProcedural style:
string mysqli_stmt_error ( mysqli_stmt stmt )Object oriented style (property):
class mysqli_stmt {For the statement specified by stmt, mysqli_stmt_error() returns a containing the error message for the most recently invoked statement function that can succeed or fail.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Error: Table 'world.myCountry' doesn't exist. |
(PHP 5)
mysqli_stmt_execute(no version information, might be only in CVS)
stmt->execute -- Executes a prepared QueryProcedural style:
bool mysqli_stmt_execute ( mysqli_stmt stmt )Object oriented style (method):
class mysqli_stmt {The mysqli_stmt_execute() function executes a query that has been previously prepared using the mysqli_prepare() function represented by the stmt object. When executed any parameter markers which exist will automatically be replaced with the appropiate data.
If the statement is UPDATE, DELETE, or INSERT, the total number of affected rows can be determined by using the mysqli_stmt_affected_rows() function. Likewise, if the query yields a result set the mysqli_stmt_fetch() function is used.
Nota: When using mysqli_stmt_execute(), the mysqli_stmt_fetch() function must be used to fetch the data prior to performing any additional queries.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Stuttgart (DEU,Baden-Wuerttemberg) Bordeaux (FRA,Aquitaine) |
(PHP 5)
mysqli_stmt_fetch(no version information, might be only in CVS)
stmt->fetch -- Fetch results from a prepared statement into the bound variablesProcedural style:
bool mysqli_stmt_fetch ( mysqli_stmt stmt )Object oriented style (method):
class mysqli_stmt {mysqli_stmt_fetch() fetch the result from a prepared statement into the variables bound by mysqli_stmt_bind_result().
Nota: Note that all columns must be bound by the application before calling mysqli_stmt_fetch().
mysqli_prepare(), mysqli_stmt_errno(), mysqli_stmt_error() e mysqli_stmt_bind_result().
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Rockford (USA) Tallahassee (USA) Salinas (USA) Santa Clarita (USA) Springfield (USA) |
(PHP 5)
mysqli_stmt_free_result(no version information, might be only in CVS)
stmt->free_result -- Frees stored result memory for the given statement handleProcedural style:
void mysqli_stmt_free_result ( mysqli_stmt stmt )Object oriented style (method):
class mysqli_stmt {The mysqli_stmt_free_result() function frees the result memory associated with the statement represented by the stmt parameter, which was allocated by mysqli_stmt_store_result().
(PHP 5)
mysqli_stmt_init(no version information, might be only in CVS)
mysqli->stmt_init -- Initializes a statement and returns an object for use with mysqli_stmt_prepareProcedural style :
mysqli_stmt mysqli_stmt_init ( mysqli link )Object oriented style (property):
class mysqli {Allocates and initializes a statement object suitable for mysqli_stmt_prepare().
Nota: Any subsequent calls to any mysqli_stmt function will fail until mysqli_stmt_prepare() was called.
(PHP 5)
mysqli_stmt_num_rows(no version information, might be only in CVS)
stmt->num_rows -- Return the number of rows in statements result setProcedural style :
int mysqli_stmt_num_rows ( mysqli_stmt stmt )Object oriented style (property):
class mysqli_stmt {Returns the number of rows in the result set. The use of mysqli_stmt_num_rows() depends on whether or not you used mysqli_stmt_store_result() to buffer the entire result set in the statement handle.
If you use mysqli_stmt_store_result(), mysqli_stmt_num_rows() may be called immediately.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Number of rows: 20. |
(PHP 5)
mysqli_stmt_param_count(no version information, might be only in CVS)
stmt->param_count -- Returns the number of parameter for the given statementProcedural style:
int mysqli_stmt_param_count ( mysqli_stmt stmt )Object oriented style (property):
class mysqli_stmt {mysqli_stmt_param_count() returns the number of parameter markers present in the prepared statement.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Statement has 2 markers. |
(PHP 5)
mysqli_stmt_prepare(no version information, might be only in CVS)
stmt->prepare -- Prepare a SQL statement for executionProcedure style:
bool mysqli_stmt_prepare ( mysqli_stmt stmt, string query )Object oriented style (method)
class mysqli_stmt {mysqli_stmt_prepare() prepares the SQL query pointed to by the null-terminated string query. The statement object has to be allocated by mysqli_stmt_init(). The query must consist of a single SQL statement.
Nota: You should not add a terminating semicolon or \g to the statement.
The parameter query can include one or more parameter markers in the SQL statement by embedding question mark (?) characters at the appropriate positions.
Nota: The markers are legal only in certain places in SQL statements. For example, they are allowed in the VALUES() list of an INSERT statement (to specify column values for a row), or in a comparison with a column in a WHERE clause to specify a comparison value.
However, they are not allowed for identifiers (such as table or column names), in the select list that names the columns to be returned by a SELECT statement), or to specify both operands of a binary operator such as the = equal sign. The latter restriction is necessary because it would be impossible to determine the parameter type. In general, parameters are legal only in Data Manipulation Languange (DML) statements, and not in Data Defination Language (DDL) statements.
The parameter markers must be bound to application variables using mysqli_stmt_bind_param() and/or mysqli_stmt_bind_result() before executing the statement or fetching rows.
mysqli_stmt_init(), mysqli_stmt_execute(), mysqli_stmt_fetch(), mysqli_stmt_bind_param(), mysqli_stmt_bind_result() e mysqli_stmt_close().
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Amersfoort is in district Utrecht |
(PHP 5)
mysqli_stmt_reset(no version information, might be only in CVS)
stmt->reset -- Resets a prepared statementProcedural style:
bool mysqli_stmt_reset ( mysqli_stmt stmt )Object oriented style (method):
class mysqli_stmt {The mysqli_stmt_reset() resets a prepared statement on client and server to state after prepare. For now this is mainly used to reset data sent with mysqli_stmt_send_long_data().
Nota: To prepare a statement with another query use function mysqli_stmt_prepare().
Procedural style:
mysqli_result mysqli_stmt_result_metadata ( mysqli_stmt stmt )Object oriented style (method):
class mysqli_stmt {If a statement passed to mysqli_prepare() is one that produces a result set, mysqli_stmt_result_metadata() returns the result object that can be used to process the meta information such as total number of fields and individual field information.
Nota: This result set pointer can be passed as an argument to any of the field-based functions that process result set metadata, such as:
The result set structure should be freed when you are done with it, which you can do by passing it to mysqli_free_result()
Nota: The result set returned by mysqli_stmt_result_metadata() contains only metadata. It does not contain any row results. The rows are obtained by using the statement handle with mysqli_stmt_fetch().
mysqli_stmt_result_metadata() returns a result object or FALSE if an error occured.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
(PHP 5)
mysqli_stmt_send_long_data(no version information, might be only in CVS)
stmt->send_long_data -- Send data in blocksProcedural style:
bool mysqli_stmt_send_long_data ( mysqli_stmt stmt, int param_nr, string data )Object oriented style (method)
class mysqli_stmt {Allows to send parameter data to the server in pieces (or chunks), e.g. if the size of a blob exceeds the size of max_allowed_packet. This function can be called multiple times to send the parts of a character or binary data value for a column, which must be one of the TEXT or BLOB datatypes.
param_nr indicates which parameter to associate the data with. Parameters are numbered beginning with 0. data is a string containing data to be sent.
Returns a string containing the SQLSTATE error code for the most recently invoked prepared statement function that can succeed or fail. The error code consists of five characters. '00000' means no error. The values are specified by ANSI SQL and ODBC. For a list of possible values, see http://dev.mysql.com/doc/mysql/en/error-handling.html.
Nota: Note that not all MySQL errors are yet mapped to SQLSTATE's. The value HY000 (general error) is used for unmapped errors.
Returns a string containing the SQLSTATE error code for the last error. The error code consists of five characters. '00000' means no error.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Error: 42S02. |
(PHP 5)
mysqli_stmt_store_result(no version information, might be only in CVS)
mysqli_stmt->store_result -- Transfers a result set from a prepared statementProcedural style:
bool mysqli_stmt_store_result ( mysqli_stmt stmt )Object oriented style (method):
class mysqli_stmt {You must call mysqli_stmt_store_result() for every query that successfully produces a result set (SELECT, SHOW, DESCRIBE, EXPLAIN), and only if you want to buffer the complete result set by the client, so that the subsequent mysqli_stmt_fetch() call returns buffered data.
Nota: It is unnecessary to call mysqli_stmt_store_result() for other queries, but if you do, it will not harm or cause any notable performance in all cases. You can detect whether the query produced a result set by checking if mysqli_stmt_result_metadata() returns NULL.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Number of rows: 20. |
(PHP 5)
mysqli_store_result(no version information, might be only in CVS)
mysqli->store_result -- Transfers a result set from the last queryProcedural style:
mysqli_result mysqli_store_result ( mysqli link )Object oriented style (method):
class mysqli {Transfers the result set from the last query on the database connection represented by the link parameter to be used with the mysqli_data_seek() function.
Nota: Although it is always good practice to free the memory used by the result of a query using the mysqli_free_result() function, when transfering large result sets using the mysqli_store_result() this becomes particularly important.
Nota: mysqli_store_result() returns FALSE in case the query didn't return a result set (if the query was, for example an INSERT statement). This function also returns FALSE if the reading of the result set failed. You can check if you have got an error by checking if mysqli_error() doesn't return an empty string, if mysqli_errno() returns a non zero value, or if mysqli_field_count() returns a non zero value. Also possible reason for this function returning FALSE after successfull call to mysqli_query() can be too large result set (memory for it cannot be allocated). If mysqli_field_count() returns a non-zero value, the statement should have produced a non-empty result set.
(PHP 5)
mysqli_thread_id(no version information, might be only in CVS)
mysqli->thread_id -- Returns the thread ID for the current connectionProcedural style:
int mysqli_thread_id ( mysqli link )Object oriented style (property):
class mysqli {The mysqli_thread_id() function returns the thread ID for the current connection which can then be killed using the mysqli_kill() function. If the connection is lost and you reconnect with mysqli_ping(), the thread ID will be other. Therefore you should get the thread ID only when you need it.
Nota: The thread ID is assigned on a connection-by-connection basis. Hence, if the connection is broken and then re-established a new thread ID will be assigned.
To kill a running query you can use the SQL command KILL QUERY processid.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Error: MySQL server has gone away |
Procedural style:
bool mysqli_thread_safe ( void )mysqli_thread_safe() indicates whether the client library is compiled as thread-safe.
(PHP 5)
mysqli_use_result(no version information, might be only in CVS)
mysqli->use_result -- Initiate a result set retrievalProcedural style:
mysqli_result mysqli_use_result ( mysqli link )Object oriented style (method):
class mysqli {mysqli_use_result() is used to initiate the retrieval of a result set from the last query executed using the mysqli_real_query() function on the database connection specified by the link parameter. Either this or the mysqli_store_result() function must be called before the results of a query can be retrieved, and one or the other must be called to prevent the next query on that database connection from failing.
Nota: The mysqli_use_result() function does not transfer the entire result set from the database and hence cannot be used functions such as mysqli_data_seek() to move to a particular row within the set. To use this functionality, the result set must be stored using mysqli_store_result(). One should not use mysqli_use_result() if a lot of processing on the client side is performed, since this will tie up the server and prevent other threads from updating any tables from which the data is being fetched.
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
my_user@localhost ----------------- Amersfoort Maastricht Dordrecht Leiden Haarlemmermeer |
(PHP 5)
mysqli_warning_count(no version information, might be only in CVS)
mysqli->warning_count -- Returns the number of warnings from the last query for the given linkProcedural style:
int mysqli_warning_count ( mysqli link )Object oriented style (property):
class mysqli {mysqli_warning_count() returns the number of warnings from the last query in the connection represented by the link parameter.
Nota: For retrieving warning messages you can use the SQL command SHOW WARNINGS [limit row_count].
Esempio 1. Object oriented style
|
Esempio 2. Procedural style
|
Il precedente esempio visualizzerà:
Warning (1264): Data truncated for column 'Name' at row 1 |
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.
Avvertimento |
Questo modulo è SPERIMENTALE. Ovvero, il comportamento di queste funzioni, i nomi di queste funzioni, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questo modulo è a vostro rischio. |
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].
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. Ncurses configuration options
Name | Default | Changeable | Changelog |
---|---|---|---|
ncurses.value | "42" | PHP_INI_ALL | |
ncurses.string | "foobar" | PHP_INI_ALL |
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Tabella 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 mode |
NCURSES_COLOR_YELLOW | yellow - supported when terminal is in color mode |
NCURSES_COLOR_BLUE | blue - supported when terminal is in color mode |
NCURSES_COLOR_CYAN | cyan - supported when terminal is in color mode |
NCURSES_COLOR_MAGENTA | magenta - supported when terminal is in color mode |
Tabella 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 occurred |
NCURSES_KEY_MAX | maximum key value |
Tabella 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 |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.2.0, PHP 5)
ncurses_addchnstr -- Add attributed string with specified length at current positionAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_beep() sends an audible alert (bell) and if its not possible flashes the screen. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also ncurses_flash()
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.2.0, PHP 5)
ncurses_border -- Draw a border around the screen using attributed charactersAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_border() draws the specified lines and corners around the main window. Each parameter expects 0 to draw a line and 1 to skip it. The corners are top left, top right, bottom left and bottom right.
Use ncurses_wborder() for borders around subwindows!
See also ncurses_wborder().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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 occurred.
See also: ncurses_nocbreak()
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_clear() clears the screen completely without setting blanks. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
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().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_clrtobot() erases all lines from cursor to end of screen and creates blanks. Blanks created by ncurses_clrtobot() have the current background rendition. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also ncurses_clear(), and ncurses_clrtoeol()
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_clrtoeol() erases the current line from cursor position to the end. Blanks created by ncurses_clrtoeol() have the current background rendition. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also ncurses_clear(), and ncurses_clrtobot()
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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()
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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()
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.3.0, PHP 5)
ncurses_del_panel -- Remove panel from the stack and delete it (but not the associated window)
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.1.0, PHP 5)
ncurses_delch -- Delete character at current position, move rest of line leftAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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()
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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()
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_echo() enables echo mode. All characters typed by user are echoed by ncurses_getch(). Returns FALSE on success, TRUE if any error occurred.
To disable echo mode use ncurses_noecho().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_erase() fills the terminal screen with blanks. Created blanks have the current background rendition, set by ncurses_bkgd(). Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also ncurses_bkgd(), and ncurses_clear()
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_erasechar() returns the current erase char character.
See also: ncurses_killchar()
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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()
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_getmaxyx() puts the horizontal and vertical size of the window window into the given variables y and x. Variables must be passed as reference, so they are updated when the user changes terminal size.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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()
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_has_colors() returns TRUE or FALSE depending on whether the terminal has color capacities.
See also: ncurses_can_change_color()
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_has_ic() checks terminals insert- and delete capabilities. It returns TRUE when terminal has insert/delete-capabilities, otherwise FALSE.
See also: ncurses_has_il()
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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()
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.2.0, PHP 5)
ncurses_hline -- Draw a horizontal line at current position using an attributed character and max. n characters longAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_inch() returns the character from the current position.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_init() initializes the ncurses interface and must be used before any other ncurses function.
(PHP 4 >= 4.1.0, PHP 5)
ncurses_insch -- Insert character moving rest of line including character at current positionAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.1.0, PHP 5)
ncurses_insdelln -- Insert lines before current line scrolling down (negative numbers delete and scroll up)Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_insertln() inserts a new line above the current line. The bottom line will be lost.
(PHP 4 >= 4.2.0, PHP 5)
ncurses_insstr -- Insert string at current position, moving rest of line rightAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_instr() returns the number of characters read from the current character position until end of line. buffer contains the characters. Attributes are stripped from the characters.
(PHP 4 >= 4.1.0, PHP 5)
ncurses_isendwin -- Ncurses is in endwin mode, normal screen output may be performedAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_isendwin() returns TRUE, if ncurses_endwin() has been called without any subsequent calls to ncurses_wrefresh(), otherwise FALSE.
See also ncurses_endwin() and ncurses_wrefresh().
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_killchar() returns the current line kill character.
See also: ncurses_erasechar()
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_longname() returns a verbose description of the terminal. The description is truncated to 128 characters. On Error ncurses_longname() returns NULL.
See also: ncurses_termname()
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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 by NCURSES_KEY_MOUSE in the ncurses_wgetch() input stream. To read the event data and pop the event 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() and ncurese_getch().
(PHP 4 >= 4.3.0, PHP 5)
ncurses_move_panel -- Moves a panel so that its upper-left corner is at [startx, starty]
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.2.0, PHP 5)
ncurses_mvaddchnstr -- Move position and add attributed string with specified lengthAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.2.0, PHP 5)
ncurses_mvdelch -- Move position and delete character, shift rest of line leftAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.2.0, PHP 5)
ncurses_mvhline -- Set new position and draw a horizontal line using an attributed character and max. n characters longAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(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 longAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_newwin() creates a new window to draw elements in. Windows can be positioned using x, y, rows and cols. When creating additional windows, remember to use ncurses_getmaxyx() to check for available space, as terminal size is individual and may vary. The return value is a resource ID used to differ between multiple windows.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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 occurred, otherwise FALSE.
See also: ncurses_cbreak()
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_noecho() prevents echoing of user typed characters. Returns TRUE if any error occurred, otherwise FALSE.
See also: ncurses_echo(), ncurses_getch()
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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 occurred, otherwise FALSE.
See also: ncurses_raw(), ncurses_cbreak(), ncurses_nocbreak()
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
If panel is null, returns the bottom panel in the stack.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
If panel is null, returns the top panel in the stack.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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 occurred, otherwise FALSE.
See also: ncurses_noraw(), ncurses_cbreak(), ncurses_nocbreak()
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Function ncurses_resetty() restores the terminal state, which was previously saved by calling ncurses_savetty(). This function always returns FALSE.
See also: ncurses_savetty()
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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()
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.1.0, PHP 5)
ncurses_scrl -- Scroll window content up or down without changing current positionAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.3.0, PHP 5)
ncurses_show_panel -- Places an invisible panel on top of the stack, making it visible
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_slk_attr() returns the current soft label key attribute. On error returns TRUE, otherwise FALSE.
(PHP 4 >= 4.1.0, PHP 5)
ncurses_slk_attroff -- Turn off the given attributes for soft function-key labelsAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.1.0, PHP 5)
ncurses_slk_attron -- Turn on the given attributes for soft function-key labelsAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
The function ncurses_slk_clear() clears soft label keys from screen. Returns TRUE on error, otherwise FALSE.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Function 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.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_slk_refresh() copies soft label keys from virtual screen to physical screen. Returns TRUE on error, otherwise FALSE.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
The function ncurses_slk_restore() restores the soft label keys after ncurses_slk_clear() has been performed.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
The ncurses_slk_touch() function forces all the soft labels to be output the next time a ncurses_slk_noutrefresh() is performed.
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.1.0, PHP 5)
ncurses_termattrs -- Returns a logical OR of all attribute flags supported by terminalAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_termname() returns terminals shortname. The shortname is truncated to 14 characters. On error ncurses_termname() returns NULL.
See also: ncurses_longname()
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
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()
(PHP 4 >= 4.3.0, PHP 5)
ncurses_update_panels -- Refreshes the virtual screen to reflect the relations between panels in the stack
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.1.0, PHP 5)
ncurses_use_env -- Control use of environment information about terminal sizeAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.1.0, PHP 5)
ncurses_use_extended_names -- Control use of extended names in terminfo descriptionsAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.1.0, PHP 5)
ncurses_vidattr -- Display the string on the terminal in the video attribute modeAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.2.0, PHP 5)
ncurses_vline -- Draw a vertical line at current position using an attributed character and max. n characters longAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.3.0, PHP 5)
ncurses_waddch -- Adds character at current position in a window and advance cursor
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.3.0, PHP 5)
ncurses_wborder -- Draws a border around the window using attributed charactersAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
ncurses_wborder() draws the specified lines and corners around the passed window window. Each parameter expects 0 to draw a line and 1 to skip it. The corners are top left, top right, bottom left and bottom right.
Use ncurses_border() for borders around the main window.
See also ncurses_border().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.3.0, PHP 5)
ncurses_whline -- Draws a horizontal line in a window at current position using an attributed character and max. n characters long
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Non è necessaria nessuna installazione per usare queste funzioni, esse fanno parte del core di PHP.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Per maggiori dettagli e definizioni delle costanti PHP_INI_* vedere ini_set().
Breve descrizione dei parametri di configurazione.
Inposta se definire o meno le varie varaibili di syslog (quali $LOG_PID, $LOG_CRON, etc.). Disattivarle ha effetti positivi sulle performance. A runtime, queste variabili possono essere definit richiamando define_syslog_variables().
Le costanti qui elencate sono sempre disponibili in quanto parte del core di PHP.
Tabella 2. Opzioni openlog()
Costante | Descrizione |
---|---|
LOG_CONS | Se si verifica un errore nella scrittura nel log di sistema scrive direttamente sulla console. |
LOG_NDELAY | Apre immediatamente la connessione con il log |
LOG_ODELAY | (default) attende ad aprire la connessione fino a quando non vi è un messaggio da registrare. |
LOG_NOWAIT | |
LOG_PERROR | Scrive il messaggio di log anche nello standard error |
LOG_PID | Include anche il PID in ciascun messaggio |
Tabella 3. Tools openlog()
Costante | Descrizione |
---|---|
LOG_AUTH | Messaggio di sicurezza/autorizzazione (utilizzare LOG_AUTHPRIV nei sistemi in cui questa costante è definita) |
LOG_AUTHPRIV | Messaggi di sicurezza/autorizzazione (privati) |
LOG_CRON | Demone dell'ora (cron ed at) |
LOG_DAEMON | Altri demoni di sistema |
LOG_KERN | Messaggi del kernel |
LOG_LOCAL0 ... LOG_LOCAL7 | Riservato per utilizzi locali, questi non sono dipsonibili in Windows |
LOG_LPR | Sottosistema della stampante |
LOG_MAIL | Sottosistema di posta |
LOG_NEWS | Sottosistema USENET news |
LOG_SYSLOG | Messaggi generati internamente da syslogd |
LOG_USER | Messaggi utente generici |
LOG_UUCP | Sottosistema UUCP |
Tabella 4. Priorità (in ordine decrescente) di syslog()
Costante | Descrizione |
---|---|
LOG_EMERG | Sistema inutilizzabile |
LOG_ALERT | Azioni devono essere intraprese immediatamente |
LOG_CRIT | Condizioni critiche |
LOG_ERR | Condizioni di errore |
LOG_WARNING | Condizioni di attenzione |
LOG_NOTICE | Situazione normale, ma significativa |
LOG_INFO | Messaggio informativo |
LOG_DEBUG | Messaggio di debug |
Tabella 5. Parametri dns_get_record()
Costante | Descrizione |
---|---|
DNS_A | Risorsa con indirizzo IPv4 |
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 (Vedere la pagina IANA Operating System Names per il significato di questi valori) |
DNS_SOA | Start of Authority Resource |
DNS_TXT | Text Resource |
DNS_ANY | Any Resource Record. In molti sistemi questo restituisce tutti i record, tuttavia non si dovrebbe farne affidamento per utilzzi critici. Piuttosto utilizzare DNS_ALL. |
DNS_AAAA | IPv6 Address Resource |
DNS_ALL | Interroga in modo iterativo il DNS alla ricerca di ogni tipo di record disponibile. |
(PHP 3, PHP 4, PHP 5)
checkdnsrr -- Controlla i record DNS relativi ad un host Internet o indirizzo IPCerca i record DNS del tipo type corrispondenti a host. Restituisce vero se dei records sono trovati; falso se nessun record viene trovato o in caso di errore.
type può essere uno dei seguenti: A, MX, NS, SOA, PTR, CNAME, oppure ANY. Il default è MX.
Host può essere sia l'indirizzo IP in notazione decimale o il nome dell'host.
Nota: Questa funzione non è implementata su piattaforme Windows
Vedere anche getmxrr(), gethostbyaddr(), gethostbyname(), gethostbynamel() e la man page named(8).
closelog() chiude il descrittore usato per scrivere al logger di sistema. L'uso di closelog() è facoltativo.
Vedere anche define_syslog_variables(), syslog() e openlog().
Disattiva il debugger interno PHP. Il debugger è ancora in fase di sviluppo.
Attiva il debugger interno PHP, connettendolo ad indirizzo. Il debugger è in fase di sviluppo.
Inizializza tutte le costanti usate nelle funzioni del syslog.
Vedere anche openlog(), syslog() e closelog().
Check DNS records corresponding to a given Internet host name or IP address
Get MX records corresponding to a given Internet host name.
Nota: This function is not implemented on Windows platforms, nor does it (currently) work on *BSD systems. Try the PEAR class Net_DNS.
This function returns an array of associative arrays. Each associative array contains at minimum the following keys:
Tabella 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_SRV, DNS_NAPTR, DNS_A6, DNS_ALL or DNS_ANY. The default is DNS_ANY.
Nota: Because of eccentricities 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.
Tabella 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 IANA's Operating System Names for the meaning of these values. |
SOA | mname: FQDN of the machine from which the resource records originated. 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 |
A6(PHP >= 5.1.0) | masklen: Length (in bits) to inherit from the target specified by chain. ipv6: Address for this specific record to merge with chain. chain: Parent record to merge with ipv6 data. |
SRV | pri: (Priority) lowest priorities should be used first. weight: Ranking to weight which of commonly prioritized targets should be chosen at random. target and port: hostname and port where the requested service can be found. For additional information see: RFC 2782 |
NAPTR | order and pref: Equivalent to pri and weight above. flags, services, regex, and replacement: Parameters as defined by RFC 2915. |
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().
Esempio 1. Using dns_get_record()
Produces output similar to the following:
|
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 containing a list of authoritative name servers.
Esempio 2. Using dns_get_record() and DNS_ANY
Produces output similar to the following:
|
See also dns_get_mx(), and dns_check_record()
(PHP 3, PHP 4, PHP 5)
fsockopen -- Apre una connessione a un socket appartenente a un dominio Internet o UnixInizializza una connessione nel dominio Internet (AF_INET, usando TCP o UDP) o Unix (AF_UNIX). Per il dominio Internet, apre una connessione a un socket TCP verso l' hostname sulla porta port. hostname può essere in questo caso, sia un fully qualified domain name o un indirizzo IP. Per le connessioni UDP, è necessario specificare esplicitamente il protocollo, usando: 'udp://' come prefisso di hostname. Per il dominio Unix, hostname viene utilizzato come percorso verso il socket, in questo caso, porta deve essere impostato a 0. Il parametro opzionale timeout può essere usato per impostare un timeout in secondi per la chiamata di sistema connect.
A partire da PHP 4.3.0, se si è compilato con il supporto OpenSSL, si può prefissare hostname con 'ssl://' oppure 'tls://' per utilizzare una connessione client SSL o TLS su una connessione TCP/IP per connettersi all'host remoto.
fsockopen() restituisce un puntatore a file che può essere usato nelle altre funzioni orientate ai file (come fgets(), fgetss(), fputs(), fclose() e feof()).
Se la chiamata non ha successo, viene restituito FALSE e se gli argomenti opzionali errno e errstr sono presenti, vengono impostati a indicare l'errore a livello di sistema che è avvenuto nella chiamata alla funzione connect() del sistema operativo. Se il valore di errno restituito è 0 e la funzione restituisce FALSE, è un'indicazione che l'errore è avvenuto prima della chiamata di connect(). Questo è molto probabilmente legato ad un problema di inizializzazione del socket. Si noti che gli argomenti errno e errstr verranno sempre passati by reference.
A seconda dell'ambiente operativo, il dominio Unix o l'opzionale timeout della connect potrebbero non essere disponibili.
Il socket viene aperto di default in modo blocking. Si può passare al modo non-blocking usando socket_set_blocking().
Nota: Il parametro timeout è stato introdotto nel PHP 3.0.9 e il supporto UDP è stato aggiunto nel PHP 4.
Restituisce l'hostname dell'host Internet specificato da indirizzo_ip. Se occorre un errore, restituisce indirizzo_ip.
Vedere anche gethostbyname().
(PHP 3, PHP 4, PHP 5)
gethostbyname -- Ottiene l'indirizzo IP corrispondente a un dato hostname InternetRestituisce l'indirizzo IP dell'host Internet specificato da hostname.
Vedere anche gethostbyaddr().
(PHP 3, PHP 4, PHP 5)
gethostbynamel -- Ottiene la lista degli indirizzi IP corrispondenti a un dato hostname InternetRestituisce una lista di indirizzi IP che risolvono nei confronti dell'host Internet specificato da hostname.
Vedere anche gethostbyname(), gethostbyaddr(), checkdnsrr(), getmxrr() e la pagina man named(8).
Cerca nel DNS i record MX corrispondenti a hostname. Restituisce TRUE se ne vengono trovati. Restituisce FALSE se non ne vengono trovati o se avviene un errore.
La lista di record MX trovati viene messa nell'array mxhosts. Se viene indicato l'array weight, esso viene riempito con le informazioni ottenute sui vari pesi.
Vedere anche checkdnsrr(), gethostbyname(), gethostbynamel(), gethostbyaddr()e la pagina man named(8).
getprotobyname() restituisce il numero del protocollo associato al protocollo nome come in /etc/protocols.
Vedere anche: getprotobynumber().
getprotobynumber() restituisce il nome del protocollo associato al protocollo numero come in /etc/protocols.
Vedere anche: getprotobyname().
(PHP 4, PHP 5)
getservbyname -- Ottiene il numero di porta associato ad un servizio Internet e ad un protocollogetservbyname() restituisce la porta Internet corrispondente a servizio per il protocollo specificato come in /etc/services. protocollo può essere sia "tcp" che "udp" (scritti in minuscolo). Restituisce FALSE se service o protocol non sono trovati.
Per avere la lista completa dei numeri di porta vedere: http://www.iana.org/assignments/port-numbers.
Vedere anche: getservbyport().
(PHP 4, PHP 5)
getservbyport -- Ottiene il servizio Internet corrispondente ad una porta e ad un protocollogetservbyport() restituisce il servizio Internet associato a porta relativamente al protocollo specificato come in /etc/services. protocollo può essere sia "tcp" che "udp" (scritti in minuscolo).
Vedere anche: getservbyname().
(PHP 5 >= 5.1.0RC1)
inet_ntop -- Converts a packed internet address to a human readable representationThis function converts a 32bit IPv4, or 128bit IPv6 address (if PHP was built with IPv6 support enabled) into an address family appropriate string representation. Returns FALSE on failure.
Nota: Questa funzione non è implementata su piattaforme Windows
See also long2ip(), inet_pton(), and ip2long().
(PHP 5 >= 5.1.0RC1)
inet_pton -- Converts a human readable IP address to its packed in_addr representationThis function converts a human readable IPv4 or IPv6 address (if PHP was built with IPv6 support enabled) into an address family appropriate 32bit or 128bit binary structure.
Nota: Questa funzione non è implementata su piattaforme Windows
See also ip2long(), inet_ntop(), and long2ip().
(PHP 4, PHP 5)
ip2long -- Converts a string containing an (IPv4) Internet Protocol dotted address into a proper address. Converte una stringa contenente un indirizzo di rete del Protocollo Internet (IPv4) in un indirizzo espresso come tipo di dato int.La funzione ip2long() genera un indirizzo di rete Internet IPv4 a partire dalla rappresentazione in formato standard (stringa separata da punti).
Nota: Poiché il tipo di dato integer in PHP è signed e molti indirizzi IP risulterebbero essere interi negativi, è necessario usare il formattatore "%u" della funzione sprintf() e printf() per ottenere la rappresentazione in stringa dell'indirizzo IP in modo nsigned.
Vedere anche: long2ip()
(PHP 4, PHP 5)
long2ip -- Converte un indirizzo di rete del Protocollo Internet (IPv4) in una stringa contenente un indirizzo espresso secondo la notazione standard di Internet.La funzione long2ip() genera un indirizzo Internet in formato separato da punti (es.: aaa.bbb.ccc.ddd) a partire dalla rappresentazione propria.
Vedere anche: ip2long()
openlog() apre una connessione al logger di sistema per un programma. La stringa ident viene aggiunta a ogni messaggio. Valori per option e facility sono dati di seguito. L'argomento option viene usato per indicare quali opzioni di loggin verranno usate durante la generazione di un messaggio di log. L'argomento facility viene usato per specificare quale tipo di programma sta loggando il messaggio. Questo permette di specificare (nella comfigurazione del syslog della macchina) come trattare i messaggi provenienti dalle diverse facility. L'uso di openlog() è opzionale. Viene chiamato automaticamente da syslog() se necessario, in tal caso ident sarà di default FALSE.
Tabella 1. Opzioni di openlog()
Costante | Descrizione |
---|---|
LOG_CONS | se si verifica un errore durante l'invio dei dati al logger di sistema, scrive direttamente sulla console di sistema |
LOG_NDELAY | apre immediatamente una connessione al logger |
LOG_ODELAY | (default) ritarda l'apertura della connessione fino a quando non viene loggato il primo messaggio |
LOG_PERROR | stampa un messaggio di log anche su standard error |
LOG_PID | include il PID in ciascun messaggio |
Tabella 2. Facility di openlog()
Costante | Descrizione |
---|---|
LOG_AUTH | messaggi di sicurezza/autorizzazione (usa LOG_AUTHPRIV nei sistemi dove è definita quella costante) |
LOG_AUTHPRIV | messaggi di sicurezza/autorizzazione (private) |
LOG_CRON | clock daemon (cron e at) |
LOG_DAEMON | altri demoni di sistema |
LOG_KERN | messaggi del kernel |
LOG_LOCAL0 ... LOG_LOCAL7 | riservato per il locale |
LOG_LPR | sottosistema line printer |
LOG_MAIL | sottosistema mail |
LOG_NEWS | sottosistema news di USENET |
LOG_SYSLOG | messaggi generati internamente da syslogd |
LOG_USER | messaggi generici user-level |
LOG_UUCP | sottosistema UUCP |
Vedere anche define_syslog_variables(), syslog() e closelog().
(PHP 3 >= 3.0.7, PHP 4, PHP 5)
pfsockopen -- Apre una connessione persistente Internet o di tipo domain socket UnixQuesta funzione si comporta esattamente come fsockopen() con la differenza che la connessione non viene chiusa dopo che lo script ha finito la sua esecuzione. È la versione persistente di fsockopen().
syslog() genera un messaggio di log che viene distribuito dal logger di sistema. priorità è la combinazione della facility e del livello, valori utilizzabili sono riportati nella prossima sezione. L'argomento rimanente è il messaggio da inviare, eccetto i due caratteri %m che vengono sostituiti dalla stringa del messaggio di errore (strerror) corrispondente all'attuale valore di errno.
Tabella 1. Priorità syslog() (in ordine discendente)
Costante | Descrizione |
---|---|
LOG_EMERG | sistema non utilizzabile |
LOG_ALERT | azione da intraprendere immediatamente |
LOG_CRIT | condizioni critiche |
LOG_ERR | condizioni di errore |
LOG_WARNING | condizioni di attenzione |
LOG_NOTICE | condizione normale, ma significativa |
LOG_INFO | messaggio di informazione |
LOG_DEBUG | messaggio a livello di debug |
Esempio 1. Uso di syslog()
|
Su Windows NT, il servizio syslog è emulato usando Event Log.
Vedere anche define_syslog_variables(), openlog() e closelog().
This is a PHP language extension for RedHat Newt library, a terminal-based window and widget library for writing applications with user friendly interface. Once this extension is enabled in PHP it will provide the use of Newt widgets, such as windows, buttons, checkboxes, radiobuttons, labels, editboxes, scrolls, textareas, scales, etc. Use of this extension if very similar to the original Newt API of C programming language.
This module uses the functions of the RedHat Newt library. You need libnewt version >= 0.51.0.
This PECL extension is not bundled with PHP. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: http://pecl.php.net/package/newt.
In PHP 4 this PECL extensions source can be found in the ext/ directory within the PHP source or at the PECL link above. In order to use these functions you must compile CGI or CLI PHP with newt support by using the --with-newt[=DIR] configure option.
Nota: This extension is not available for Windows platform.
You may need also curses and slang libraries, in order to compile this extension. To specify locations of these libraries, use the followin configuration options: --with-curses-dir=/path/to/libcurses --with-slang-dir=/path/to/libslang
This extension uses two resource types: "newt component" and "newt grid". Resource type "newt component" is returned by functions, which create common newt widgets (for example: newt_button()) Resource type "newt grid" is a special link identifier for components, returned by newt grid factory functions (for example: newt_create_grid())
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
This function sends a beep to the terminal.
Nota: Depending on the terminal's settings, this been may or may not be audible.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Open a centered window of the specified size.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Its description
Its description
Its description
Its description
Its description
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Its description
Its description
Its description
Its description
Its description
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Its description
Its description
Its description
Its description
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Its description
Its description
Its description
Its description
Its description
What the function returns, first on success, then on failure. See also the &return.success; entity
(PECL)
newt_clear_key_buffer -- Discards the contents of the terminal's input buffer without waiting for additional inputDiscards the contents of the terminal's input buffer without waiting for additional input.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Displays the string text at the position indicated.
Column number
Nota: If left is negative, the position is measured from the opposite side of the screen.
Line number
Nota: If top is negative, the position is measured from the opposite side of the screen.
Text to display.
Esempio 1. A newt_draw_root_text() example This code demonstrates drawing of titles in the both corners of the screen.
|
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Its description
Its description
Its description
Its description
Its description
What the function returns, first on success, then on failure. See also the &return.success; entity
Uninitializes newt interface. This function be called, when program is ready to exit.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Fills in the passed references with the current size of the terminal.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Its description
Its description
Its description
Its description
Its description
Its description
Its description
Its description
Its description
Its description
Its description
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Its description
Its description
Its description
Its description
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Initializes the newt interface. This function must be called before any other newt function.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Its description
Its description
Its description
Its description
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Its description
Its description
Its description
Its description
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Its description
Its description
Its description
Its description
Its description
Its description
Its description
What the function returns, first on success, then on failure. See also the &return.success; entity
Open a window of the specified size and position.
Location of the upper left-hand corner of the window (column number)
Location of the upper left-hand corner of the window (row number)
Window width
Window height
Window title
Replaces the current help line with the one from the stack.
Nota: It's important not to call to newt_pop_help_line() more then newt_push_help_line().
Removes the top window from the display, and redraws the display areas which the window overwrote.
Saves the current help line on a stack, and displays the new line.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Its description
Its description
Its description
Its description
Its description
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Its description
Its description
Its description
Its description
Its description
Its description
What the function returns, first on success, then on failure. See also the &return.success; entity
To increase performance, newt only updates the display when it needs to, not when the program tells it to write to the terminal. Applications can force newt to immediately update modified portions of the screen by calling this function.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Its description
Its description
Its description
Its description
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
(PECL)
newt_set_suspend_callback -- Set a callback function which gets invoked when user presses the suspend keySet a callback function which gets invoked when user presses the suspend key (normally ^Z). If no suspend callback is registered, the suspend keystroke is ignored.
A callback function, which accepts one argument: data
This data is been passed to the callback function
Tells newt to return the terminal to its initial state. Once this is done, the application can suspend itself (by sending itself a SIGTSTP, fork a child program, or do whatever else it likes.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Its description
Its description
Its description
Its description
Its description
Its description
Its description
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Its description
Its description
Its description
Its description
Its description
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Its description
Its description
Its description
Its description
Its description
What the function returns, first on success, then on failure. See also the &return.success; entity
This function doesn't return until a key has been pressed. The keystroke is then ignored. If a key is already in the terminal's buffer, this function discards a keystroke and returns immediately.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Its description
Its description
Its description
Its description
Its description
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Its description
Its description
Its description
Its description
Its description
Its description
Its description
Its description
Its description
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Its description
Its description
Its description
Its description
Its description
Its description
Its description
Its description
Its description
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Its description
Its description
Its description
Its description
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Its description
Its description
Its description
Its description
What the function returns, first on success, then on failure. See also the &return.success; entity
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
These functions are only available when running PHP as a NSAPI module in Netscape/iPlanet/SunONE webservers.
For PHP installation on Netscape/iPlanet/SunONE webservers see the NSAPI section (UNIX, Windows) in the installation chapter.
The behaviour of the NSAPI PHP module is affected by settings in php.ini. Configuration settings from php.ini may be overridden by additional parameters to the php4_execute call in obj.conf
Tabella 1. NSAPI configuration options
Name | Default | Changeable | Changelog |
---|---|---|---|
nsapi.read_timeout | "60" | PHP_INI_ALL | Available since PHP 4.3.3. |
Breve descrizione dei parametri di configurazione.
Sets the time in seconds the plugin is waiting for POST data from the client.
NSAPI implements a subset of the functions from the Apache module for maximum compatibility.
Tabella 2. Apache functions implemented by NSAPI
Apache function (only as alias) | NSAPI function | Description |
---|---|---|
apache_request_headers() | nsapi_request_headers() | Fetch all HTTP request headers |
apache_response_headers() | nsapi_response_headers() | Fetch all HTTP response headers |
getallheaders() | nsapi_request_headers() | Fetch all HTTP request headers |
virtual() | nsapi_virtual() | Make NSAPI sub-request |
nsapi_request_headers() gets all the HTTP headers in the current request. This is only supported when PHP runs as a NSAPI module.
Nota: Prior to PHP 4.3.3, getallheaders() was only available for the Apache servers. After PHP 4.3.3, getallheaders() is an alias for nsapi_request_headers() if you use the NSAPI module.
Nota: You can also get at the value of the common CGI variables by reading them from the $_SERVER superglobal, which works whether or not you are using PHP as a NSAPI module.
nsapi_virtual() is an NSAPI-specific function which is equivalent to <!--#include virtual...--> in SSI (.shtml files). It does an NSAPI sub-request. It is useful for including CGI scripts or .shtml files, or anything else that you'd parse through webserver.
To run the sub-request, all buffers are terminated and flushed to the browser, pending headers are sent too.
You cannot make recursive requests with this function to other PHP scripts. If you want to include PHP scripts, use include() or require().
Nota: This function depends on a undocumented feature of the Netscape/iPlanet/SunONE webservers. Use phpinfo() to determine if it is available. In the Unix environment it should always work, in windows it depends on the name of a ns-httpdXX.dll file.
Read the note about subrequests in the NSAPI section (UNIX, Windows) if you experience this problem.
Avvertimento |
Questo modulo è SPERIMENTALE. Ovvero, il comportamento di queste funzioni, i nomi di queste funzioni, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questo modulo è a vostro rischio. |
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 hierarchies 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:
Esempio 1. Class association
|
Esempio 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:
Esempio 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:
Esempio 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 process of aggregation is cumulative, 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.
(no version information, might be only in CVS)
aggregate_info -- Returns an associative array of the methods and properties from each class that has been aggregated to the objectWill return the aggregation 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
Esempio 1. Using aggregate_info()
Will produce the output
|
_secret_super_dicing
See also aggregate(), aggregate_methods(), aggregate_methods_by_list(), aggregate_methods_by_regexp(), aggregate_properties(), aggregate_properties_by_list(), aggregate_properties_by_regexp(), deaggregate()
(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 parameter 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 expression to match method names. The optional parameter 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 parameter 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 expression to match their names. The optional parameter 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()
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()
Lo scopo di questa estensione è di permettere l'overloading delle proprietà di accesso agli oggetti e dei metodi di chiamata. Solo una funzione è definita in questa estensione, overload() che prende il nome dalla classe che ha questa funzionalità abilitata. La classe nominata ha da definire metodi appropriati se vuole avere questa funzionalità: __get(), __set() and __call() rispettivamente per ricevere/impostare una proprietà, o chiamare un metodo. Questa strada del sovraccarico può essere selettiva. Dentro queste funzioni handler l'overloading è disabilitato così si può accedere alle proprietà dell'oggetto normalmente.
Avvertimento |
Questo modulo è SPERIMENTALE. Ovvero, il comportamento di queste funzioni, i nomi di queste funzioni, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questo modulo è a vostro rischio. |
Avvertimento |
Questo modulo non è parte di PHP 5. Php 5 gestisce le chiamate __get(), __set() and __call() in modo nativo. Vedere la pagina l'overload in PHP 5 per maggiori dettagli. |
Per potere utilizzare queste funzioni occorre compilare il PHP con --enable-overload. A partire dal PHP 4.3.0 questo modulo è abilitato per default. Si può disabilitare il supporto overload tramite --disable--overload.
La versione per Windows di PHP ha già compilato il supporto per questo modulo. Non occorre caricare alcun modulo addizionale per potere utilizzare queste funzioni.
Nota: Il supporto per questo modulo è compilato per default a partire dal PHP 4.3.0.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Alcuni semplici esempi sull'uso della funzione overload()
Esempio 1. Overloading di una classe PHP
|
La funzione overload() abiliterà la proprietà e il method call overloading per una classe identificata dal parametro class_name. Guarda un esempio nella sezione di introduzione di questa parte..
Queste funzioni permettono di accedere ai database Oracle9, Oracle8 e Oracle7. Usano la Oracle Call Interface (OCI).
Questa estensione è più flessibile della estensione precedente di Oracle. Supporta il binding di variabili PHP locali e globali ai segnaposto Oracle, ha pieno supporto di LOB, FILE e ROWID e permette di utilizzare variabili di definizione personalizzabili. Si raccomanda di utilizzare questa estensione al posto della vecchia estensione quando possibile;
Occorre avere installate le librerie client di Oracle per utilizzare questa estensione. Gli utenti Windows necessitano almeno della versione 8.1 di Oracle per utilizzare la dll php_oci8.dll.
Prima di usare questa estensione, occorre sincerarsi di aver impostato le variabili d'ambiente per l'utente Oracle, come pure per l'utente del server web. Le variabili che potrebbero necessitare l'impostazione sono le seguenti:
ORACLE_HOME
ORACLE_SID
LD_PRELOAD
LD_LIBRARY_PATH
NLS_LANG
ORA_NLS33
Dopo aver impostato le variabili d'ambiente per l'utente del server web, occorre sicerarsi di aver aggiunto anche l'utente stesso (nobody, www) al gruppo oracle.
Se il server web non parte o va in blocco: Controllare che apache sia linkato con la libreria pthread:
# 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)Se la libpthread non compare nell'elenco, occorre reinstallare Apache:
Si noti che su alcuni sistemi, come ad esempio UnixWare, la libreria si chiama libthread invece di libpthread. PHP e Apache devono essere configurati con EXTRA_LIBS=-lthread.
Si deve compilare PHP con l'opzione --with-oci8[=DIR], dove DIR è di default il contenuto della variabile di ambiente ORACLE_HOME.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Modalità di esecuzione dello statement. Non viene eseguito il commit automatico utilizzando questa modalità.
Modalità di esecuzione dello statement. Utilizzare questa modalità se non si vuole eseguire la query, ma solamente ricevere la descrizione della select list.
Modalità di esecuzione dello statement. Vene eseguito automaticamente il commit dello statement dopo la chiamata della oci_execute().
Modalità di recupero dati dello statement. Utilizzato quando l'applicazione conosce in anticipo quante righe verranno recuperate. Questa modalità disattiva il prefetching negli Oracle release 8 o successivi. Il cursore viene eliminato dopo che le sono state caricate e ciò può determinare un utilizzo ridotto delle risorse del server.
Utilizzato con oci_bind_by_name() quando si collegano i BFILE.
Utilizzato con oci_bind_by_name() quando si collegano i CFILE.
Utilizzato con oci_bind_by_name() quando si collegano i CLOB.
Utilizzato con oci_bind_by_name() quando si collegano i BLOB.
Utilizzato con oci_bind_by_name() quando si collegano i ROWID.
Utilizzato con oci_bind_by_name() quando si collegano i cursori, precedentemente allocati con oci_new_descriptor().
Utilizzato con oci_bind_by_name() quando si collegano i named data type.
Alias di OCI_B_BFILE.
Alias di OCI_B_CFILEE.
Alias di OCI_B_CLOB.
Alias di OCI_B_BLOB.
Alias di OCI_B_ROWID.
Alias di OCI_B_NTY.
Modalità di default di oci_fetch_all().
Modalità alternativa di oci_fetch_all().
Utilizzato con oci_fetch_all() e oci_fetch_array() per ottenere un array associative come risultato.
Utilizzato con oci_fetch_all() e oci_fetch_array() per ottenere un array enumerativo come risultato.
Utilizzato con oci_fetch_all() e oci_fetch_array() per ottenere un array con indici sia associativi che numerici.
Utilizzato con oci_fetch_array() per ottenere elementi dell'array vuoti se il valore del campo è NULL.
Utilizzato con oci_fetch_array() per ottenere il valore del LOB invece del suo descrittore.
Questo flag ordina a oci_new_descriptor() di inizializzare un nuovo descrittore di FILE.
Questo flag ordina a oci_new_descriptor() di inizializzare un nuovo descrittore di LOB.
Questo flag ordina a oci_new_descriptor() di inizializzare un nuovo descrittore di ROWID.
Alias di OCI_DTYPE_FILE.
Alias di OCI_DTYPE_LOB.
Alias di OCI_DTYPE_ROWID.
Esempio 1. Trucchi OCI
|
You can easily access stored procedures in the same way as you would from the commands line.
Esempio 2. Using Stored Procedures
|
(no version information, might be only in CVS)
OCI-Collection->append -- Appends element to the collectionAppends element to the end of the collection. Parameter value can be a string or a number.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
(no version information, might be only in CVS)
OCI-Collection->assign -- Assigns a value to the collection from another existing collectionAssigns a value to the collection from another, previously created collection. Both collections must be created with oci_new_collection() prior to using them.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
(no version information, might be only in CVS)
OCI-Collection->assignElem -- Assigns a value to the element of the collectionAssigns a value to the element with index index. Parameter value can be a string or a number.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
(no version information, might be only in CVS)
OCI-Collection->free -- Frees the resources associated with the collection objectFrees the resources associated with the collection object.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
(no version information, might be only in CVS)
OCI-Collection->getElem -- Returns value of the elementReturns element's value with the index index (1-based).
OCI-Collection->getElem() returns FALSE if such element doesn't exist; NULL if element is NULL; string if element is column of a string datatype or number if element is numeric field.
(no version information, might be only in CVS)
OCI-Collection->max -- Returns the maximum number of elements in the collectionReturns the maximum number of elements in the collection. If the returned value is 0, then the number of elements is not limited. OCI-Collection->max() returns FALSE in case of error.
(no version information, might be only in CVS)
OCI-Collection->size -- Returns size of the collectionReturns the number of elements in the collection or FALSE on error.
(no version information, might be only in CVS)
OCI-Collection->trim -- Trims elements from the end of the collectionTrims num of elements from the end of the collection.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
(no version information, might be only in CVS)
OCI-Lob->append -- Appends data from the large object to another large objectAppends data from the large object to the end of another large object.
Writing to the large object with OCI-Lob->append() will fail if buffering was previously enabled. You must disable buffering before appending. You may need to flush buffers with OCI-Lob->flush before disabling buffering.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
OCI-Lob->close() closes descriptor of LOB or FILE. This function should be used only with OCI-Lob->writeTemporary.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
(no version information, might be only in CVS)
OCI-Lob->eof -- Tests for end-of-file on a large object's descriptorReturns TRUE if internal pointer of large object is at the end of LOB. Otherwise returns FALSE.
(no version information, might be only in CVS)
OCI-Lob->erase -- Erases a specified portion of the internal LOB dataErases a specified portion of the internal LOB data starting at a specified offset. Parameters length and offset are optional. OCI-Lob->erase() erases all LOB data by default.
For BLOBs, erasing means that the existing LOB value is overwritten with zero-bytes. For CLOBs, the existing LOB value is overwritten with spaces.
OCI-Lob->erase() returns the actual number of characters/bytes erased or FALSE in case of error.
Exports LOB contents to a file. The file name is given in the parameter filename. The optional parameter start indicates from where to start exporting and the parameter length - indicates the length of data to be exported.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
(no version information, might be only in CVS)
OCI-Lob->flush -- Flushes/writes buffer of the LOB to the serverOCI-Lob->flush() actually writes data to the server. By default, resources are not freed, but using flag OCI_LOB_BUFFER_FREE you can do it explicitly. Be sure you know what you're doing - next read/write operation to the same part of LOB will involve a round-trip to the server and initialize new buffer resources. It is recommended to use OCI_LOB_BUFFER_FREE flag only when you are not going to work with the LOB anymore.
OCI-Lob->flush() returns FALSE if buffering was not enabled or an error occurred.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
(no version information, might be only in CVS)
OCI-Lob->free -- Frees resources associated with the LOB descriptorFrees resources associated with the descriptor, previously allocated with oci_new_descriptor().
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
(no version information, might be only in CVS)
OCI-Lob->getBuffering -- Returns current state of buffering for the large objectReturns FALSE if buffering for the large object is off and TRUE if buffering is used.
Writes data from the filename in to the current position of large object.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Returns large object's contents. As script execution is terminated when the memory_limit is reached, ensure that the LOB does not exceed this limit. In most cases it's recommended to use OCI-Lob->read instead. In case of error OCI-Lob->load() returns FALSE.
Reads length bytes from the current position of LOB's internal pointer. Reading stops when length bytes have been read or end of the large object is reached. Internal pointer of the large object will be shifted on the amount of bytes read.
Returns FALSE in case of error.
(no version information, might be only in CVS)
OCI-Lob->rewind -- Moves the internal pointer to the beginning of the large objectSets the internal pointer to the beginning of the large object.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Saves data to the large object. Parameter offset can be used to indicate offset from the beginning of the large object.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
(no version information, might be only in CVS)
OCI-Lob->seek -- Sets the internal pointer of the large objectSets the internal pointer of the large object. Parameter offset indicates the amount of bytes, on which internal pointer should be moved from the position, pointed by whence:
OCI_SEEK_SET - sets the position equal to offset |
OCI_SEEK_CUR - adds offset bytes to the current position |
OCI_SEEK_END - adds offset bytes to the end of large object (use negative value to move to a position before the end of large object) |
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
(no version information, might be only in CVS)
OCI-Lob->setBuffering -- Changes current state of buffering for the large objectlob->setBuffering() sets the buffering for the large object, depending on the value of the on_off parameter. Repeated calls to lob->setBuffering() with the same flag will return TRUE. The values for on_off are: TRUE for on and FALSE for off.
Use of this function may provide performance improvements by buffering small reads and writes of LOBs by reducing the number of network round-trips and LOB versions. oci_lob_flush() should be used to flush buffers, when you have finished working with the large object.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Returns length of large object value or FALSE in case of error. Empty objects have zero length.
(no version information, might be only in CVS)
OCI-Lob->tell -- Returns current position of internal pointer of large objectReturns current position of a LOB's internal pointer or FALSE if an error occurred.
If parameter length is given, OCI-Lob->truncate() truncates large object to length bytes. Otherwise, OCI-Lob->truncate() will purge the LOB completely.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Writes data from the parameter data into the current position of LOB's internal pointer. If the parameter length is given, writing will stop after length bytes have been written or the end of data is reached, whichever comes first.
OCI-Lob->write() returns the number of bytes written or FALSE in case of error.
(no version information, might be only in CVS)
OCI-Lob->writeTemporary -- Writes temporary large objectCreates a temporary large object and writes data to it.
Parameter lob_type can be one of the following:
OCI_TEMP_BLOB is used to create temporary BLOBs |
OCI_TEMP_CLOB is used to create temporary CLOBs |
OCI-Lob->writeTemporary() creates a CLOB by default.
You should use OCI-Lob->close when the work with the object is over.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
oci_bind_by_name() collega la variabile PHP variable al segnaposto Oracle ph_name. L'utilizzo in modalità input o output sarà determinato a run-time, e lo spazio di memoria necessario sarà allocato. Il parametro lungmax imposta la lunghezza massima del collegamento. Se si imposta lungmax a -1 oci_bind_by_name() userà l'attuale lunghezza di variabile per impostare la lunghezza massima.
Se si deve collegare un tipo dato astratto (LOB/ROWID/BFILE) occorre innanzitutto allocarlo usando la funzione oci_new_descriptor(). Il parametro lungmax non è usato con i tipi dati astratti e dovrebbe essere impostato a -1. La variabile tipo informa oracle sul tipo di descrittore che si vuole usare. I valori possibili sono:
OCI_B_FILE - per i BFILE;
OCI_B_CFILE - per i CFILE;
OCI_B_CLOB - per i CLOB;
OCI_B_BLOB - per i BLOB;
OCI_B_ROWID - per i ROWID;
OCI_B_NTY - per i named datatype;
OCI_B_CURSOR - per i cursori precedentemente creati con oci_new_cursor().
Esempio 1. esempio di ocibindbyname()
|
Ricordarsi che questa funzione elimina gli spazi alla fine della riga. Vedere il seguente esempio:
Esempio 2. esempio di oci_bind_by_name()
|
Esempio 3. esempio di oci_bind_by_name()
|
Avvertimento |
Non utilizzare le magic_quotes_gpc o addslashes() e oci_bind_by_name() simultaneamente in quanto le virgolette non sono necessarie nelle variabili e qualsiasi virgoletta aggiunta automaticamente verrà scritta nel database dal momento che ocibindbyname() non è in grado di distinguere le virgolette aggiunte automaticamente da quelle intenzionali. |
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: Nelle versioni di PHP antecedenti la 5.0.0 si deve usare ocibindbyname(). Questo nome può ancora essere utilizzato, è rimasto come alias di oci_bind_by_name() per mantenere la compatibilità. Ciò è comunque deprecato e non raccomandato.
oci_cancel() invalida un cursore, rilasciando tutte le risorse associate e cancella la possibilità di leggere da esso.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nelle versioni di PHP antecedenti la 5.0.0 si deve usare ocicancel(). Questo nome può ancora essere utilizzato, è rimasto come alias di oci_cancel() per mantenere la compatibilità. Ciò è comunque deprecato e non raccomandato.
oci_close() closes the Oracle connection connection.
Nota: Starting from the version 1.1 oci_close() correctly closes the Oracle connection. Use oci8.old_oci_close_semantics option to restore old behaviour of this function.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: In PHP versions before 5.0.0 you must use ocilogoff() instead. This name still can be used, it was left as alias of oci_close() for downwards compatability. This, however, is deprecated and not recommended.
oci_commit() commits all outstanding statements for the active transaction on the Oracle connection connection.
Esempio 1. oci_commit() example
|
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: Transactions are automatically rolled back when you close the connection, or when the script ends, whichever is soonest. You need to explicitly call oci_commit() to commit the transaction, or oci_rollback() to abort it.
Nota: In PHP versions before 5.0.0 you must use ocicommit() instead. This name still can be used, it was left as alias of oci_commit() for downwards compatability. This, however, is deprecated and not recommended.
See also oci_rollback() and oci_execute().
oci_connect() returns a 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.
Parameter session_mode is available since version 1.1 and accepts the following values: OCI_DEFAULT, OCI_SYSOPER and OCI_SYSDBA. If either OCI_SYSOPER or OCI_SYSDBA were specified, oci_connect() will try to establish privileged connection using external credentials. Privileged connections are disabled by default. To enable them you need to set oci8.privileged_connect to On.
Nota: If you're using PHP with Oracle Instant Client, you can use easy connect naming method described here: http://download-west.oracle.com/docs/cd/B12037_01/network.101/b10775/naming.htm#i498306. Basically this means you can specify "//db_host[:port]/database_name" as database name. But if you want to use the old way of naming you must set either ORACLE_HOME or TNS_ADMIN.
Nota: The second and subsequent calls to oci_connect() with the same parameters will return the connection handle returned from the first call. This means that queries issued against one handle are also applied to the other handles, because they are the same handle. This behaviour is demonstrated in Example 1 below. If you require two handles to be transactionally isolated from each other, you should use oci_new_connect() instead.
Using Oracle server version 9.2 and greater, you can indicate charset parameter, which will be used in the new connection. If you're using Oracle server < 9.2, this parameter will be ignored and NLS_LANG environment variable will be used instead.
Esempio 1. oci_connect() example
|
oci_connect() returns FALSE if an error occured.
Nota: In PHP versions before 5.0.0 you must use ocilogon() instead. This name still can be used, it was left as the alias of oci_connect() for downwards compatability. This, however, is deprecated and not recommended.
See also oci_pconnect(), oci_new_connect() and oci_close().
oci_define_by_name() defines PHP variables for fetches of SQL-Columns. Take into consideration that Oracle uses ALL-UPPERCASE column names, whereby in your select you can also use lowercase. oci_define_by_name() expects the column_name to be in uppercase. If you define a variable that doesn't exists in your select statement, no error will be issued.
If you need to define an abstract datatype (LOB/ROWID/BFILE) you must allocate it first using oci_new_descriptor(). See also the oci_bind_by_name() function.
Esempio 1. oci_define_by_name() example
|
Nota: In PHP versions before 5.0.0 you must use ocidefinebyname() instead. This name still can be used, it was left as alias of oci_define_by_name() for downwards compatability. This, however, is deprecated and not recommended.
For most errors, the parameter is the most appropriate resource handle. For connection errors with oci_connect(), oci_new_connect() or oci_pconnect(), do not pass a parameter. If no error is found, oci_error() returns FALSE. oci_error() returns the error as an associative array. In this array, code consists the oracle error code and message the oracle error string.
As of PHP 4.3: offset and sqltext will also be included in the return array to indicate the location of the error and the original SQL text which caused it.
Esempio 3. Displaying the Oracle error message and problematic statement after an execution error
|
Nota: In PHP versions before 5.0.0 you must use ocierror() instead. This name still can be used, it was left as alias of oci_error() for downwards compatability. This, however, is deprecated and not recommended.
oci_execute() executes a previously parsed statement (see oci_parse()). 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, you should specify OCI_DEFAULT as your mode.
When using OCI_DEFAULT mode, you're creating a transaction. Transactions are automatically rolled back when you close the connection, or when the script ends, whichever is soonest. You need to explicitly call oci_commit() to commit the transaction, or oci_rollback() to abort it.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: In PHP versions before 5.0.0 you must use ociexecute() instead. This name still can be used, it was left as alias of oci_execute() for downwards compatability. This, however, is deprecated and not recommended.
oci_fetch_all() fetches all the rows from a result into a user-defined array. oci_fetch_all() returns the number of rows fetched or FALSE in case of an error. skip is the number of initial rows to ignore when fetching the result (default value of 0, to start at the first line). maxrows is the number of rows to read, starting at the skipth row (default to -1, meaning all the rows).
Nota: This function sets NULL fields to PHP NULL value.
Parameter flags can be any combination of the following:
OCI_FETCHSTATEMENT_BY_ROW |
OCI_FETCHSTATEMENT_BY_COLUMN (default value) |
OCI_NUM |
OCI_ASSOC |
Esempio 1. oci_fetch_all() example
|
For details on the data type mapping performed by the oci8 driver, see the datatypes supported by the driver
oci_fetch_all() returns FALSE in case of error.
Nota: In PHP versions before 5.0.0 you must use ocifetchstatement() instead. This name still can be used, it was left as alias of oci_fetch_all() for downwards compatability. This, however, is deprecated and not recommended.
(PHP 5)
oci_fetch_array -- Returns the next row from the result data as an associative or numeric array, or bothReturns an array, which corresponds to the next result row or FALSE in case of error or there are no more rows in the result.
oci_fetch_array() returns an array with both associative and numeric indices.
Nota: This function sets NULL fields to PHP NULL value.
An optional second parameter can be any combination of the following constants:
OCI_BOTH - return an array with both associative and numeric indices (the same as OCI_ASSOC + OCI_NUM). This is the default behavior. |
OCI_ASSOC - return an associative array (as oci_fetch_assoc() works). |
OCI_NUM - return a numeric array, (as oci_fetch_row() works). |
OCI_RETURN_NULLS - create empty elements for the NULL fields. |
OCI_RETURN_LOBS - return the value of a LOB of the descriptor. |
It should be mentioned here, that oci_fetch_array() is insignificantly slower, than oci_fetch_row(), but much more handy.
Nota: Oracle returns all field names in uppercase and associative indices in the result array will be uppercased too.
Esempio 1. oci_fetch_array() with OCI_BOTH example
|
Esempio 2. oci_fetch_array() with OCI_NUM example
|
Esempio 3. oci_fetch_array() with OCI_ASSOC example
|
Esempio 4. oci_fetch_array() with OCI_RETURN_LOBS example
|
For details on the data type mapping performed by the oci8 driver, see the datatypes supported by the driver
See also oci_fetch_assoc(), oci_fetch_object(), oci_fetch_row() and oci_fetch_all().
oci_fetch_assoc() returns the next row from the result data as an associative array (identical to oci_fetch_array() call with OCI_ASSOC flag).
Nota: This function sets NULL fields to PHP NULL value.
A subsequent call to oci_fetch_assoc() will return the next row or FALSE if there are no more rows.
Nota: Oracle returns all field names in uppercase and associative indices in the result array will be uppercased too.
For details on the data type mapping performed by the oci8 driver, see the datatypes supported by the driver
See also oci_fetch_array(), oci_fetch_object(), oci_fetch_row() and oci_fetch_all().
oci_fetch_object() returns the next row from the result data as an object, which attributes correspond to fields in statement.
Nota: This function sets NULL fields to PHP NULL value.
Subsequent calls to oci_fetch_object() will return the next row from the result or FALSE if there are no more rows.
Nota: Oracle returns all field names in uppercase and attributes' names in the result object will be in uppercase as well.
For details on the data type mapping performed by the oci8 driver, see the datatypes supported by the driver
See also oci_fetch_array(), oci_fetch_assoc(), oci_fetch_row() and oci_fetch_all().
Calling oci_fetch_row() is identical to oci_fetch_array() with OCI_NUM flag and returns the next row from the result data as a numeric array.
Nota: This function sets NULL fields to PHP NULL value.
Subsequent calls to oci_fetch_row() will return the next row from the result data or FALSE if there are no more rows.
For details on the data type mapping performed by the oci8 driver, see the datatypes supported by the driver
See also oci_fetch_array(), oci_fetch_object(), oci_fetch_assoc() and oci_fetch_all().
oci_fetch() fetches the next row (for SELECT statements) into the internal result-buffer.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
For details on the data type mapping performed by the oci8 driver, see the datatypes supported by the driver
Nota: In PHP versions before 5.0.0 you must use ocifetch() instead. This name still can be used, it was left as alias of oci_fetch() for downwards compatability. This, however, is deprecated and not recommended.
oci_field_is_null() returns TRUE if field field from the statement is NULL. Parameter field could be a field's index or a field's name (uppercased).
Nota: In PHP versions before 5.0.0 you must use ocicolumnisnull() instead. This name still can be used, it was left as alias of oci_field_is_null() for downwards compatability. This, however, is deprecated and not recommended.
oci_field_name() returns the name of the field corresponding to the field number (1-based).
Esempio 1. oci_field_name() example
|
Nota: In PHP versions before 5.0.0 you must use ocicolumnname() instead. This name still can be used, it was left as alias of oci_field_name() for downwards compatability. This, however, is deprecated and not recommended.
See also oci_num_fields(), oci_field_type(), and oci_field_size().
Returns precision of the field with field index (1-based).
For FLOAT columns, precision is nonzero and scale is -127. If precision is 0, then column is NUMBER. Else it's NUMBER(precision, scale).
Nota: In PHP versions before 5.0.0 you must use ocicolumnprecision() instead. This name still can be used, it was left as alias of oci_field_precision() for downwards compatability. This, however, is deprecated and not recommended.
See also oci_field_scale() and oci_field_type().
Returns scale of the column with field index (1-based) or FALSE if there is no such field.
For FLOAT columns, precision is nonzero and scale is -127. If precision is 0, then column is NUMBER. Else it's NUMBER(precision, scale).
Nota: In PHP versions before 5.0.0 you must use ocicolumnscale() instead. This name still can be used, it was left as alias of oci_field_scale() for downwards compatability. This, however, is deprecated and not recommended.
See also oci_field_precision() and oci_field_type().
oci_field_size() returns the size of a field in bytes. Value of field parameter can be the field's index (1-based) or it's name.
Esempio 1. oci_field_size()example
|
Nota: In PHP versions before 5.0.0 you must use ocicolumnsize() instead. This name still can be used, it was left as alias of oci_field_size() for downwards compatability. This, however, is deprecated and not recommended.
See also oci_num_fields() and oci_field_name().
oci_field_type_raw() returns Oracle's raw data type of the field.
Nota: In PHP versions before 5.0.0 you must use ocicolumntyperaw() instead. This name still can be used, it was left as alias of oci_field_type_raw() for downwards compatability. This, however, is deprecated and not recommended.
However, if you want to get field's type, then oci_field_type() will suit you better. See oci_field_type() for additional information.
oci_field_type() returns a field's data type. Parameter field is an index of the field in the statement (1-based).
Esempio 1. oci_field_type() example
|
Nota: In PHP versions before 5.0.0 you must use ocicolumntype() instead. This name still can be used, it was left as alias of oci_field_type() for downwards compatability. This, however, is deprecated and not recommended.
See also oci_num_fields(), oci_field_name(), and oci_field_size().
oci_free_statement() frees resources associated with Oracle's cursor or statement, which was received from as a result of oci_parse() or obtained from Oracle.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
oci_internal_debug() enables or disables internal debug output. Set onoff to 0 to turn debug output off or 1 to turn it on.
Nota: In PHP versions before 5.0.0 you must use ociinternaldebug() instead. This name still can be used, it was left as alias of oci_internal_debug() for downwards compatability. This, however, is deprecated and not recommended.
Copies a large object or a part of a large object to another large object. Parameter length indicates the length of data to be copied. Old LOB-recipient data will be overwritten.
If you need to copy a particular part of a LOB to a particular position of a LOB, use oci_lob_seek() to move LOB internal pointers.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Compares two LOB/FILE locators. Returns TRUE if these objects are equal and FALSE otherwise.
Allocates a new collection object. Parameter tdo should be a valid named type (uppercase). The third, optional parameter schema should point to the scheme, where the named type was created. oci_new_collection() uses the name of the current user as the default value of schema.
oci_new_collection() returns FALSE on error.
Nota: In PHP versions before 5.0.0 you must use ocinewcollection() instead. This name still can be used, it was left as alias of oci_new_collection() for downwards compatability. This, however, is deprecated and not recommended.
oci_new_connect() establishes a new connection to an Oracle server and logs on. Unlike oci_connect() and oci_pconnect(), oci_new_connect() does not cache connections and will always return a brand-new freshly opened connection handle. This is useful if your application needs transactional isolation between two sets of queries.
The optional third parameter can either contain the name of the local Oracle instance or the name of the entry in tnsnames.ora. If the third parameter is not specified, PHP uses environment variables ORACLE_SID and TWO_TASK to determine the name of local Oracle instance and location of tnsnames.ora accordingly.
Parameter session_mode is available since version 1.1 and accepts the following values: OCI_DEFAULT, OCI_SYSOPER and OCI_SYSDBA. If either OCI_SYSOPER or OCI_SYSDBA were specified, oci_new_connect() will try to establish privileged connection using external credentials. Privileged connections are disabled by default. To enable them you need to set oci8.privileged_connect to On.
Nota: If you're using PHP with Oracle Instant Client, you can use easy connect naming method described here: http://download-west.oracle.com/docs/cd/B12037_01/network.101/b10775/naming.htm#i498306. Basically this means you can specify "//db_host[:port]/database_name" as database name. But if you want to use the old way of naming you must set either ORACLE_HOME or TNS_ADMIN.
Using Oracle server version 9.2 and greater, you can indicate charset parameter, which will be used in the new connection. If you're using Oracle server < 9.2, this parameter will be ignored and NLS_LANG environment variable will be used instead.
The following demonstrates how you can separate connections.
Esempio 1. oci_new_connect() example
|
oci_new_connect() returns FALSE on error.
Nota: In PHP versions before 5.0.0 you must use ocinlogon() instead. This name still can be used, it was left as alias of oci_new_connect() for downwards compatability. This, however, is deprecated and not recommended.
See also oci_connect() and oci_pconnect().
oci_new_cursor() allocates a new statement handle on the specified connection.
Esempio 1. Using REF CURSOR in an Oracle's stored procedure
|
Esempio 2. Using REF CURSOR in an Oracle's select statement
|
oci_new_cursor() returns FALSE on error.
Nota: In PHP versions before 5.0.0 you must use ocinewcursor() instead. This name still can be used, it was left as alias of oci_new_cursor() for downwards compatability. This, however, is deprecated and not recommended.
oci_new_descriptor() allocates resources to hold descriptor or LOB locator. Valid values for type are: OCI_D_FILE, OCI_D_LOB and OCI_D_ROWID.
Esempio 1. oci_new_descriptor() example
|
Esempio 2. oci_new_descriptor() example
|
oci_new_descriptor() returns FALSE on error.
Nota: In PHP versions before 5.0.0 you must use ocinewdescriptor() instead. This name still can be used, it was left as alias of oci_new_descriptor() for downwards compatability. This, however, is deprecated and not recommended.
oci_num_fields() returns the number of columns in the statement.
Esempio 1. oci_num_fields() example
|
oci_num_fields() returns FALSE on error.
Nota: In PHP versions before 5.0.0 you must use ocinumcols() instead. This name still can be used, it was left as alias of oci_num_fields() for downwards compatability. This, however, is deprecated and not recommended.
oci_num_rows() returns number of rows affected during statement execution.
Nota: This function does not return number of rows selected! For SELECT statements this function will return the number of rows, that were fetched to the buffer with oci_fetch*() functions.
Esempio 1. oci_num_rows() example
|
oci_num_rows() returns FALSE on error.
Nota: In PHP versions before 5.0.0 you must use ocirowcount() instead. This name still can be used, it was left as alias of oci_num_rows() for downwards compatability. This, however, is deprecated and not recommended.
oci_parse() prepares the query using connection and returns the statement identifier, which can be used with oci_bind_by_name(), oci_execute() and other functions.
Nota: This function does not validate query. The only way to find out if query is valid SQL or PL/SQL statement - is to execute it.
oci_parse() returns FALSE on error.
Nota: In PHP versions before 5.0.0 you must use ociparse() instead. This name still can be used, it was left as alias of oci_parse() for downwards compatability. This, however, is deprecated and not recommended.
Changes password for user with username. Parameters old_password and new_password should indicate old and new passwords respectively.
Nota: The second oci_password_change() syntax is available since version 1.1.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: In PHP versions before 5.0.0 you must use ocipasswordchange() instead. This name still can be used, it was left as alias of oci_password_change() for downwards compatability. This, however, is deprecated and not recommended.
oci_pconnect() creates a persistent connection to an Oracle server and logs on. Persistent connections are cached and re-used between requests, resulting in reduced overhead on each page load; a typical PHP application will have a single persistent connection open against an Oracle server per Apache child process (or PHP FastCGI/CGI process). See the Persistent Database Connections section for more information.
Nota: Starting with version 1.1 of the oci8 extension, the lifetime and maximum amount of persistent Oracle connections can be tuned by setting the following configuration values: oci8.persistent_timeout, oci8.ping_interval and oci8.max_persistent.
The optional third parameter can either contain the name of the local Oracle instance or the name of the entry in tnsnames.ora. If the third parameter is not specified, PHP uses environment variables ORACLE_SID and TWO_TASK to determine the name of local Oracle instance and location of tnsnames.ora accordingly.
Parameter session_mode is available since version 1.1 and accepts the following values: OCI_DEFAULT, OCI_SYSOPER and OCI_SYSDBA. If either OCI_SYSOPER or OCI_SYSDBA were specified, oci_connect() will try to establish privileged connection using external credentials. Privileged connections are disabled by default. To enable them you need to set oci8.privileged_connect to On.
Nota: If you're using PHP with Oracle Instant Client, you can use easy connect naming method described here: http://download-west.oracle.com/docs/cd/B12037_01/network.101/b10775/naming.htm#i498306. Basically this means you can specify "//db_host[:port]/database_name" as database name. But if you want to use the old way of naming you must set either ORACLE_HOME or TNS_ADMIN.
Using Oracle server version 9.2 and greater, you can indicate charset parameter, which will be used in the new connection. If you're using Oracle server < 9.2, this parameter will be ignored and NLS_LANG environment variable will be used instead.
oci_pconnect() returns connection identifier or FALSE on error.
Nota: In PHP versions before 5.0.0 you must use ociplogon() instead. This name still can be used, it was left as alias of oci_pconnect() for downwards compatability. This, however, is deprecated and not recommended.
See also oci_connect() and oci_new_connect().
oci_result() returns the data from the field field in the current row, fetched by oci_fetch(). oci_result() returns everything as strings except for abstract types (ROWIDs, LOBs and FILEs). oci_result() returns FALSE on error.
You can either use the column number (1-based) or the column name (in uppercase) for the field() parameter.
Nota: In PHP versions before 5.0.0 you must use ociresult() instead. This name still can be used, it was left as alias of oci_result() for downwards compatability. This, however, is deprecated and not recommended.
For details on the data type mapping performed by the oci8 driver, see the datatypes supported by the driver
See also oci_fetch_array(), oci_fetch_assoc(), oci_fetch_object(), oci_fetch_row() and oci_fetch_all().
oci_rollback() rolls back all outstanding statements for Oracle connection connection.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: Transactions are automatically rolled back when you close the connection, or when the script ends, whichever is soonest. You need to explicitly call oci_commit() to commit the transaction, or oci_rollback() to abort it.
Nota: In PHP versions before 5.0.0 you must use ocirollback() instead. This name still can be used, it was left as alias of oci_rollback() for downwards compatability. This, however, is deprecated and not recommended.
See also oci_commit().
Returns a string with version information of the Oracle server, which uses connection connection or returns FALSE on error.
Nota: In PHP versions before 5.0.0 you must use ociserverversion() instead. This name still can be used, it was left as alias of oci_server_version() for downwards compatability. This, however, is deprecated and not recommended.
Sets the number of rows to be prefetched after successful call to oci_execute(). The default value for rows is 1.
Nota: In PHP versions before 5.0.0 you must use ocisetprefetch() instead. This name still can be used, it was left as alias of oci_set_prefetch() for downwards compatability. This, however, is deprecated and not recommended.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also oci8_.default_prefetch ini option.
oci_statement_type() returns the query type of statement statement as one of the following values:
SELECT
UPDATE
DELETE
INSERT
CREATE
DROP
ALTER
BEGIN
DECLARE
UNKNOWN
Parameter statement is a valid OCI statement identifier, returned from oci_parse().
oci_statement_type() returns FALSE on error.
Nota: In PHP versions before 5.0.0 you must use ocistatementtype() instead. This name still can be used, it was left as alias of oci_statement_type() for downwards compatability. This, however, is deprecated and not recommended.
Se non si vogliono leggere altri dati da un cursore, chiamare ocicancel().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.0.6, PHP 5)
ocicollassignelem -- Assegna un elemento alla collezione in una specifica posizione
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
ocicolumnisnull() restituisce TRUE se il campo col nel risultato dell'istruzione stmt è NULL. Si può usare il numero del campo (primo campo=1) o il nome del campo per il parametro col.
ocicolumnname() restituisce il nome del campo corrispondente alla posizione (1 = primo campo) specificata.
Esempio 1. esempio di ocicolumnname()
|
Vedere anche ocinumcols(), ocicolumntype(), e ocicolumnsize().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
ocicolumnsize() restituisce la dimensione del campo come riportata da Oracle. Si può usare il numero del campo (primo campo=1) o il nome del campo per il parametro col.
Esempio 1. esempio di ocicolumnsize()
|
Vedere anche ocinumcols(), ocicolumnname() e ocicolumnsize().
ocicolumntype() restituisce il tipo del campo corrispondente alla posizione (1 = primo campo) specificata.
Esempio 1. OCIColumnType
|
Vedere anche ocinumcols(), ocicolumnname(), e ocicolumnsize().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
ocicommit() esegue tutte le transazioni in sospeso sulla connessione Oracle connection. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Questo esempio dimostra l'utilizzo di OCICommit.
Esempio 1. OCICommit
|
Vedere anche ocirollback().
(PHP 3 >= 3.0.7, PHP 4, PHP 5)
OCIDefineByName -- Utilizza una variabile PHP per la fase di definizione in un comando SELECTocidefinebyname() aggancia le variabili PHP ai campi SQL. Attenzione: Oracle usa nomi di colonna MAIUSCOLI, mentre nella SELECT si possono anche scrivere minuscoli. ocidefinebyname() vuole il parametro Column-Name in caratteri maiuscoli. Se si definisce una variabile che non esiste nel comando SELECT, non viene dato alcun errore!
Se occorre definire un tipo di dati astratto (LOB/ROWID/BFILE) lo si deve prima allocare usando la funzione OCINewDescriptor(). Vedere anche la funzione OCIBindByName().
Esempio 1. OCIDefineByName
|
ocierror() restituisce l'ultimo errore. Se il parametro opzionale stmt|conn|global non è specificato, viene restituito l'ultimo errore generato. Se non ci sono errori, ocierror() restituisce FALSE. ocierror() restituisce l'errore in un array associativo. In questo array, code dà il codice d'errora oracle e message dà la stringa d'errore.
ociexecute() esegue un comando precedentemente analizzato. (vedere ociparse()). Il parametro opzionale mode permette di specificare la modalità di esecuzione (il default è OCI_COMMIT_ON_SUCCESS). Se non si desidera che i comandi eseguano un commit automatico, usare OCI_DEFAULT nella variabile mode.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
(PHP 3 >= 3.0.4, PHP 4, PHP 5)
ocifetch -- Estrae la prossima tupla opnendola nel buffer di risultato.ocifetch() estrae la prossima tupla (nelle istruzioni SELECT) ponendola nel buffer interno di risultato.
ocifetchinto() estrae la prossima tupla (nelle istruzioni SELECT) ponendola nell'array result. ocifetchinto() sovrascriverà il precedente contenuto di result. Di default result conterrà un array (primo indice = 1) di tutti i campi che non sono NULL.
Il parametro mode permette di cambiare il comportamento predefinito. E' possibile specificare più di un'opzione sommandole (es. OCI_ASSOC+OCI_RETURN_NULLS). Le opzioni valide sono:
OCI_ASSOC Restituisce un array associativo. |
OCI_NUM Restituisce un array indicizzato (primo indice = 0). (DEFAULT) |
OCI_RETURN_NULLS Restituisce anche i campi NULL. |
OCI_RETURN_LOBS Restituisce il valore di un LOB invece del descrittore. |
Vedere anche ocifetch() e ociexecute().
ocifetchstatement() estrae tutte le tuple da un risultato ponendole in un array definito dall'utente. ocifetchstatement() restituisce il numero di tuple estratte.
Esempio 1. Esempio di ocifetchstatement()
|
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
ocifreecursor() libera tutte le risorse associate al cursore stmt. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
ocifreedesc() cancella il descrittore di oggetto binario lob. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
(PHP 3 >= 3.0.5, PHP 4, PHP 5)
ocifreestatement -- Libera tutte le risorse associate ad un'istruzioneocifreestatement() libera tutte le risorse associate all'istruzione stmt.Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
(PHP 3 >= 3.0.4, PHP 4, PHP 5)
ociinternaldebug -- Abilita o disabilita la visualizzazione del debug interno.ociinternaldebug() abilita la visualizzazione del debug interno. Impostare onoff a 0 per spegnere il debug, 1 per accenderlo.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
ocilogoff() chiude la connessione Oracle.
L'uso di ocilogoff() normalmente non è necessario, dal momento che i collegamenti non persistenti sono automaticamente chiusi alla fine dell'esecuzione dello script. Vedere anche liberare le risorse
ocilogon() restituisce un identificatore di connessione necessario per la maggior parte delle altre chiamate OCI. Il terzo parametro opzionale può contenere il nome della istanza Oracle locale o il nome della voce in tnsnames.ora a cui ci si vuole connettere. Se il terzo parametro opzionale non è specificato, PHP usa la variabile d'ambiente ORACLE_SID (istanza di Oracle) o TWO_TASK (in tnsnames.ora) per determinare a quale database collegarsi.
Le connessioni sono condivise a livello di pagina quando si usa OCILogon(). Questo significa che i commit e i rollback avvengono su tutte le transazioni aperte nella pagina, anche se sono state create connessioni multiple.
Questo esempio dimostra come le connessioni sono condivise.
Esempio 1. esempio di ocilogon()
|
Vedere anche ociplogon() e ocinlogon().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
ocinewcursor() alloca un nuovo identificatore di istruzione sulla connessione specificata.
Esempio 1. Using a REF CURSOR from a stored procedure
|
Esempio 2. Using a REF CURSOR in a select statement
|
ocinewdescriptor() alloca memoria per accogliere descrittori o locatori LOB. I valori validi per il parametro type sono OCI_D_FILE, OCI_D_LOB e OCI_D_ROWID. Per i descrittori LOB, i metodi load, save, e savefile sono associati al descrittore, per i BFILE esiste solo il metodo load. Vedere i suggerimenti nel secondo esempio.
Esempio 1. esempio di ocinewdescriptor()
|
Esempio 2. OCINewDescriptor
|
ocinlogon() crea una nuova connessione a un database Oracle 8 e si autentica. Il terzo parametro opzionale può contenere il nome della istanza Oracle locale o il nome della voce in tnsnames.ora a cui ci si vuole connettere. Se il terzo parametro opzionale non è specificato, PHP usa la variabile d'ambiente ORACLE_SID (istanza di Oracle) o TWO_TASK (in tnsnames.ora) per determinare a quale database collegarsi.
ocinlogon() forza una nuova connessione. Si deve usare quando si ha necessità di isolare un insieme di transazioni. Di default, le connessioni sono condivise a livello di pagina se si usa ocilogon() o a livello di processo del web server se si usa ociplogon(). Se ci sono connessioni multiple aperte con ocinlogon(), tutti i commit e rollback avverranno solo sulla connessione specificata.
Questo esempio dimostra come le connessioni sono isolate.
Esempio 1. esempio di ocinlogon()
|
Vedere anche ocilogon() e ociplogon().
(PHP 3 >= 3.0.4, PHP 4, PHP 5)
ocinumcols -- Restituisce il numero di campi che risultano da un comando SQLocinumcols() restituisce il numero di campi contenuti in un'istruzione SQL.
Esempio 1. ocinumcols()
|
ociparse() analizza la query rispetto alla connessione conn. Restituisce un identificatore di istruzione se la query è valida, FALSE altrimenti. La query può essere qualsiasi comando SQL o blocco di codice PL/SQL.
ociplogon() crea una connessione persistente a un database Oracle 8 e si autentica. Il terzo parametro opzionale può contenere il nome della istanza Oracle locale o il nome della voce in tnsnames.ora a cui ci si vuole connettere. Se il terzo parametro opzionale non è specificato, PHP usa la variabile d'ambiente ORACLE_SID (istanza di Oracle) o TWO_TASK (in tnsnames.ora) per determinare a quale database collegarsi.
Vedere anche ocilogon() e ocinlogon().
ociresult() restituisce i dati del campo column nella tupla corrente (vedere ocifetch()).ociresult() restituirà tutto come stringa, eccetto i tipi astratti (ROWIDs, LOBs e FILEs).
ocirollback() annulla tutte le transazioni in sospeso sulla connessione Oracle connection. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere anche ocicommit()
ocirowcount() restituisce il numero di tuple modificate, ad esempio, da un comando update. Questa funzione non riporta il numero di tuple restituite da una select!
Esempio 1. esempio di ocirowcount()
|
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 3 >= 3.0.4, PHP 4, PHP 5)
ociserverversion -- Restituisce una stringa contenente informazioni sulla versione del serverImposta a rows il numero di tuple da precaricare. Il valore di default è 1.
ocistatementtype() restituisce uno dei seguenti valori:
SELECT
UPDATE
DELETE
INSERT
CREATE
DROP
ALTER
BEGIN
DECLARE
UNKNOWN
Esempio 1. Esempi di ocistatementtype()
|
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
ociwritetemporarylob -- Alias di OCI-Lob->writeTemporaryIn aggiunta al normale supporto ODBC, le funzioni ODBC unificate del PHP consentono l'accesso a diversi database che hanno preso in prestito la semantica dell'API ODBC per implementare le loro API. Invece di mantenere più driver per database che sono tutti pressoché identici, questi driver sono stati riuniti in un singolo insieme di funzioni ODBC.
Le funzioni ODBC unificate supportano i seguenti database: Adabas D, IBM DB2, iODBC, Solid ed Sybase SQL Anywhere.
Nota: Nella connessione ai database sopra elencati non vengono coinvolte funzioni ODBC. Le funzioni che vengono utilizzate per collegarsi nativamente con essi condividono solamente lo stesso nome e sintassi delle funzioni ODBC. L'eccezione a questo è iODBC. Compilando il PHP con il supporto di iODBC, si può utilizzare qualsiasi driver compatibile ODBC nelle applicazioni PHP. iODBC è gestito da OpenLink Software. Maggiori informazioni su iODBC, ed un HOWTO sono diponibili nel sito www.iodbc.org.
Per potere accedere ai database supportati occorre avere installato le librerie necessarie.
Include il supporto per Adabas D. DIR indica la directory di installazione di Adabas, il default è /usr/local.
Include il supporto per SAP DB. DIR indica la directory di installazione di SAP DB, il default è /usr/local.
Include il supporto per Solid. DIR indica la directory di installazione di Solid, il default è /usr/local/solid.
Include il supporto per IBM DB2. DIR indica la directory di installazione di DB2, il default è /home/db2inst1/sqllib.
Include il supporto per Empress. DIR indica la directory di installazione di Empress, il default è $EMPRESSPATH. A partire da PHP 4, questa opzione supporta solo Empress Versione 8.60 e successive.
Include il supporto per Empress Local Access. DIR indica la directory di installazione di Empress, il default è $EMPRESSPATH. A partire da PHP 4, questa opzione supporta solo Empress Versione 8.60 e successive.
Include il supporto per Birdstep. DIR indica la directory di installazione di Birdstep, il default è /usr/local/birdstep.
Include il supporto definito dall'utente per ODBC. DIR indica la directory di installazione di ODBC, il default è /usr/local. Accertarsi di definire CUSTOM_ODBC_LIBS e di avere odbc.h nelle directory di include. Ad esempio, si devorebbe definire i seguenti parametri per Sybase SQL Anywhere 5.5.00 su QNX, prima di eseguire lo script di configurazione: CPPFLAGS="-DODBC_QNX -DSQLANY_BUG" LDFLAGS=-lunix CUSTOM_ODBC_LIBS="-ldblib -lodbc".
Include il supporto per iODBC. DIR indica la directory di installazione di iODBC, il default è /usr/local.
Include il supporto per Easysoft OOB. DIR indica la directory di installazione di OOB, il default è /usr/local/easysoft/oob/client.
Include il supporto per unixODBC. DIR indica la directory di installazione di unixODBC, il default è /usr/local.
Include il supporto per OpenLink ODBC. DIR indica la directory di installazione di OpenLink, il default è /usr/local. This is the same as iODBC.
Include il supporto per DBMaker. DIR indica la directory di installazione di DBMaker, per default si ha la directory in cui è installata l'ultima versione di DBMaker (tipo /home/dbmaker/3.6).
Per disabilitare il supporto alle funzioni ODBC unificate in PHP 3 aggiungere il parametro --disable-unified-odbc nella linea di configurazione. Ciò è applicabile soltanto se è abilitata una delle seguenti interfaccie: iODBC, Adabas, Solid, Velocis oppure una versione personalizzata di ODBC.
La versione per Windows di PHP ha già compilato il supporto per questo modulo. Non occorre caricare alcun modulo addizionale per potere utilizzare queste funzioni.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. Parametrizzazione per il modulo Funzioni ODBC Unificate
Nome | Default | Modificabile | Log delle modifiche |
---|---|---|---|
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: I parametri segnati con * non sono ancora implementati.
Breve descrizione dei parametri di configurazione.
Sorgenti di dati ODBC da utilizzare se non viene fornita in odbc_connect() o odbc_pconnect().
Nome utente da usare se non viene passato nelle funzioni odbc_connect() o odbc_pconnect().
Password da usare se non viene passato nelle funzioni odbc_connect() o odbc_pconnect().
Indica se permettere le connessioni ODBC persistenti.
Verifica se una connessione è ancora valida prima di ri-utilizzarla.
Imposta il numero massimo di connessioni persistenti permesse per processo.
Imposta il numero massimo di connessioni permesse per processo, comprese le connessioni persistenti.
Gestisce i campi di tipo LONG. Specifica il numero di byte da ritornare alla variabile.
When an integer is used, the value is measured in bytes. You may also use shorthand notation as described in this FAQ.
Gestione dei dati binari.
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Se non viene fornito il parametro OnOff, la funzione restituisce lo stato dell'auto-commit per id_connessione. Il valore reso è vero se l'autocommit è attivo, altrimenti falso se non è attivato oppure si verifica un errore.
Se il campo OnOff è posto a vero, l' auto-commit è abilitato, se è valorizzato a falso l'auto-commit è disabilitato. La funzione restituisce TRUE se l'operazione riesce, FALSE se si verifica un errore.
Per default, l'auto-commit è abilitato. La disabilitazione dell'auto-commit equivale ad iniziare una transazione.
Vedere inoltre odbc_commit() e odbc_rollback().
(Tipi di campi ODBC SQL coinvolti: BINARY, VARBINARY, LONGVARBINARY)
ODBC_BINMODE_PASSTHRU: Restituzione del dato binario direttamente al client
ODBC_BINMODE_RETURN: restituisce il dato inalterato
ODBC_BINMODE_CONVERT: Conversione in char
Quando si esegue la conversione da dati binari SQL a dati di tipo char del C, ciascun byte ( 8 bits) dei dati sorgenti vengono rappresentati da 2 caratteri ASCII. Questi caratteri sono la rappresentazione ASCII dei numeri nella loro forma esadecimale. Ad esempio, il valore binario 00000001 è convertito in "01" e il valore binario 11111111 è convertito come "FF".
Tabella 1. Gestione del tipo LONGVARBINARY
Modalità | Impostazione di longreadlen | Comportamento |
---|---|---|
ODBC_BINMODE_PASSTHRU | 0 | direttamente al client |
ODBC_BINMODE_RETURN | 0 | direttamente al client |
ODBC_BINMODE_CONVERT | 0 | direttamente al client |
ODBC_BINMODE_PASSTHRU | 0 | passthru |
ODBC_BINMODE_PASSTHRU | >0 | direttamente al client |
ODBC_BINMODE_RETURN | >0 | restituito inalterato |
ODBC_BINMODE_CONVERT | >0 | restituito come char |
Se viene utilizzata odbc_fetch_into(), nei casi in cui il dato viene inviato direttamente al client, quest'ultima restituisce una stringa vuota per le colonne binarie.
Se l'argomento id_risultato è valorizzato a 0, il settaggio viene applicato come default per i nuovi risultati.
Nota: I valori di default per longreadlen è 4096, mentre la modalità di default è ODBC_BINMODE_RETURN. La gestione delle colonne di campi long binary, è anche gestita dalla funzione odbc_longreadlen()
La funzione odbc_close_all() chiude tutte le connessioni aperte con il database server
Nota: Se ci sono delle transazioni aperte sulla connessione richiesta, la funzione fallisce. In questo caso la connessione resta aperta.
odbc_close() chiude la connessione con il database server associata all'identificativo di connessione indicato.
Nota: Se ci sono delle transazioni aperte sulla connessione richiesta, la funzione fallisce. In questo caso la connessione resta aperta.
(PHP 4, PHP 5)
odbc_columnprivileges -- Restituisce un identificatore di risultato che permette di ricavare l'elenco delle colonne e dei privilegi ad esse associati.Elenca le colonne e i privilegi associati ad esse per la tabella data. La funzione ritorna un identificatore di risultato ODBC oppure FALSE se si verifica un errore.
Le righe risultanti dall'elaborazione contengono i seguenti campi:
TABLE_QUALIFIER
TABLE_OWNER
TABLE_NAME
GRANTOR
GRANTEE
PRIVILEGE
IS_GRANTABLE
I campi di ordinamento delle righe risultanti sono TABLE_QUALIFIER, TABLE_OWNER e TABLE_NAME.
L'argomento nome_colonna accetta dei criteri di ricerca ('%' per indicare zero o più caratteri e '_' per indicare un singolo carattere).
Elenca i nomi di tutte le colonne presenti nel range richiesto. La funzione restituisce un identificatore di risultato ODBC oppure FALSE se si verifica un errore.
Le righe risultanti dall'elaborazione contengono i seguenti campi:
TABLE_QUALIFIER
TABLE_SCHKM
TABLE_NAME
COLUMN_NAME
DATA_TYPE
TYPE_NAME
PRECISION
LENGTH
SCALE
RADIX
NULLABLE
REMARKS
I campi di ordinamento delle righe risultanti sono TABLE_QUALIFIER, TABLE_SCHKM e TABLE_NAME.
Gli argomenti schema, nome_tabella e nome_colonna accettano dei criteri di ricerca ('%' per indicare zero o più caratteri e '_' per indicare un singolo carattere).
Vedere anche odbc_columnprivileges() per ottenere i privilegi associati alle colonne.
La funzione odbc_commit() esegue tutte le transazioni pendenti sulla connessione indicata dall'argomento id_connessione. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Restituisce un identificatore di connessione ODBC oppure 0 (falso) se si verifica un errore.
L'identificatore di connessione ritornato da questa funzione è utilizzato dalle altre funzioni ODBC. Si possono avere più connessioni aperte contemporaneamente se queste utlizzano differenti database o differenti credenziali utente. Il quarto parametro (opzionale), setta il tipo di cursore da utilizzare per questa connessione. Normalmente questo parametro non è necessario, ma può essere utilizzato per aggirare dei problemi che si manifestano con alcuni driver ODBC.
Con alcuni driver ODBC, l'esecuzione di complesse procedure può generare un errore tipo: "Non si riesce ad aprire un cursore sulla procedura che richieda qualsiasi cosa oltre ad un singola istruzione select". L'uso di SQL_CUR_USE_ODBC, può evitare questo errore. Inoltre alcuni driver non supportano il parametro row_number della funzione odbc_fetch_row(). In questo caso SQL_CUR_USE_ODBC può essere d'aiuto.
Il campo tipo_cursore può assumere le seguenti costanti:
SQL_CUR_USE_IF_NEEDED
SQL_CUR_USE_ODBC
SQL_CUR_USE_DRIVER
SQL_CUR_DEFAULT
Per le connessioni persistenti vedere odbc_pconnect().
odbc_cursor restituisce il nome del cursore per l'argomento id_risultato.
La funzione restituisce FALSE se si verifica un errore, oppure un array se ha successo.
Questa funzione restituisce la listya dei DNS disponibili ( dopo essere stata richiamata diverse volte). E' obbligatorio che il parametro connection_id sia una connessione ODBC valida. Il parametro fetch_type può essere impostato ad una delle seguenti costanti: SQL_FETCH_FIRST oppure SQL_FETCH_NEXT. Utilizzare SQL_FETCH_FIRST la prima volta che si richiama la funzione, SQL_FETCH_NEXT le volte successive.
odbc_do() esegue una query sulla connessione data.
La funzione restituisce un codice di 6 cifre indicante lo stato di ODBC. Se non vi sono errori viene restituita una stringa vuota. Se viene passato il parametro id_connessione, viene restituito l'ultimo stato di questa connessione, altrimenti si ha l'ultimo stato dell'ultima operazione su una qualsiasi connessione.
Questa funzione restituisce valori sensati se l'ultima query ODBC è fallita (ad esempio odbc_exec() restituisce FALSE).
Vedere anche: odbc_errormsg() e odbc_exec().
la funzione restituisce una stringa contenente l'ultimo messaggio di errore generato da ODBC, oppure una stringa vuota se non ci sono errori. Se viene passato il parametro id_connessione, viene restituito l'ultimo stato di questa connessione, altrimenti si ha l'ultimo stato dell'ultima operazione su una qualsiasi connessione.
Questa funzione restituisce valori sensati se l'ultima query ODBC è fallita (ad esempio odbc_exec() restituisce FALSE).
Vedere anche: odbc_error() and odbc_exec().
Restituisce FALSE se si verifica un errore. Restituisce un identificatore del risultato ODBC se l'espressione SQL viene eseguita correttamente.
odbc_exec() invia una espressione SQL al server tramite la connessione specificata da id_connessione. Questo parametro deve essere un identificativo valido restituito da odbc_connect() oppure odbc_pconnect().
Vedere anche: odbc_prepare() e odbc_execute() per l'esecuzione di molteplici espressioni SQL.
Esegue una espressione SQL memorizzata tramite la funzione odbc_prepare(). Restituisce TRUE in caso di successo, FALSE in caso di fallimento. L'array array_parametri occorre soltanto se è necessario fornire parametri all'espressione.
I parametri in array_parametri saranno sostituiti dai segnaposto nell'ordine dell'espressione predisposta.
Qualsiasi parametro in array_parametri che inizia e finisce con gli apici singoli sarà considerato come il nome di un file da leggere e inviare al database server come dati per gli appropriati segnaposto.
Nota: Dalla versione 4.1.1 la funzionalità di lettura del file ha le seguenti restrizioni:
La lettura del file non è soggetta alle restrizioni di modalità sicura o open-basedir. Questo sarà risolto nella versione 4.2.0 di PHP.
File remoti non sono supportati.
Se si desidera archiviare una stringa che inizia e termina con l'apice singolo, occorre farla precedere dal carattere di escape, oppure da un'altro carattere all'inizio o alla fine del parametro, per prevenire che il parametro sia considerato come nome di un file. Se questo non è possibile occorre utilizzare altri meccanismi per archiviare la stringa, quali, ad esempio, eseguire direttamente la query con odbc_exec().
Scarica, in una matrice associativa, da una query ODBC. Vedere nel successivo log delle modifiche per sapere quando questa funzione è disponibile.
Risorsa risultato da odbc_exec().
Opzionale, indica quale nnumero di riga recuperare.
Restituisce una matrice corrispondente alla riga scaricata, oppure FALSE se non vi sono righe successive.
(PHP 3 >= 3.0.6, PHP 4, PHP 5)
odbc_fetch_into -- Scarica una riga del risultato della query in un arrayLa funzione restituisce il numero di colonne presenti nel risultato; FALSE se si verifica un errore. Il parametro array_dati deve essere passato per referenza, ma può essere di qualsiasi tipo dato che verrà convertito in array. Nell'array saranno posti i valori delle colonne di una riga tratta dalla tabella risultante dalla query a partire dall'indice 0.
A partire dalla versione 4.0.5 di PHP non occorre passare il parametro array_dati per riferimento.
A partire dall versione 4.0.6 di PHP il parametro numero_riga non può essere passato come costante, ma come variabile.
A partire dalla versione 4.2.0 di PHP i parametri array_dati e numero_riga sono stati invertiti. Questo permette al parametro numero_riga di essere ancora una costante. Questa è l'ultima variazione alla funzione.
Scarica un oggetto da una query ODBC. Vedere nel successivo log delle modifiche per sapere quando questa funzione è disponibile.
Risorsa risultato da odbc_exec().
Opzionale, indica quale nnumero di riga recuperare.
Restituisce un oggetto corrispondente alla riga scaricata, oppure FALSE se non vi sono righe successive.
Se odbc_fetch_row() ha successo (c'è almeno una riga), la funzione restituisce TRUE. Altrimenti, se non vi sono più righe, la funzione restituisce FALSE.
odbc_fetch_row() estrae un record dai dati restituiti dalle funzioni odbc_do() / odbc_exec(). Dopo l'esecuzione di odbc_fetch_row(), i campi della riga sono accessibili tramite la funzione odbc_result().
Se non viene specificato il parametro numero_riga, odbc_fetch_row() restituisce la riga successiva dal set delle righe risultanti dalla query. Si può intercalare esecuzioni successive di odbc_fetch_row() con e senza il parametro numero_riga.
Per spostarsi attraverso le righe risultanti, si può eseguire odbc_fetch_row() con il parametro numero_riga impostato a 1, e quindi continuare ad utilizzare odbc_fetch_row() senza numero_riga. Se il driver non supporta l'estrazione di una riga per numero, il campo numero_riga sarà ignorato.
All'interno di un set di righe, referenziate dall'identificativo di risultato ODBC fornito, la funzione odbc_field_len() restituisce la dimensione (precisione) del campo indicato dall'argomento. La numerazione dei campi parte da 1.
Vedere anche: odbc_field_scale() per ottenere la scala di un numero in virgola mobile.
La funzione odbc_field_name() restituisce il nome del campo presente nella colonna richiesta all'interno di un risultato ODBC identificato dal'argomento id_risultato. La numerazione delle colonne parte da 1. La funzione restituisce falso se si verifica un errore.
odbc_field_num() restituisce il numero della colonna in cui si trova il campo richiesto all'interno di un risultato ODBC indicato dall'argomento id_risultato. La numerazione delle colonne parte da 1. Si ottiene FALSE se si verifica un errore.
All'interno di un set di righe, referenziate dall'identificativo di risultato ODBC fornito, la funzione odbc_field_precision() restituisce la precisione del campo indicato dal numero di campo indicato.
Vedere anche: odbc_field_scale() per ottenere la scala di un numero in virgola mobile.
All'interno di un set di righe, referenziate dall'identificativo di risultato ODBC fornito, la funzione odbc_field_scale() restituisce la scala del campo indicato dal numero di campo indicato.
La funzione odbc_field_type() restituisce il tipo di dato SQL del campo indicato dal numero all'interno di un set di righe referenziate dall'identificativo di risultato ODBC passato. La numerazione delle colonne parte da 1.
(PHP 4, PHP 5)
odbc_foreignkeys -- Restituisce l'elenco delle chiavi esterne per la tabella indicata, oppure la lista delle chiavi esterne in altre tabelle che fanno riferimento alla chiave primaria della tabella indicata.La funzione odbc_foreignkeys() ritorna informazioni sulle chiavi esterne. Restituisce un identificatore di risultato oppure FALSE se si verifica un errore.
Le righe risultanti dall'elaborazione contengono i seguenti campi:
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
Se l'argomento pk_tabella contiene il nome di una tabella, la funzione odbc_foreignkeys() ritorna una serie di righe contenenti i dati della chiave primaria della tabella e di tutte le chiavi esterne che hanno riferimenti a questa.
Se l'argomento fk_tabella contiene il nome di una tabella, la funzione odbc_foreignkeys() ritorna una serie di righe contenenti i dati delle chiavi esterne della tabella e delle chiavi primarie ( di altre tabelle ) a cui queste hanno riferimenti.
Se entrambi gli argomenti pk_tabella e fk_tabella contengono nomi di tabelle, odbc_foreignkeys() restituisce le chiavi esterne della tabella specificata in fk_tabella che hanno riferimenti alla chiave primaria della tabella indicata in pk_tabella. La funzione dovrebbe trovare almeno una chiave.
Restituisce sempre TRUE.
La funzione odbc_free_result() permette di non utilizzare molta memoria durante l'esecuzione di uno script. Infatti, se si è sicuri di non avere più bisogno dei dati del risultato, si può eseguire odbc_free_result(), e la memoria associata a id_risultato sarà liberata. Se la funzione non viene utilizzata, le aree di memoria resteranno disponibili per tutta la durata dello script. Al termine verranno liberate in modo automatico.
Nota: Se si ha l'auto-commit disabilitato (vedere odbc_autocommit()) e si esegue odbc_free_result() prima di eseguire il commit, tutte le transazioni pendenti saranno annullate,
(PHP 4, PHP 5)
odbc_gettypeinfo -- Restituisce un identificatore di risultato contenente informazioni sui tipi di dati supportati dalla sorgente di datiRecupera informazioni sui tipi di dati supportati dalla sorgente di dati. La funzione restituisce un identificatore di risultato ODBC oppure FALSE su errore. L'argomento opzionale tipo_dato può essere utilizzato per restringere l'informazione su un singolo tipo.
Le righe risultanti dall'elaborazione contengono i seguenti campi:
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
I campi di ordinamento delle righe risultanti sono DATA_TYPE e TYPE_NAME.
(tipi di campi ODBC ed SQL coinvolti: LONG, LONGVARBINARY) Tramite l'argomento lunghezza si controlla il numero di byte da ritornare a PHP. Se il campo viene posto a 0, i dati della colonna saranno passati direttamente al client.
Nota: Per la gestione delle colonne di tipo LONGVARBINARY si utilizza anche odbc_binmode().
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
All'interno di un set di righe, referenziate dall'identificativo di risultato ODBC fornito, la funzione odbc_num_fields() restituisce il numero di campi (colonne) presenti. La funzione restituisce -1 se si verifica un errore. L'argomento fornito è un identificatore di esito restituito dalla funzione odbc_exec().
odbc_num_rows() ritorna il numero di record presenti in un risultato ODBC. La funzione ritorna -1 se si verifica un errore. Per le clausole INSERT, UPDATE e DELETE, odbc_num_rows() ritorna il numero di righe coinvolte. Nella clausola SELECT questo può essere il numero di righe disponibili.
Nota: Con diversi driver, la funzione odbc_num_rows(), utilizzata con lo scopo di determinare il numero di righe dopo una SELECT, restituisce -1.
Restituisce un identificatore di connessione ODBC oppure 0 (FALSE) su errore. Questa funzione è molto simile a odbc_connect(), eccetto che la connessione non viene realmente chiusa quando lo script finisce. Successive richieste di connessione che utilizzino la stessa combinazione di dsn, utente, password (eseguite sia utilizzando odbc_connect(), sia utilizzando odbc_pconnect()) possono riutilizzare la connessione.
Nota: Le connessioni persistenti non hanno effetti se PHP viene utilizzato come programma CGI.
Per informazioni sul campo opzionale tipo_cursore, vedere la funzione odbc_connect(). Per maggiori dettagli sulle connessioni persistenti, fare riferimento alla FAQ di PHP.
La funzione restituisce FALSE su errore.
Restituisce un identificativo di risultato ODBC se l'espressione SQL viene predisposta correttamente. L'identificativo restituito può essere utilizzato successivamente per eseguire l'espressione utilizzando la funzione odbc_execute().
Alcuni database (tipo IBM DB2, MS SQL server e Oracle) gestiscono le le stored procedure che accettano parametri di tipo IN, INOUT e OUT come definito nelle specifiche ODBC. Tuttavia il driver Unified ODBC supporta soltanto i parametri di tipo IN.
Nel seguente codice, $res sarà valido soltanto se tutti i tre parametri per myproc sono di tipo IN:
<?php $a = 1; $b = 2; $c = 3; $stmt = odbc_prepare($conn, 'CALL myproc(?,?,?)'); $res = odbc_execute($stmt, array($a, $b, $c)); ?> |
(PHP 4, PHP 5)
odbc_primarykeys -- Restituisce un identificatore di risultato che può essere utilizzato per ricavare il nome della colonna che contiene la chiave primaria della tabella.Restituisce il nome della colonna che contiene la chiave primaria per la tabella. La funzione ritorna un identificatore di risultato ODBC oppure FALSE se si verifica un errore.
Le righe risultanti dall'elaborazione contengono i seguenti campi:
TABLE_QUALIFIER
TABLE_OWNER
TABLE_NAME
COLUMN_NAME
KEY_SEQ
PK_NAME
La funzione ritorna la lista dei parametri di input e di output e anche delle colonne che concorrono al determinazione del risultato per le procedure indicate. Viene restituito un identificatore di risultato oppure FALSE se si è un errore.
Le righe risultanti dall'elaborazione contengono i seguenti campi:
PROCEDURE_QUALIFIER
PROCEDURE_OWNER
PROCEDURE_NAME
COLUMN_NAME
COLUMN_TYPE
DATA_TYPE
TYPE_NAME
PRECISION
LENGTH
SCALE
RADIX
NULLABLE
REMARKS
I campi di ordinamento delle righe risultanti sono PROCEDURE_QUALIFIER, PROCEDURE_OWNER, PROCEDURE_NAME e COLUMN_TYPE.
Gli argomenti proprietario, procedura e colonna accettano dei criteri di ricerca ('%' per indicare zero o più caratteri e '_' per indicare un singolo carattere).
(PHP 4, PHP 5)
odbc_procedures -- Restituisce l'elenco delle procedure memorizzate in una specifica sorgente di dati.Si ottiene l'elenco di tutte le procedure presenti nei limiti richiesti. La funzione restituisce un identificatore di risultato, oppure FALSE su errore.
Le righe risultanti dall'elaborazione contengono i seguenti campi:
PROCEDURE_QUALIFIER
PROCEDURE_OWNER
PROCEDURE_NAME
NUM_INPUT_PARAMS
NUM_OUTPUT_PARAMS
NUM_RESULT_SETS
REMARKS
PROCEDURE_TYPE
Gli argomenti proprietario e nome accettano dei criteri di ricerca ('%' per indicare zero o più caratteri e '_' per indicare un singolo carattere).
Restituisce il numero di righe elaborate, oppure FALSE se si verifica un errore.
Dato un identificatore di risultato restituito da odbc_exec(), la funzione odbc_result_all() visualizza tutti i record ottenuti in una di tabella in formato HTML. Utilizzando il parametro opzionale formato, è possibile fornire informazioni addizionali sulla formattazione della tabella.
Restituisce il contenuto dei campi.
Il parametro campo può essere sia un intero indicante il numero di colonna del campo desiderato; sia una stringa contenente il nome del campo. Ad esempio:
Nel primo caso l'esecuzione di odbc_result() restituisce il valore del terzo campo del record corrente della query. Nel secondo, la funzione odbc_result() restituisce il valore del campo il cui nome è "val", sempre utilizzando i dati dal record corrente. Si ha un errore qualora il numero di colonna fornito sia minore di 1 oppure sia superiore al numero delle colonne (o campi) presenti nel record corrente. Analogamente, si ottiene un errore se il nome del campo richiesto non sia presente nella tabella/e oggetto della ricerca.
L'indice dei campi parte da 1. Per quanto riguarda la gestione dei campi di tipo binario o long fare riferimento a odbc_binmode() e a odbc_longreadlen().
Annulla tutte le operazioni pendenti sulla connessione indicata da id_connessione. Se ha successo restituisce TRUE, altrimenti FALSE.
Questa funzione permette di manipolare i parametri ODBC per la connessione o il risultato di una query indicati. La funzione è stata sviluppata per permettere di aggirare dei problemi emersi in alcuni driver ODBC. Pertanto si dovrebbe utilizzare questa funzione soltanto se si è dei programmatori e si conoscono gli effetti generati dalle varie opzioni. Dato che ogni singola versione di driver ODBC supporta differenti parametri, occorre avere a disposizione un buon manuale del driver per avere esposti tutti i differenti settaggi che possono essere utilizzati.
Poiché i parametri possono variare in base al driver ODBC, è fortemente sconsigliato l'uso di questa funzione in script resi pubblici. Inoltre, alcune opzioni di ODBC non sono gestibili da questa funzione, dato che devono essere specificate prima di stabilire la connessione o prima della preparazione della query. Tuttavia, se per un particolare lavoro permette al PHP di funzionare, può evitare il ricorso a prodotti commerciali.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Il campo identificativo indica la connessione o l'esito su cui si varia il settaggio. Per la funzione SQLSetConnectOption(), questo indica l'identificativo di connessione, per SQLSetStmtOption(), indica l'identificativo del risultato.
Il campo funzione indica quale funzione ODBC utilizzare. Dovrebbe essere valorizzato a 1 per SQLSetConnectOption() e a 2 per SQLSetStmtOption().
Il parametro opzione indica l'opzione da settare.
Il campo parametro indica il valore per l'opzione richiesta.
Esempio 1. Esempi di utilizzo
|
(PHP 4, PHP 5)
odbc_specialcolumns -- Restituisce sia il set di colonne che identificano in modo univoco una riga nella tabella, sia colonne che sono automaticamente aggiornate quando un qualsiasi campo della riga viene aggiornato da una transazione.Quando l'argomento tipo è impostato a SQL_BEST_ROWID, odbc_specialcolumns() restituisce la colonna o le colonne che identificano in modo univoco ciascuna riga nella tabella.
Quando l'argomento tipo è impostato a SQL_ROWVER, odbc_specialcolumns() restituisce la colonna o le colonne della tabella indicata, se ve ne sono, che sono state aggiornate automaticamente dalla sorgente dati quando un qualsiasi campo della riga è stato aggiornato da una transazione.
La funzione restituisce un identificatore di risultato ODBC, oppure FALSE su errore.
Le righe risultanti dall'elaborazione contengono i seguenti campi:
SCOPE
COLUMN_NAME
DATA_TYPE
TYPE_NAME
PRECISION
LENGTH
SCALE
PSEUDO_COLUMN
Le righe del risultato sono ordinate in base alla colonna SCOPE.
Si ottengono informazioni statistiche sulla tabella e i propri indici. La funzione restituisce un identificatore di risultato ODBC, oppure FALSE su errore.
Le righe risultanti dall'elaborazione contengono i seguenti campi:
TABLE_QUALIFIER
TABLE_OWNER
TABLE_NAME
NON_UNIQUE
INDEX_QUALIFIER
INDEX_NAME
TYPE
SEQ_IN_INDEX
COLUMN_NAME
COLLATION
CARDINALITY
PAGES
FILTER_CONDITION
I campi di ordinamento delle righe risultanti sono NON_UNIQUE, TYPE, INDEX_QUALIFIER, INDEX_NAME e SEQ_IN_INDEX.
Elenca le tabelle presenti nei limiti richiesti e, per ciascuna di queste, ne fornisce i privilegi. La funzione ritorna un identificatore di risultato ODBC, oppure FALSE su errore.
Le righe risultanti dall'elaborazione hanno i seguenti campi:
TABLE_QUALIFIER
TABLE_OWNER
TABLE_NAME
GRANTOR
GRANTEE
PRIVILEGE
IS_GRANTABLE
I campi di ordinamento delle righe risultanti sono TABLE_QUALIFIER, TABLE_OWNER e TABLE_NAME.
Gli argomenti proprietario e nome accettano dei criteri di ricerca ('%' per indicare zero o più caratteri e '_' per indicare un singolo carattere).
(PHP 3 >= 3.0.17, PHP 4, PHP 5)
odbc_tables -- Restituisce l'elenco delle tabelle presenti in una specifica sorgente di datiLa funzione elenca tutte le tabelle presenti nei limiti richiesti. Restituisce un identificatore di risultato in cui vi sono i dati oppure FALSE se si verifica un errore.
Le righe risultanti hanno i seguenti campi:
TABLE_QUALIFIER
TABLE_OWNER
TABLE_NAME
TABLE_TYPE
REMARKS
I campi di ordinamento delle righe risultanti sono TABLE_TYPE, TABLE_QUALIFIER, TABLE_OWNER e TABLE_NAME.
Gli argomenti proprietario e nome accettano dei criteri di ricerca ('%' per indicare zero o più caratteri e '_' per indicare un singolo carattere).
Per supportare l'enumerazione delle qualifiche, dei proprietari e dei tipi tabelle, è stata predisposta la seguente semantica per i campi qualifica, proprietario, nome, e tipo:
Se l'argomento qualifica è valorizzato con il carattere percento (%) e i parametri proprietario e nome sono delle stringhe vuote, il risultato sarà un set di righe contenente la lista delle qualifiche previste per la sorgente di dati. (Tutte le colonne tranne TABLE_QUALIFIER conterranno NULL.)
Se l'argomento proprietario è valorizzato con il carattere percento (%) e i parametri qualifica e nome sono delle stringhe vuote, il risultato sarà un set di righe contenente la lista dei proprietari previsti per la sorgente di dati. (Tutte le colonne tranne TABLE_OWNER conterranno NULL.)
Se l'argomento tipo è valorizzato con il carattere percento (%) e i parametri qualifica, proprietario e nome sono delle stringhe vuote, il risultato sarà un set di righe contenente la lista dei tipi di tabella previsti per la sorgente di dati. (Tutte le colonne tranne TABLE_TYPE conterranno NULL.)
Se l'argomento tipo non è una stinga vuota, deve contenere l'elenco dei tipi interessati separati dalla virgola; ogni singolo valore può essere, o meno, racchiuso tra apici singoli ('). Ad esempio: "'TABLE','VIEW'" o "TABLE, VIEW" sono valori validi. Se la sorgente di dati non supporta alcuni dei tipi di tabelle specificati, per questi, la funzione odbc_tables() non riporta alcuna informazione.
Vedere inoltre odbc_tableprivileges() per ottenere i privilegi associati alla tabella.
PDO_ODBC is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to databases through ODBC drivers or through the IBM DB2 Call Level Interface (DB2 CLI) library. PDO_ODBC currently supports three different "flavours" of database drivers:
Supports access to IBM DB2 Universal Database, Cloudscape, and Apache Derby servers through the free DB2 client.
Supports access to database servers through the unixODBC driver manager and the database's own ODBC drivers.
Offers a compile option for ODBC driver managers that are not explicitly supported by PDO_ODBC.
On Windows, PDO_ODBC is built into the PHP core by default. It is linked against the Windows ODBC Driver Manager so that PHP can connect to any database cataloged as a System DSN, and is the recommended driver for connecting to Microsoft SQL Server databases.
As of PHP 5.1, PDO_ODBC is included in the PHP source. You can compile the PDO_ODBC extension as either a static or shared module using the following configure commands.
./configure --enable-pdo_odbc=ibm-db2,/opt/IBM/db2/V8.1/ |
If you do not supply a location for the DB2 libraries and headers to the configure command, PDO_ODBC defaults to /home/db2inst1/sqllib.
./configure --enable-pdo_odbc=unixODBC,/usr/local |
./configure --enable-pdo_odbc=generic,/usr/local,libname,ldflags,cflags |
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. PDO_ODBC Configuration Options
Name | Default | Changeable | Changelog |
---|---|---|---|
pdo_odbc.connection_pooling | "strict" | PHP_INI_ALL |
Breve descrizione dei parametri di configurazione.
Whether to pool ODBC connections. Can be one of "strict", "relaxed" or "off" (equals to ""). The parameter describes how strict the connection manager should be when matching connection parameters to existing pooled connections. strict is the recommend default, and will result in the use of cached connections only when all the connection parameters match exactly. relaxed will result in the use of cached connections when similar connection parameters are used. This can result in increased use of the cache, at the risk of bleeding connection information between (for example) virtual hosts.
This setting can only be changed from the php.ini file, and affects the entire process; any other modules loaded into the process that use the same ODBC libraries will be affected too, including the Unified ODBC extension.
Avvertimento |
relaxed matching should not be used on a shared server, for security reasons. |
Suggerimento: Leave this setting at the default strict setting unless you have good reason to change it.
The PDO_ODBC Data Source Name (DSN) is composed of the following elements:
The DSN prefix is odbc:. If you are connecting to a database cataloged in the ODBC driver manager or the DB2 catalog, you can append the cataloged name of the database to the DSN.
The name of the database as cataloged in the ODBC driver manager or the DB2 catalog. Alternately, you can provide a complete ODBC connection string to connect to a database as described at http://connectionstrings.com/.
The name of the user for the connection. If you specify the user name in the DSN, PDO ignores the value of the user name argument in the PDO constructor.
The password of the user for the connection. If you specify the password in the DSN, PDO ignores the value of the password argument in the PDO constructor.
The OGG/Vorbis file format, as defined by http://www.vorbis.com/ and http://www.vorbis.com/, is a scheme for compressing audio streams by multiple factors with a minimum of quality loss. This extension adds Ogg Vorbis support to PHP's URL Wrappers. When used in read mode, compressed OGG/Vorbis data is expanded to raw PCM audio in one of six PCM encoding formats listed below.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
oggvorbis is installed through the usual PECL package installation process.
$ pear install oggvorbis |
Copy the resulting oggvorbis.so to an appropriate location and add extension=oggvorbis.so to your php.ini file or load it dynamically in your PHP script using dl('oggvorbis.so');
Tabella 1. OGG/Vorbis tuning options
Option | Definition | Relevance | Default |
---|---|---|---|
pcm_mode | PCM byte encoding used. See constants below. | Read / Write | OGGVORBIS_PCM_S16_LE |
rate | PCM Sampling rate. Measured in Hz. | Write only | 44100 |
bitrate | Vorbis Average Bitrate Encoding / Variable Bitrate Encoding. Measured in bps (ABR) or Quality level (VBR: 0.0 to 1.0). 128000 ABR is rough equal to 0.4 VBR. | Write only | 128000 |
channels | Number of PCM channels. 1 == Mono, 2 == Stereo. | Write only | 2 |
serialno | Serial Number of stream within file. Must be unique within file. Because of the potential to select a duplicate serial number within a chained file, make efforts to manually assign unique numbers when encoding. | Write only | Random |
comments | Associative array of file comments. Will be translated to strtoupper($name) . "=$value". Note: This context option is not available in oggvorbis-0.1 | Write only | array('ENCODER' => 'PHP/OggVorbis, http://pear.php.net/oggvorbis') |
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Tabella 2. OGG/Vorbis supports PCM encodings in the following formats
Constant | Definition |
---|---|
OGGVORBIS_PCM_U8 | Unsigned 8-bit PCM. |
OGGVORBIS_PCM_S8 | Signed 8-bit PCM. |
OGGVORBIS_PCM_U16_LE | Unsigned 16-bit PCM. Little Endian byte order. |
OGGVORBIS_PCM_U16_BE | Unsigned 16-bit PCM. Big Endian byte order. |
OGGVORBIS_PCM_S16_LE | Signed 16-bit PCM. Little Endian byte order. |
OGGVORBIS_PCM_S16_BE | Signed 16-bit PCM. Big Endian byte order. |
Esempio 1. Reading an OGG/Vorbis file
|
Esempio 2. Encode an audio file to OGG/Vorbis
|
Platform independent audio bindings. Requires the OpenAL library.
This PECL extension is not bundled with PHP.
Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: http://pecl.php.net/package/openal.
You may download this PECL extension DLL from the PHP Downloads page or at http://snaps.php.net/.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
This extension defines four resource types: Open AL(Device) - Returned by openal_device_open(), Open AL(Context) - Returned by openal_context_create(), Open AL(Buffer) - Returned by openal_buffer_create(), and Open AL(Source) - Returned by openal_source_create().
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Context Attribute
Context Attribute
Context Attribute
Buffer Setting
Buffer Setting
Buffer Setting
Buffer Setting
Source/Listener Setting (Integer)
Source/Listener Setting (Integer)
Source/Listener Setting (Integer)
Source/Listener Setting (Float)
Source/Listener Setting (Float)
Source/Listener Setting (Float)
Source/Listener Setting (Float)
Source/Listener Setting (Float)
Source/Listener Setting (Float)
Source/Listener Setting (Float)
Source/Listener Setting (Float)
Source/Listener Setting (Float)
Source/Listener Setting (Float)
Source/Listener Setting (Float Vector)
Source/Listener Setting (Float Vector)
Source/Listener Setting (Float Vector)
Source/Listener Setting (Float Vector)
PCM Format
PCM Format
PCM Format
PCM Format
Source State
Source State
Source State
Source State
Source State
Boolean value recognized by OpenAL
Boolean value recognized by OpenAL
An Open AL(Buffer) resource (previously created by openal_buffer_create()).
Format of data, one of: AL_FORMAT_MONO8, AL_FORMAT_MONO16, AL_FORMAT_STEREO8 e AL_FORMAT_STEREO16
Block of binary audio data in the format and freq specified.
Frequency of data given in Hz.
An Open AL(Buffer) resource (previously created by openal_buffer_create()).
An Open AL(Buffer) resource (previously created by openal_buffer_create()).
Specific property, one of: AL_FREQUENCY, AL_BITS, AL_CHANNELS e AL_SIZE.
Returns an integer value appropriate to the property requested or FALSE on failure.
An Open AL(Buffer) resource (previously created by openal_buffer_create()).
Path to .WAV file on local file system.
An Open AL(Device) resource (previously created by openal_device_open()).
An Open AL(Context) resource (previously created by openal_context_create()).
An Open AL(Context) resource (previously created by openal_context_create()).
An Open AL(Context) resource (previously created by openal_context_create()).
An Open AL(Context) resource (previously created by openal_context_create()).
An Open AL(Device) resource (previously created by openal_device_open()) to be closed.
Open an audio device optionally specified by device_desc. If device_desc is not specified the first available audio device will be used.
Property to retrieve, one of: AL_GAIN (float), AL_POSITION (array(float,float,float)), AL_VELOCITY (array(float,float,float)) e AL_ORIENTATION (array(float,float,float)).
Property to set, one of: AL_GAIN (float), AL_POSITION (array(float,float,float)), AL_VELOCITY (array(float,float,float)) e AL_ORIENTATION (array(float,float,float)).
Value to set, either float, or an array of floats as appropriate.
An Open AL(Source) resource (previously created by openal_source_create()).
An Open AL(Source) resource (previously created by openal_source_create()).
Property to get, one of: AL_SOURCE_RELATIVE (int), AL_SOURCE_STATE (int), AL_PITCH (float), AL_GAIN (float), AL_MIN_GAIN (float), AL_MAX_GAIN (float), AL_MAX_DISTANCE (float), AL_ROLLOFF_FACTOR (float), AL_CONE_OUTER_GAIN (float), AL_CONE_INNER_ANGLE (float), AL_CONE_OUTER_ANGLE (float), AL_REFERENCE_DISTANCE (float), AL_POSITION (array(float,float,float)), AL_VELOCITY (array(float,float,float)), AL_DIRECTION (array(float,float,float)).
Returns the type associated with the property being retrieved or FALSE on failure.
An Open AL(Source) resource (previously created by openal_source_create()).
An Open AL(Source) resource (previously created by openal_source_create()).
An Open AL(Source) resource (previously created by openal_source_create()).
An Open AL(Source) resource (previously created by openal_source_create()).
Property to set, one of: AL_BUFFER (OpenAL(Source)), AL_LOOPING (bool), AL_SOURCE_RELATIVE (int), AL_SOURCE_STATE (int), AL_PITCH (float), AL_GAIN (float), AL_MIN_GAIN (float), AL_MAX_GAIN (float), AL_MAX_DISTANCE (float), AL_ROLLOFF_FACTOR (float), AL_CONE_OUTER_GAIN (float), AL_CONE_INNER_ANGLE (float), AL_CONE_OUTER_ANGLE (float), AL_REFERENCE_DISTANCE (float), AL_POSITION (array(float,float,float)), AL_VELOCITY (array(float,float,float)), AL_DIRECTION (array(float,float,float)).
Value to assign to specified property. Refer to the description of property for a description of the value(s) expected.
An Open AL(Source) resource (previously created by openal_source_create()).
An Open AL(Source) resource (previously created by openal_source_create()).
Format of data, one of: AL_FORMAT_MONO8, AL_FORMAT_MONO16, AL_FORMAT_STEREO8 e AL_FORMAT_STEREO16
Frequency of data to stream given in Hz.
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 between versions 4.0.5 and 4.3.1 will work with OpenSSL >= 0.9.5. Other versions (PHP <=4.0.4pl1 and >= 4.3.2) require OpenSSL >= 0.9.6.
Avvertimento |
You are strongly encouraged to use the most recent OpenSSL version, otherwise your web server could be vulnerable to attack. |
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 folder 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.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
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.
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
The S/MIME functions make use of flags which are specified using a bitfield which can include one or more of the following values:
Tabella 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 you do not specify any flags to openssl_pkcs7_sign(). 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.
The optional parameter 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.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
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.
The optional parameter 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.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
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 an alternative openssl configuration file by setting the value of 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.
Tabella 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 | string | 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 | boolean | encrypt_key | Should an exported key (with passphrase) be encrypted? |
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Esempio 1. openssl_csr_new() example - creating a self-signed-certificate
|
(PHP 4 >= 4.2.0, PHP 5)
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. You can finetune the CSR signing by configargs. See openssl_csr_new() for more information about configargs. Since PHP 4.3.3 you can specify the serial number of issued certificate by serial. In earlier versions, it was always 0.
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.
Esempio 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.
openssl_free_key() frees the key associated with the specified key_identifier from memory.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento. 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.
Esempio 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 its associated private key specified by recipcert and recipkey.
The decrypted message is output to the file specified by outfilename
Esempio 1. openssl_pkcs7_decrypt() example
|
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. Cipher can be selected with cipherid since PHP 5.
Esempio 1. openssl_pkcs7_encrypt() example
|
openssl_pkcs7_sign() takes the contents of the file named infilename and signs them using the certificate and its 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.
Esempio 1. openssl_pkcs7_sign() example
|
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.
(PHP 4 >= 4.2.0, PHP 5)
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. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
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.
(PHP 4 >= 4.2.0, PHP 5)
openssl_pkey_export -- Gets an exportable representation of a key into a stringopenssl_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. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
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.
This function frees a private key created by openssl_pkey_new().
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, PHP 5)
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_public_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.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
You can use this function e.g. to decrypt data which were supposed only to you.
See also openssl_public_encrypt() and openssl_public_decrypt().
openssl_private_encrypt() encrypts data with private key and stores the result into crypted. Encrypted data can be decrypted via openssl_public_decrypt(). padding defaults to OPENSSL_PKCS1_PADDING, but can also be OPENSSL_NO_PADDING.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
This function can be used e.g. to sign data (or its hash) to prove that it is not written by someone else.
See also openssl_public_decrypt() and openssl_public_encrypt().
openssl_public_decrypt() decrypts data that was previous encrypted via openssl_private_encrypt() and stores the result into decrypted. key must be the public key corresponding that was used to encrypt the data. padding defaults to OPENSSL_PKCS1_PADDING, but can also be OPENSSL_NO_PADDING.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
You can use this function e.g. to check if the message was written by the owner of the private key.
See also openssl_private_encrypt() and openssl_private_decrypt().
openssl_public_encrypt() encrypts data with public key and stores the result into crypted. Encrypted data can be decrypted via openssl_private_decrypt(). padding defaults to OPENSSL_PKCS1_PADDING, but can also be one of OPENSSL_SSLV23_PADDING, OPENSSL_PKCS1_OAEP_PADDING, OPENSSL_NO_PADDING.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
This function can be used e.g. to encrypt message which can be then read only by owner of the private key. It can be also used to store secure data in database.
See also openssl_private_decrypt() and openssl_private_encrypt().
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.
Esempio 1. openssl_seal() example
|
See also openssl_open().
Restituisce TRUE in caso di successo, FALSE in caso di fallimento. 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.
Esempio 1. openssl_sign() example
|
See also openssl_verify().
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.
Esempio 1. openssl_verify() example
|
See also openssl_sign().
(PHP 4 >= 4.2.0, PHP 5)
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, PHP 5)
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. It defaults to an empty array.
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.
Tabella 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? |
openssl_x509_export_to_file() stores x509 into a file named by outfilename in a PEM encoded format.
The optional parameter 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.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
openssl_x509_export() stores x509 into a string named by output in a PEM encoded format.
The optional parameter 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.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
openssl_x509_free() frees the certificate associated with the specified x509cert resource from memory.
(PHP 4 >= 4.0.6, PHP 5)
openssl_x509_parse -- Parse an X509 certificate and return the information as an arrayopenssl_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.
Questa estensione permette l'accesso ai server database Oracle. Vedere anche l'estensione OCI8.
You have to compile PHP with the option --with-oracle[=DIR], where DIR defaults to your environment variable ORACLE_HOME.
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
(PHP 3, PHP 4, PHP 5 <= 5.1.0RC1)
Ora_Bind -- effettua il binding di una variabile PHP ad un parametro di OracleRestituisce TRUE se il binding riesce, altrimenti FALSE. I dettagli dell'errore si ottengono usando le funzioni ora_error() e ora_errorcode().
Questa funzione collega la variabile PHP indicata con un parametro SQL. Il parametro SQL deve essere nella forma ":name". Con il parametro facoltativo type, si può determinare se il parametro SQL è di in/out (0, default), in (1) oppure out (2). Dalla versione 3.0.1 di PHP, su possono utilizzare le costanti ORA_BIND_INOUT, ORA_BIND_IN e ORA_BIND_OUT al posto dei numeri.
ora_bind deve essere invocata dopo ora_parse() e prima di ora_exec(). I valori di input possono essere dati mediante assegnamento alle variabili PHP collegate; dopo aver chiamato ora_exec() le variabili PHP collegate contengono i valori di output, se disponibili.
<?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"; ?> |
Restituisce TRUE se la chiusura è effettuata, altrimenti FALSE. I dettagli dell'errore si ottengono con le funzioni ora_error() e ora_errorcode().
Questa funzione chiude un corsore dati aperto con ora_open().
Restituisce il nome del campo/colonna column nel cursore cursor. Il nome è restituito in lettere maiuscole. La colonna 0 è la prima.
(PHP 3, PHP 4, PHP 5 <= 5.1.0RC1)
ora_columnsize -- restituisce la dimensione di un campo risultato OracleRestituisce la dimensione del campo/colonna column nel cursore cursor. La colonna 0 è la prima.
Restituisce il tipo Oracle del campo/colonna column nel cursore cursor. La colonna 0 è la pirma. Il tipo restituito sarà uno dei seguenti:
"VARCHAR2" |
"VARCHAR" |
"CHAR" |
"NUMBER" |
"LONG" |
"LONG RAW" |
"ROWID" |
"DATE" |
"CURSOR" |
Questa funzione esegue una transazione Oracle. Una transazione è definita come tutti i cambiamenti su una data connessione dall'ultimo commit/rollback, con autocommit spento, o dall'inizio della connessione.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento. I dettagli dell'errore si ottengono usando le funzioniora_error() e ora_errorcode().
Questa funzione disabilita il commit automatico dopo ogni ora_exec().
Restituisce TRUE in caso di successo, FALSE in caso di fallimento. I dettagli dell'errore si ottengono usando le funzioni ora_error() e ora_errorcode().
Questa funzione abilita il commit automatico dopo ogni ora_exec() sulla connessione specificata.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento. I dettagli dell'errore si ottengono usando le funzioni ora_error() e ora_errorcode().
Questa funzione è la combinazione veloce di ora_parse(), ora_exec() e ora_fetch(). Analizza, ed esegue un comando SQL, quindi scarica la prima tupla del risultato.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento. I dettagli dell'errore si ottengono usando le funzioni ora_error() e ora_errorcode().
Vedere anche ora_parse(),ora_exec(), e ora_fetch().
Restituisce un messaggio d'errore nella forma XXX-NNNNN dove XXX è la sorgente dell'errore e NNNNN identifica il messaggio d'errore.
Nota: Il supporto per gli id di connessione è stato aggiunto nella versione 3.0.4.
Nelle versioni UNIX di Oracle, è possibile ottenere i dettagli dell'errore in questo modo: $ 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
Restituisce il codice numerico di errore dell'ultimo comando eseguito sul cursore o sulla connessione specificata.
Nota: Il supporto per gli id di connessione è stato aggiunto nella versione 3.0.4.
ora_exec() esegue il comando cursor, già analizzato da ora_parse().
Restituisce TRUE in caso di successo, FALSE in caso di fallimento. I dettagli dell'errore si ottengono usando le funzioni ora_error() e ora_errorcode().
Vedere anche ora_parse(), ora_fetch() e ora_do().
Recupera una tupla e la mette in un array. Il parametro flags ha due valori: se il flag ORA_FETCHINTO_NULLS è impostato, i campi con valori NULL vengono inseriti nell'array; se il flag ORA_FETCHINTO_ASSOC è impostato, viene creato un array associativo.
Restituisce il numero di campi acquisiti.
Vedere anche ora_parse(),ora_exec(), ora_fetch() e ora_do().
Acquisisce una tupla di dati dal cursore specificato.
Restituisce TRUE (la tupla è stata acquisita) o FALSE (non ci sono più tuple, o è avvenuto un errore). Se è avvenuto un errore, i dettagli si ottengono usando le funzioni ora_error() e ora_errorcode(). Se non sono avvenuti errori, ora_errorcode() restituirà 0.
Vedere anche ora_parse(),ora_exec(), e ora_do().
Restituisce i dati del campo o del risultato di una funzione.
Restituisce il contenuto del campo/colonna. Se avviene un errore, viene restituito il valore FALSE e ora_errorcode() restituirà un valore diverso da zero. Si noti, comunque, che un test al valore FALSE sul risultato di questa funzione può dare esito positivo anche in caso non ci siano errori (campo NULL, stringa vuota, il numero 0, la stringa "0").
Depenna l'utente e disconnette dal server.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento. I dettagli dell'errore si ottengono usando le funzioni ora_error() e ora_errorcode().
Vedere anche ora_logon().
Stabilisce una connessione tra PHP e un database Oracle utilizzando la username user e password password specificate.
Le connessioni possono essere create usando SQL*Net fornendo il nomeTNS a user in questo modo:
Se i dati contengono caratteri non-ASCII, si deve controllare di avere impostato NLS_LANG nel proprio environment. Per quanto riguarda i moduli del server, occorre impostarlo nell' environment del server prima di avviarlo.
Restituisce un indice di connessione se l'operazione ha successo, oppure FALSE in caso di errore. I dettagli dell'errore si ottengono usando le funzioni ora_error() e ora_errorcode() functions.
ora_numcols() restituisce il numero di campi di un risultato. Dopo una sequenza parse/exec/fetch restituisce solo risultati che abbiano coerenza.
Vedere anche ora_parse(),ora_exec(), ora_fetch() e ora_do().
ora_numrows() restituisce il numero di tuple in un risultato.
Apre un cursore Oracle associato alla connessione.
Restituisce un indice di cursore oppure FALSE in caso di errore. I dettagli dell'errore si ottengono usando le funzioni ora_error() e ora_errorcode().
Questa funziona analizza un comando SQL o un blocco PL/SQL e lo associa al cursore specificato.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere anche ora_exec(), ora_fetch() e ora_do().
Stabilisce una connessione permanente tra PHP ed un database Oracle con le username and password specificate.
Vedere anche ora_logon().
Questa funzione annulla una transazione Oracle. (Vedere ora_commit() per la definizione di una transazione.)
Restituisce TRUE in caso di successo, FALSE in caso di fallimento. I dettagli dell'errore si ottengono usando le funzioni ora_error() e ora_errorcode() functions.
Avvertimento |
Questo modulo è SPERIMENTALE. Ovvero, il comportamento di queste funzioni, i nomi di queste funzioni, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questo modulo è a vostro rischio. |
The PDO_OCI Data Source Name (DSN) is composed of the following elements:
The DSN prefix is oci:. If you are connecting to a database defined in tnsnames.ora, append the name of the database to the DSN prefix and your DSN is complete.
The URI for the Oracle Instant Client connection takes the form of dbname=//hostname:port-number/database.
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.
Non è necessaria nessuna installazione per usare queste funzioni, esse fanno parte del core di PHP.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. Output Control configuration options
Name | Default | Changeable | Changelog |
---|---|---|---|
output_buffering | "0" | PHP_INI_PERDIR | |
output_handler | NULL | PHP_INI_PERDIR | Available since PHP 4.0.4. |
implicit_flush | "0" | PHP_INI_ALL | PHP_INI_PERDIR in PHP <= 4.2.3. |
Breve descrizione dei parametri di configurazione.
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). As of PHP 4.3.5, this directive is always Off in PHP-CLI.
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_iconv_handler() and you cannot use both ob_gzhandler() and zlib.output_compression.
Nota: Only built-in functions can be used with this directive. For user defined functions, use ob_start().
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 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.
flush() has no effect on the buffering scheme of your webserver or the browser on the client side. Thus you need to call both ob_flush() and flush() to flush the output buffers.
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 topmost output buffer and turns off this output buffering. If you want to further process the buffer's contents you have to call ob_get_contents() before ob_end_clean() as the buffer contents are discarded when ob_end_flush() is called. The function returns TRUE when it successfully discarded one buffer and FALSE otherwise. Reasons for failure are first that you called the function without an active buffer or that for some reason a buffer could not be deleted (possible for special buffer).
The following example shows an easy way to get rid of all output buffers:
Nota: If the function fails it generates an E_NOTICE.
The boolean return value was added in PHP 4.2.0.
See also ob_start(), ob_get_contents(), and ob_flush().
This function will send the contents of the topmost output buffer (if any) and turn this output buffer 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. The function returns TRUE when it successfully discarded one buffer and FALSE otherwise. Reasons for failure are first that you called the function without an active buffer or that for some reason a buffer could not be deleted (possible for special buffer).
Nota: This function is similar to ob_get_flush(), except that ob_get_flush() returns the buffer as a string.
The following example shows an easy way to flush and end all output buffers:
Nota: If the function fails it generates an E_NOTICE.
The boolean return value was added in PHP 4.2.0.
See also ob_start(), ob_get_contents(), ob_get_flush(), 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 and end output buffering. If output buffering isn't active then FALSE is returned. ob_get_clean() essentially executes both ob_get_contents() and ob_end_clean().
See also ob_start() and ob_get_contents().
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().
(PHP 4 >= 4.3.0, PHP 5)
ob_get_flush -- Flush the output buffer, return it as a string and turn off output bufferingob_get_flush() flushs the output buffer, return it as a string and turns off output buffering. ob_get_flush() returns FALSE if no buffering is active.
Nota: This function is similar to ob_end_flush(), except that this function returns the buffer as a string.
Esempio 1. ob_get_flush() example
Il precedente esempio visualizzerà:
|
See also ob_end_clean(), ob_end_flush() and ob_list_handlers().
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 or zero if output buffering is not activated.
See also ob_start() and ob_get_contents().
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: ob_gzhandler() requires the zlib extension.
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 its 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: mode was added in PHP 4.0.5.
Nota: You cannot use both ob_gzhandler() and zlib.output_compression. Also note that using 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 will return an array with the output handlers in use (if any). If output_buffering is enabled or an anonymous function was used with ob_start(), ob_list_handlers() will return "default output handler".
Esempio 1. ob_list_handlers() example
Il precedente esempio visualizzerà:
|
See also ob_end_clean(), ob_end_flush(), ob_get_flush(), ob_start().
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. If the output_callback is not a callable function, this function will return FALSE. If the callback function has two parameters, the second parameter is filled with a bit-field consisting of PHP_OUTPUT_HANDLER_START, PHP_OUTPUT_HANDLER_CONT and PHP_OUTPUT_HANDLER_END.
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 its output accordingly.
Nota: Before PHP 4.3.2 this function did not return FALSE in case the passed output_callback can not be executed.
Avvertimento |
Some web servers (e.g. Apache) change the working directory of a script when calling the callback function. You can change it back by e.g. chdir(dirname($_SERVER['SCRIPT_FILENAME'])) in the callback function. |
If the optional parameter chunk_size is passed, the callback function is called on every first newline after chunk_size bytes of output. The output_callback parameter may be bypassed by passing a NULL value.
If the optional parameter erase is set to FALSE, the buffer will not be deleted until the script finishes (as of PHP 4.3.0).
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. You can't even call functions using the output buffering functions like print_r($expression, true) or highlight_file($filename, true) from a callback function.
Esempio 1. User defined callback function example
Would produce:
|
See also ob_get_contents(), ob_end_flush(), ob_end_clean(), ob_implicit_flush(), ob_gzhandler(), ob_iconv_handler() mb_output_handler(), and ob_tidyhandler().
This function rewrite the URLs and forms with the given variable.
Nota: This function buffers the output.
Esempio 1. output_add_rewrite_var() example
Il precedente esempio visualizzerà:
|
See also output_reset_rewrite_vars(), ob_flush() and ob_list_handlers().
This function resets the URL rewriter and undo the changes made by output_add_rewrite_var() and/or by session_start() that are still in the buffer.
Esempio 1. output_reset_rewrite_vars() example
Il precedente esempio visualizzerà:
|
See also output_add_rewrite_var(), ob_flush(), ob_list_handlers() and session_start().
Ovrimos SQL Server, is a client/server, transactional RDBMS combined with Web capabilities and fast transactions.
Nota: Questo modulo è stato spostato nel repository PECL e non sarà più rilascio con il PHP dalla versione 5.1.0.
Nota: Questo modulo non è disponibile su piattaforme Windows.
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.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Esempio 1. Connect to Ovrimos SQL Server and select from a system table
|
ovrimos_close() is used to close the specified connection to Ovrimos. This has the effect of rolling back uncommitted transactions.
ovrimos_commit() is used to commit the transaction. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
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 db 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.
Esempio 1. ovrimos_connect() Example
|
ovrimos_cursor() returns the name of the cursor. Useful when wishing to perform positioned updates or deletes.
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() executes a prepared statement. Restituisce TRUE in caso di successo, FALSE in caso di fallimento. 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() 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. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Esempio 1. A fetch into example
|
ovrimos_fetch_row() fetches a row from the result set. Column values should be retrieved with other calls. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Esempio 1. A fetch row example
|
ovrimos_field_len() is used to get the length of the output column with number field_number (1-based), in result result_id.
ovrimos_field_name() returns the output column name at the (1-based) index specified.
ovrimos_field_num() returns the (1-based) index of the output column specified by field_name, or FALSE.
ovrimos_field_type() returns the (numeric) type of the output column at the (1-based) index specified by field_number.
ovrimos_free_result() frees the specified result_id. Returns TRUE.
(PHP 4 >= 4.0.3, PHP 5)
ovrimos_longreadlen -- Specifies how many bytes are to be retrieved from long datatypesovrimos_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() returns the number of columns in a result_id resulting from a query.
ovrimos_num_rows() returns the number of rows affected by update operations.
ovrimos_prepare() prepares an SQL statement and returns a result_id (or FALSE on failure).
Esempio 1. Connect to Ovrimos SQL Server and prepare a statement
|
ovrimos_result_all() prints the whole result set as an HTML table. Returns the number of rows in the generated table.
Esempio 1. Prepare a statement, execute, and view the result
|
Esempio 2. ovrimos_result_all() with meta-information
|
Esempio 3. ovrimos_result_all() example
|
ovrimos_result() retrieves the output column specified by field, either as a string or as an 1-based index. Returns FALSE on failure.
Avvertimento |
Questo modulo è SPERIMENTALE. Ovvero, il comportamento di queste funzioni, i nomi di queste funzioni, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questo modulo è a vostro rischio. |
This module allows to read Paradox database and primary index files. It has initial support for creating Paradox databases. Consider it to be experimental due to lack of documentation of the Paradox file format.
Nota: This module has not been tested on other platforms than Debian/GNU Linux for PPC.
Nota: This module is also in development and may change, though I don't expect major changes to the API.
You need at least PHP 5.0.0 and libpx >= 0.1.9. The paradox library (libpx) is available at http://pxlib.sourceforge.net.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
The paradox extension provides also an object oriented API. It consists of only one class called paradox_doc. Its methods only differ from the functions in its name and of course the missing first parameter. The following table will list all methods and its equivalent functions.
Tabella 1. Methods of class paradox_doc
Name of method | Equivalent function |
---|---|
Constructor | px_new() |
Destructor | px_delete() |
open_fp() | px_open_fp() |
create_fp() | px_create_fp() |
close() | px_close() |
numrecords() | px_numrecords() |
numfields() | px_numfields() |
get_record() | px_get_record() |
put_record() | px_put_record() |
get_field() | px_get_field() |
get_schema() | px_get_schema() |
get_info() | px_get_info() |
set_parameter() | px_set_parameter() |
get_parameter() | px_get_parameter() |
set_value() | px_set_value() |
get_value() | px_get_value() |
get_info() | px_get_info() |
set_targetencoding() | px_set_targetencoding() |
set_tablename() | px_set_tablename() |
set_blob_file() | px_set_blob_file() |
timestamp2string() | px_timestamp2string() |
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
The following two tables lists all constants defined by the paradox extension.
Tabella 2. Contants for field types
Name | Meaning |
---|---|
PX_FIELD_ALPHA | Character data with fixed length |
PX_FIELD_DATE | Date |
PX_FIELD_SHORT | Short integer (2 Bytes) |
PX_FIELD_LONG | Long integer (4 Bytes) |
PX_FIELD_CURRENCY | same as PX_FIELD_NUMBER |
PX_FIELD_NUMBER | Double |
PX_FIELD_LOGICAL | Boolean |
PX_FIELD_MEMOBLOB | Binary large object (not supported) |
PX_FIELD_BLOB | Binary large object (not supported) |
PX_FIELD_FMTMEMOBLOB | Binary large object (not supported) |
PX_FIELD_OLE | OLE object (basically a blob, not supported) |
PX_FIELD_GRAPHIC | Graphic (basically a blob, not supported) |
PX_FIELD_TIME | time |
PX_FIELD_TIMESTAMP | timestamp (like the unix timestamp) |
PX_FIELD_AUTOINC | Auto incrementing interger (like PX_FIELD_LONG) |
PX_FIELD_BCD | Decimal number stored in bcd format (not supported) |
PX_FIELD_BYTES | Array of Bytes with not more than 255 bytes (not supported) |
PX_KEYTOLOWER | |
PX_KEYTOUPPER |
Tabella 3. Contants for file types
Name | Meaning |
---|---|
PX_FILE_INDEX_DB | Indexed database |
PX_FILE_PRIM_INDEX | Primary index |
PX_FILE_NON_INDEX_DB | None indexed database |
PX_FILE_NON_INC_SEC_INDEX | None incremental secondary index (not supported) |
PX_FILE_SEC_INDEX | Secondary index (not supported) |
PX_FILE_INC_SEC_INDEX | Incremental secondary index (not supported) |
PX_FILE_NON_INC_SEC_INDEX_G | (not supported) |
PX_FILE_SEC_INDEX_G | (not supported) |
PX_FILE_INC_SEC_INDEX_G | (not supported) |
Closes the paradox database. This function will not close the file. You will have to call fclose() afterwards.
Create a new paradox database file. The actual file has to be opened before with fopen(). Make sure the file is writable. The first parameter is the return value of px_new(). fielddesc is an array containing one element for each field containing its specification. Each field specification is an array itself with either two or three elements.The first element is always a string value used as the name of the field. It may not be larger than ten characters. The second element contains the field type which is one of the constants listed in the table Constants for field types. In the case of a character field, you will have to provide a third element specifying the length of the field.
Nota: This function is highly experimental, due to insufficient documentation of the paradox file format. Database files created with this function can be opened by px_open_fp() and has been successfully opened by the Paradox software, but your milage may vary.
Esempio 1. Creating a Paradox database with two fields
|
Deletes the resource of the paradox file and frees all memory.
Returns the specification of the fieldno'th database field as an associated array. The array contains three fields named name, type, and size.
Returns an associated array with lots of information about a paradox file. This array is likely to extend in the future.
Version of file multiplied by 10.
Name of table as stored in the file.
Number of records in this table.
Number of fields in this table.
Number of bytes used for the header. This is usually 0x800.
This value multiplied by 0x400 is the size of a data block in bytes.
The number of data blocks in the file. Each data block contains a certain number of records which depends on the record size and the data block size (maxtablesize). Data blocks may not necessarily be completely filled.
Number of fields used for the primary index. The fields do always start as field number 1.
The DOS codepage which was used for encoding fields with character data. If the target encoding is not set with px_set_targetencoding() this will be the encoding for character fields when records are being accessed with px_get_record().
The name can be one of the following:
The name of the table as it will be stored in the database header.
The encoding for the output. Data which is being read from character fields is being recode into the targetencoding.
The encoding of the input data which is to be stored into the database.
The record number is an artificial number counting records in the order as they are stored in the database. The first record has number 0.
The optional mode can be PX_KEYTOLOWER or PX_KEYTOUPPER in order to convert the keys into lower or upper case. If mode is not passed or is 0, then the key will be exactly like the field name. The element values will contain the field values. NULL values will be retained and are different from 0.0, 0 or the empty string. Fields of type PX_FIELD_TIME will be returned as an integer counting the number of milliseconds starting at midnight. A timestamp is a floating point value also counting milliseconds starting at the beginning of julian calendar.
Returns the num'th record from the paradox database. The record is returned as an associated array with its keys being the field names.
px_get_schema() returns the database schema.
If the optional mode is PX_KEYTOLOWER or PX_KEYTOUPPER the key will be converted to lower or upper case. If mode is 0 or not passed at all, then the key name will be identical to the field name.
Returns the schema of a database file as an associated array. The key name is equal to the field name. Each array element is itself an associated array containing the two fields type and size. type is one of the constants in table Constants for field types.
name can be one of the following.
The number of primary keys. Paradox databases always use the first numprimkeys fields for the primary index.
Create a new paradox object. You will have to call this function before any further functions. px_new() does not create any file on the disk, it justs creates an instance of a paradox object.
Returns the number of fields in a database file. The return value of this function is identical to the element numfields in the associated array returned by px_get_info().
Returns the number of records in a database file. The return value of this function is identical to the element numrecords in the associated array returned by px_get_info().
Open an existing paradox database file. The actual file has to be opened before with fopen(). This function can also be used to open primary index files and tread them like a paradox database. This is supported for those who would like to investigate a primary index. It cannot be used to accelerate access to a database file.
Stores a record into a paradox database. The record is added at the end of the database.
Sets the name of the file where blobs are going to be read from. Without calling this function, px_get_record() will only return data in blob fields if the data is part of the record and not stored in the blob file. Blob data is stored in the record if it is small enough to fit in the size of the blob field.
Calling this function twice will close the first blob file and open the new one.
Sets various parameters.
name can be one of the following.
The name of the table as it will be stored in the database header.
The encoding for the output. Data which is being read from character fields is being recode into the targetencoding.
The encoding of the input data which is to be stored into the database.
Sets the table name of a paradox database, which was created with px_create_fp(). Applying this function on an existing database has no effect.
Set the encoding for data retrieved from a character field. All character fields will be recoded to the encoding set by this function. If the encoding is not set, the character data will be returned in the DOS code page encoding as specified in the database.
See also px_get_info() to determine the DOS code page.
Returns FALSE if the encoding could not be set, e.g. the encoding is unknown, or pxlib does not support recoding at all. In the second case a warning will be issued.
name can be one of the following.
The number of primary keys. Paradox databases always use the first numprimkeys fields for the primary index.
These functions allow runtime analysis of opcodes compiled from PHP scripts.
This PECL extension is not bundled with PHP.
Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: http://pecl.php.net/package/parsekit.
You may download this PECL extension DLL from the PHP Downloads page or at http://snaps.php.net/.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Return full detail, but without unnecessary NULL extries.
Return shorthand opcode notation.
Opnode Flag
Opnode Flag
Opnode Flag
Opnode Flag
Opnode Flag
Opnode Flag
Opnode Flag
Opnode Flag
Class Type
Class Type
Function Type
Function Type
Function Type
Function Type
Function Type
Node Type
Node Type
Node Type
Node Type
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Opcode
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
A string containing the name of the file to compile. Similar to the argument to include().
A 2D hash of errors (including fatal errors) encountered during compilation. Returned by reference.
One of either PARSEKIT_QUIET or PARSEKIT_SIMPLE. To produce varying degrees of verbosity in the returned output.
Esempio 1. parsekit_compile_file() example
Il precedente esempio visualizzerà:
|
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
A string containing phpcode. Similar to the argument to eval().
A 2D hash of errors (including fatal errors) encountered during compilation. Returned by reference.
One of either PARSEKIT_QUIET or PARSEKIT_SIMPLE. To produce varying degrees of verbosity in the returned output.
Esempio 1. parsekit_compile_string() example
Il precedente esempio visualizzerà:
|
Avvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
A string describing a function, or an array describing a class/method.
Esempio 1. parsekit_func_arginfo() example
Il precedente esempio visualizzerà:
|
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: Questo modulo non è disponibile su piattaforme Windows.
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).
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
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.
Esempio 1. Process Control Example
|
The pcntl_alarm() function creates a timer that will send a SIGALRM signal to the process after seconds seconds. If seconds is zero, no new alarm is created. Any call to pcntl_alarm() will cancel any previously set alarm.
pcntl_alarm() will return the time in seconds that any previously scheduled alarm had remaining before it was to be delivered, or 0 if there was no previously scheduled alarm.
pcntl_exec() executes the program path with arguments args. path must be the path to a binary executable or a script with a valid path pointing to an executable in the shebang ( #!/usr/local/bin/perl for example) as the first line. See your system's man execve(2) page for additional information.
args is an array of argument strings passed to the program.
envs is an array of strings which are passed as environment to the program. The array is in the format of name => value, the key being the name of the environmental variable and the value being the value of that variable.
pcntl_exec() returns FALSE on error and does not return on success.
The pcntl_fork() function creates a child process that differs from the parent process only in its 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().
pcntl_getpriority() gets the priority of pid. If pid is not specified, the pid of the current process is used. Because priority levels can differ between system types and kernel versions, please see your system's getpriority(2) man page for specific details.
pcntl_getpriority() returns the priority of the process or FALSE on error. A lower numerical value causes more favorable scheduling.
process_identifier is one of PRIO_PGRP, PRIO_USER or PRIO_PROCESS.
Avvertimento |
Questa funzione può restituire il Booleano FALSE, ma può anche restituire un valore non-Booleano valutato come FALSE, come ad esempio 0 o "". Per favore fare riferimento alla sezione Booleans per maggiori informazioni. Usare l'operatore === per controllare il valore restituito da questa funzione. |
pcntl_setpriority() sets the priority of pid to priority. If pid is not specified, the pid of the current process is used.
priority is generally a value in the range -20 to 20. The default priority is 0 while a lower numerical value causes more favorable scheduling. Because priority levels can differ between system types and kernel versions, please see your system's setpriority(2) man page for specific details.
process_identifier is one of PRIO_PGRP, PRIO_USER or PRIO_PROCESS.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
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.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
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.
Esempio 1. pcntl_signal() example
|
Nota: As of PHP 4.3.0 PCNTL 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 must use the declare() statement to specify the locations in your program where callbacks are allowed to occur for the signal handler to function properly (as used in the above example).
See also pcntl_fork() and pcntl_waitpid().
The wait function suspends execution of the current process until a child 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 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 wait(2) man page for specific details as to how wait works on your system.
pcntl_wait() returns the process ID of the child which exited, -1 on error or zero if WNOHANG was provided as an option (on wait3-available systems) and no child was available.
If wait3 is available on your system (mostly BSD-style systems), you can provide the optional options parameter. If this parameter is not provided, wait will be used for the system call. If wait3 is not available, providing a value for options will have no effect. The value of options is the value of zero or more of the following two constants OR'ed together:
Tabella 1. Possible values for options if wait3 is available
WNOHANG | Return immediately if no child has exited. |
WUNTRACED | Return for children which are stopped, and whose status has not been reported. |
pcntl_wait() 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().
Nota: This function is equivalent to calling pcntl_waitpid() with a -1 pid and no options.
See also pcntl_fork(), pcntl_signal(), pcntl_wifexited(), pcntl_wifstopped(), pcntl_wifsignaled(), pcntl_wexitstatus(), pcntl_wtermsig(), pcntl_wstopsig() 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:
Tabella 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. |
Nota: Specifying -1 as the pid is equivalent to the functionality pcntl_wait() provides (minus options).
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:
Tabella 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, PHP 5)
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().
La sintassi utilizzata dalle espressioni regolari di queste funzioni ricorda da vicino Perl. Le espressioni regolari devono essere racchiuse tra delimitatori, ad esempio /. Ogni carattere che non sia alfanumerico od il backslash (\) può essere usato come delimitatore. Se il carattere usato come delimitatore deve essere utilizzato all'interno dell'espressione, questo deve essere preceduto dal carattere di escape (\). Infine, a partire dalla versione 4.0.4 di PHP, si possono anche usare i delimitatori stile Perl come (), {}, [], ed <>. Per maggiori dettagli vedere Sintassi dei criteri di riconoscimento.
Il delimitatore finale può essere seguito da vari modificatori che agiscono sul criterio di riconoscimento. Per maggiori informazioni si rimanda al capitolo Modificatori di criterio (Pattern Modifiers).
Utilizzando le funzioni POSIX-esteso il PHP è in grado di supportare le espressioni regolari scritte con la sintassi POSIX-esteso.
Avvertimento |
Occorre prestare attenzione ad alcune limitazioni di PCRE. Maggiori informazioni in merito possono essere reperite alla pagina http://www.pcre.org/pcre.txt for more info. |
Il supporto delle espressioni regolari è ottenuto mediante la libreria PCRE, che è un software open source, scritto da Philip Hazel, ed il cui copyright è detenuto dalla Università di Cambridge, Inghilterra. La libreria è disponibile all'indirizzo ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/.
A partire dalla versione 4.2.0 di PHP queste funzioni sono abilitate per default. Queste funzioni possono essere disattivate usando --without-pcre-regex. Utilizzare --with-pcre-regex=DIR per specificare la directory DIR in cui sono posizionati i file di include e le librerie di PCRE, nel caso non si desideri utilizzare le librerie incluse. Nelle vecchie versioni di PHP, occorre configurare e compilare il PHP con --with-pcre-regex[=DIR] per attivare queste funzioni.
La versione per Windows di PHP ha già compilato il supporto per questo modulo. Non occorre caricare alcun modulo addizionale per potere utilizzare queste funzioni.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Tabella 1. Costanti di PREG
costante | descrizione |
---|---|
PREG_PATTERN_ORDER | Ordina i risultati in modo tale che $matches[0] sia l'array di tutti i testi riconosciuti, $matches[1] sia l'array delle stringhe identificate dal primo criterio posto tra parentesi, e così via. Questa costante si usa solo con preg_match_all(). |
PREG_SET_ORDER | Ordina i risultati in modo tale che $matches[0] sia l'array del primo set di testi riconosciuti, $matches[1] sia l'array del secondo set, e così via. Questa costante si usa solo con preg_match_all(). |
PREG_OFFSET_CAPTURE | Vedere la descrizione di PREG_SPLIT_OFFSET_CAPTURE. Questa costante è disponibile a partire dalla versione 4.3.0 di PHP. |
PREG_SPLIT_NO_EMPTY | Questa costante indica a preg_split() di restituire solo segmenti non vuoti. |
PREG_SPLIT_DELIM_CAPTURE | Questa costante indica a preg_split() di catturare le espressioni tra parentesi nel criterio di delimitazione. Questa costante è disponibile a partire dalla versione 4.0.5 di PHP. |
PREG_SPLIT_OFFSET_CAPTURE | Se viene impostato questo flag, per ogni testo riconosciuto viene restituito l'offset nella stringa di ricerca. Occorre notare che questo cambia il tipo di valore restituito nell'array, ogni elemento è, a sua volta, un'array composto dalla stringa riconosciuta, all'indice 0, e dall'offset della stringa nell'indice 1. Questa costante è disponibile a partire dalla versione 4.3.0 di PHP e si utilizza solo nella funzione preg_split(). |
Di seguito saranno elencati i valori attualmente previsti. I nomi posti tra parentesi si riferiscono ai corrispettivi nomi usati internamente da PCRE.
- i (PCRE_CASELESS)
Se si attiva questo modificatore, l'espressione regolare viene riconosciuta senza distinguere tra le lettere maiuscole e minuscole.
- m (PCRE_MULTILINE)
Per default, PCRE tratta il testo su cui fare la ricerca come una "singola linea" di caratteri (anche se in realtà può contenere diversi "a capo" (newline)). Il carattere di "inizio riga" (^) indica solamente l'inizio del testo passato. Analogamente il carattere di "fine riga" ($) indica la fine del testo o prima se vi sono dei caratteri di "a capo" (a meno che non sia attivato il modificatore D). In questo modo si comporta anche Perl.
Invece quando viene indicato questo modificatore, "inizio riga" e "fine riga" vengono identificati in base ai caratteri di "a capo" presenti nel testo (rispettivamente subito dopo e subito prima di questo carattere). Questo comportamento è equivalente al modificatore /m di Perl. Se nel testo passato non vi sono caratteri di "a capo" o non vi sono occorrenze dei caratteri ^ o $ nell'espressione regolare, l'uso di questo modificatore non ha effetto.
- s (PCRE_DOTALL)
Se si attiva questo modificatore, il carattere . usato nell'espressione regolare indica tutti i possibili caratteri compreso il carattere di "a capo" (newline). Senza questo modificatore il carattere "a capo" viene escluso. Questo modificare è equivalente a /s di Perl. Una espressione regolare contenente una forma negativa, come [^a], riconosce sempre un "a capo" a prescindere da questo modificatore.
- x (PCRE_EXTENDED)
Se si attiva questo modificatore, verranno ignorati gli spazi presenti nell'espressione regolare, tranne quelli preceduti dal carattere di escape (\) o posti all'interno di una classe di caratteri. Saranno, inoltre, ignorati i caratteri posti tra il simbolo # (se non è preceduto dall'escape, ed è posto al di fuori di una classe di caratteri) ed il successivo carattere di "a capo" (newline). Questo comportamento equivale al flag /x di Perl e consente di inserire dei commenti all'interno di espressioni regolari complesse. Gli spazi bianchi non devono mai comparire all'interno di sequenze speciali di caratteri, come, ad esempio, la sequenza (?( che introduce ad un criterio condizionale.
- e
Se viene specificato questo modificatore, la funzione preg_replace() valuta la stringa di sostituzione come codice PHP, quindi utilizza il risultato come testo da sostituire alle stringhe cercate. Gli apici singoli e doppi sono preceduti dal backslash nei riferimenti sostituiti.
Soltanto preg_replace() utilizza questo modificatore; le altre funzioni di PCRE lo ignorano.
Nota: Questo modificatore non è disponibile in PHP 3.
- A (PCRE_ANCHORED)
Se si specifica questo modificatore, si forza un 'ancoraggio' del criterio di ricerca. In pratica questo viene costretto a riconoscere il testo su cui si fa la ricerca solo dall'inizio. Questo effetto può essere ottenuto anche con particolari costruzioni dell'espressione regolare, che rappresentano gli unici modi utilizzabili in Perl per ottenere il medesimo scopo.
- D (PCRE_DOLLAR_ENDONLY)
L'uso di questo modificatore forza il carattere $ dell'espressione regolare a indicare la fine della stringa oggetto della ricerca. Senza questo modificatore il carattere $ indica la posizione subito prima dell'ultimo carattere se questo è un "a capo" (ma comunque non prima di ogni altro "a capo"). Questo modificatore viene ignorato se è attivato il modificatore m. Non vi sono flag equivalenti in Perl.
- S
Quando una espressione regolare è destinata ad essere utilizzata diverse volte, vale la pena dedicare del tempo ad ottimizzare la velocità di riconoscimento. L'uso di questo modificatore permette questa analisi. Al momento lo studio della velocità è significativo per i criteri di ricerca "non ancorati", cioè espressioni che non hanno un carattere di partenza fisso.
- U (PCRE_UNGREEDY)
Questo modificatore inverte la "voracità" delle occorrenze, in modo da non essere voraci per default, ma lo tornano ad essere se seguiti da "?". Questo flag non è compatibile con Perl. Questo comportamento può anche essere settato dalla sequenza (?U) settaggio dei modificatori all'interno del criterio di ricerca
- X (PCRE_EXTRA)
Questo modificatore attiva funzionalità addizionali di PCRE che sono incompatibili con Perl. Ogni backslash (\) posto nell'espressione regolare che non sia seguito da una lettera con significato speciale causa un errore, ciò per riservare queste sequenze a future espansioni. Per default, Perl considera il backslash (\) seguito da una lettera priva di significato speciale come un qualsiasi testo. Al momento non vi sono altre caratteristiche gestite tramite questo modificatore.
- u (PCRE_UTF8)
Questo modificatore attiva funzionalità di PCRE che sono incompatibili con Perl. Le stringhe di ricerca sono considerate come UTF-8. Questo modificatore è disponibile dalla versione 4.1.0 di PHP di Unix e dalla versione 4.2.3 sulla piattaforma win32.
La libreria PCRE è costituita da una serie di funzioni che utilizzano come criterio di riconoscimento le espressioni regolari mutuando la stessa sintassi e la stessa semantica di Perl 5, a parte qualche lieve differenza descritta di seguito. L'attuale implementazione corrisponde alla versione 5.005 di Perl.
In questo capitolo saranno descritte le differenze rispetto a Perl 5.005.
Per default, lo spazio bianco indica tutti i caratteri riconoscibili dalla funzione isspace() della libreria C, ciò non pregiudica la possibilità di compilare PCRE con un set di caratteri alternativi. Normalmente isspace() riconosce gli spazi, il salto pagina, il carattere 'a capo' (newline), il carattere carriage return, la tabulazione orizzontale e verticale. Perl 5 non riconosce nel set dei caratteri indicati dallo "spazio bianco" la tabulazione verticale. Infatti il carattere di escape \v è stato presente per diverso tempo nella documentazione di Perl, ma di fatto non viene riconosciuto. Tuttavia lo stesso carattere viene trattato come spazio bianco fino alla versione 5.002 di Perl. Nelle versioni 5.004 e 5.005 non viene riconosciuto il carattere \s.
PCRE non supporta occorrenze ripetute in espressioni che "guardano avanti". Perl lo permette, ma non nel modo a cui si possa pensare. Ad esempio, (?!a){3}, non indica che i tre caratteri successivi non debbano essere delle "a", ma indica per tre volte che il carattere successivo non debba essere una "a".
Il riconoscimento di criteri parziali che possono verificarsi all'interno di espressioni che "guardano avanti" negative sono contati, ma i loro riferimenti non sono inseriti nel vettore degli offset. Perl valorizza le sue variabili da qualsiasi criterio che sia riconosciuto prima che l'espressione regolare fallisca nel riconoscere qualcosa, ma questo solo se l'espressione che "guarda avanti" contiene almeno un ramo alternativo.
Sebbene il carattere di 0 binario sia supportato nella stringa in cui si deve svolgere la ricerca, non è ammesso nel testo dell'espressione regolare, questo perché il testo viene passato come stringa C conclusa dal carattere zero. Si può comunque utilizzare la sequenza "\\x00" per richiedere il riconoscimento dello zero binario.
Non sono supportate le seguenti sequenze di escape di Perl: \l, \u, \L, \U, \E e \Q. Infatti queste sono implementate nelle funzioni di gestione delle stringhe di Perl e non nel suo motore di riconoscimento delle espressioni regolari.
L'asserzione di Perl \G non è supportata.
Ovviamente PCRE non supporta il costrutto (?{code}).
Al momento in cui si scrive, in Perl 5.005_02 vi sono alcune particolarità riguardanti la parametrizzazione delle stringhe catturate quando parte del criterio di riconoscimento viene ripetuto. Ad esempio, il riconoscimento di "aba" con il criterio /^(a(b)?)+$/, valorizza $2 con la lettera "b", usando il testo "aabbaa" con il criterio /^(aa(bb)?)+$/ non si ha la valorizzazione di $2. Tuttavia se il criterio di riconoscimento viene variato in /^(aa(b(b))?)+$/, sia $2 che $3 vengono valorizzate. Nelle versione 5.004 di Perl, la variabile $2 viene valorizzata in entrambi i casi, come pure è TRUE in PCRE. Se in futuro Perl cambierà nella gestione anche PCRE potrà cambiare di conseguenza.
Un'altra discrepanza non ancora risolta riguarda il criterio di riconoscimento /^(a)?(?(1)a|b)+$/, che in Perl 5.005_02 riconosce la stringa "a", mentre non accade in PCRE. Tuttavia in entrambi ( Perl e PCRE ) il riconoscimento di "a" con il criterio /^(a)?a/ non valorizza $1.
PCRE prevede alcune estensione alla gestione delle espressioni regolari di Perl:
Sebbene le asserzioni che "guardano indietro" richiedano testi di lunghezza fissa, è ammesso che ciascun ramo alternativo del criterio di ricerca possa intercettare stringhe di lunghezza differente. Al contrario Perl 5.005 richiede che tutte le stringhe abbiamo la stessa lunghezza.
Se viene settato PCRE_DOLLAR_ENDONLY e non viene attivato PCRE_MULTILINE, il meta-carattere $ indica soltanto la fine della stringa.
Se si attiva PCRE_EXTRA, un carattere backslash (\) seguito da una lettera che non abbia un significato speciale genera un errore.
Se si attiva PCRE_UNGREEDY, si inverte la "voracità" delle occorrenze, in modo da non essere voraci per default, ma lo tornano ad essere se seguiti da "?".
Di seguito verrà descritta la sintassi e la semantica delle espressioni regolari così come sono supportate da PCRE. La descrizione delle espressioni regolari può essere reperita anche nei manuali di Perl e in numerosi altri libri, alcuni dei quali ricchi di esempi. Ad esempio il libro di Jeffrey Friedl intitolato "Mastering Regular Expressions", edito da O'Reilly (ISBN 1-56592-257-3), li tratta in modo dettagliato. Questa descrizione, invece, viene intesa come una documentazione di riferimento. Una espressione regolare è un criterio utilizzato per identificare parti di un testo partendo da sinistra verso destra. La maggior parte delle lettere identifica se stessa nel testo oggetto del riconoscimento. Ad esempio il banale testo La volpe veloce intercetta la parte del testo uguale all'espressione regolare.
La potenza delle espressioni regolari deriva dalla possibilità di inserire criteri alternativi oppure ripetuti. Questi sono codificati nel criterio di ricerca tramite l'uso di meta-caratteri, lettere che non indicano se stesse, ma sono interpretate in modo particolare.
Esistono due differenti set di meta-caratteri: quelli che sono riconosciuti ovunque tranne che all'interno di parentesi quadrate, e quelli che sono riconosciuti all'interno di parentesi quadrate. I meta-caratteri che si usano all'esterno delle parentesi quadrate sono:
carattere di escape generico con diversi utilizzi
indica l'inizio del testo (o della linea in modalità multi-linea)
indica la fine del testo (o della linea in modalità multi-linea)
indica qualsiasi carattere tranne "a capo" (per default)
carattere di inizio della definizione di classe
carattere di fine della definizione di classe
inizio di un ramo alternativo
inizio di un criterio di riconoscimento parziale
fine del criterio di riconoscimento parziale
estende il significato di (, oppure 0 o 1 occorrenza, oppure occorrenza minima
0 o più occorrenze
1 o più occorrenze
inizia l'intervallo minimo/massimo di occorrenze
termina l'intervallo minimo/massimo di occorrenze
carattere di escape generico con diversi utilizzi
nega la classe, ma solo se posto all'inizio
indica un intervallo
chiude la classe di caratteri
Il carattere backslash (\) ha diversi utilizzi. Primo uso: se viene anteposto a caratteri non alfanumerici, rimuove gli eventuali significati speciali che il carattere può avere. Questo utilizzo di backslash come carattere di escape può essere svolto sia all'interno delle classi di caratteri sia all'esterno.
Ad esempio, un criterio che deve riconoscere il carattere "*" conterrà "\*". Ciò si applica indipendentemente dal carattere seguente, sia esso interpretabile come meta-carattere o meno. Nel caso in cui un carattere non alfanumerico debba identificare se stesso è opportuno farlo precedere dal "\". In particolare per identificare un backslash occorre scrivere "\\".
Se nel criterio di riconoscimento si specifica l'opzione PCRE_EXTENDED, lo spazio bianco (diversamente da quando si trova all'interno di una classe di caratteri), e i caratteri posti tra "#" e un "a capo" all'esterno di una classe di caratteri sono ignorati. Un backslash può essere usato come escape per inserire uno spazio bianco od il carattere "#" come parte del criterio di riconoscimento.
Un secondo utilizzo del backslash consiste nel codificare in modo visibile dei caratteri non visibili. Non ci sono restrizioni nella presenza di caratteri non-stampabili, a parte lo zero binario terminante la stringa dell'espressione regolare. Di seguito saranno elencate le sequenze di caratteri che è preferibile utilizzare per la loro semplicità al posto delle corrispondenti codifiche binarie.
allarme, il carattere BEL (hex 07)
"control-x", dove x è un qualsiasi carattere
escape (hex 1B)
salto pagina (hex 0C)
"a capo" (newline) (hex 0A)
carriage return (hex 0D)
tabulazione (hex 09)
carattere il cui codice esadecimale è hh
carattere il cui codice ottale è ddd, oppure riferimento all'indietro
Il preciso effetto di "\cx" è il seguente: se "x" è una lettera minuscola, viene convertita in lettera maiuscola. In pratica viene invertito il sesto bit (hex 40) del carattere. Quindi "\cz" diventa hex 1A, ma "\c{" diventa hex 3B, mentre "\c;" diventa hex 7B.
Dopo la sequenza "\x", saranno letti due numeri esadecimali (per le lettere non si distingue tra maiuscolo e minuscolo)
Dopo la sequenza "\0" saranno lette due cifre in ottale. In entrambi i casi se vi sono meno di due cifre, saranno usati i numeri presenti. Pertanto la sequenza "\0\x\07" indica 2 zeri binari seguiti dal carattere BEL. Occorre accertarsi di passare le cifre necessarie dopo lo zero iniziale se il carattere che segue può essere scambiato per una cifra in ottale.
Più complicata è la gestione del backslash seguito da una cifra diversa da 0. Al di fuori di una classe di caratteri, PCRE tratta le cifre che trova come numeri decimali. Se il numero è inferiore a 10, oppure vi sono state almeno altrettante parentesi sinistre, la sequenza viene considerata come un riferimento all'indietro. Più avanti, nella parte dei criteri parziali, sarà descritto come funzionano questi riferimenti.
All'interno di una classe di caratteri, oppure nel caso in cui il numero decimale è maggiore di 9 e non ci sono stati altrettanti criteri parziali, PCRE rilegge le prime 3 cifre seguenti il backslash in ottale e genera il carattere dagli 8 bit meno significativi del valore ottenuto. Ogni altra cifra seguente indica se stessa. Ad esempio:
è un'altro modo per indicare uno spazio
ha il medesimo significato dell'esempio precedente che non vi sono 40 sotto-criteri
è sempre un riferimento all'indietro
può essere un riferimento all'indietro o un'altro modo per indicare il carattere di tabulazione
è ancora il carattere di tabulazione
il carattere di tabulazione seguito da "3"
è il carattere con il codice ottale 113 (poiché non ci possono essere più di 99 riferimenti all'indietro)
è un byte con tutti i bit a 1
può essere un riferimento all'indietro o uno zero binario seguito da "8" e da "1"
Occorre rilevare che valori ottali maggiori di 100 non devono essere preceduti dallo zero, questo perché la libreria considera solo tre cifre.
Tutte le sequenze che definiscono il valore di un singolo byte possono essere utilizzate sia all'interno sia all'esterno delle classe di caratteri. Inoltre, all'interno delle classi di caratteri, la sequenza "\b" viene interpretata come carattere di backspace (hex 08), mentre all'esterno ha un'altro significato (come descritto più avanti).
Il terzo utilizzo possibile per il backslash consiste nello specificare il tipo di carattere:
qualsiasi cifra decimale
qualsiasi carattere che non sia una cifra decimale
qualsiasi carattere identificato come spazio bianco
qualsiasi carattere che non sia identificato come spazio bianco
qualsiasi carattere che sia una "parola" (word)
qualsiasi carattere che non sia una "parola" (word)
Ciascuna coppia di sequenze di escape suddivide il set completo dei caratteri in due insiemi disgiunti. Un dato carattere deve essere identificato da un solo insieme di ciascuna coppia.
I caratteri definiti "parole" sono quelle lettere o cifre o il carattere underscore (_), cioè qualsiasi carattere che possa essere parte di una "parola" in Perl. In PCRE le definizioni di lettere e cifre vengono gestite tramite le tabelle dei caratteri, che possono variare in base a specifici parametri di localizzazione (vedere il paragrafo intitolato "Supporto alle localizzazioni"). Ad esempio, nella localizzazione fr (relativa alla Francia), qualche codice carattere maggiore di 128 è utilizzato per le lettere accentate, e queste sono identificate tramite la sequenza \w.
Queste sequenze di tipi di caratteri possono apparire sia all'interno sia all'esterno delle classi di caratteri. Ciascuna di esse identifica un carattere del tipo appropriato. Se durante la fase di identificazione di un testo, si giunge al termine della stringa in cui si esegue il riconoscimento e si hanno ancora di queste sequenze da incrociare, l'operazione di identificazione fallirà perché, ovviamente, non vi sono più caratteri in cui riconoscere le suddette sequenze.
Il quarto utilizzo per il backslash riguarda la costruzione di particolari asserzioni. L'asserzione è una condizione che deve essere soddisfatta ad un certo punto del riconoscimento, senza "consumare" caratteri dalla stringa oggetto del riconoscimento. Più avanti verranno descritte asserzioni più complicate, costruite tramite l'uso di sotto-criteri di riconoscimento, per ora saranno illustrate delle semplici asserzioni costruite con il backslash:
limite di una parola
non limite di una parola
inizio dell'oggetto di ricerca (a prescindere dalla modalità multi-linea)
fine dell'oggetto di ricerca oppure newline alla fine (a prescindere dalla modalità multi-linea)
fine dell'oggetto di ricerca (a prescindere dalla modalità multi-linea)
Queste asserzioni non possono apparire all'interno di una classe di caratteri (attenzione che la sequenza "\b" all'interno di una classe di caratteri indica il carattere backspace).
Viene definito limite di una parola la posizione nella stringa oggetto della ricerca, nella quale il carattere corrente ed il carattere precedente non soddisfano la sequenza \w o la sequenza \W (ad esempio uno soddisfa la sequenza \w e l'altro carattere soddisfa la sequenza \W), oppure quella posizione, all'inizio o alla fine della stringa, nella quale rispettivamente il primo o l'ultimo carattere soddisfa la sequenza \w.
Le asserzioni \A, \Z e \z differiscono dai tradizionali caratteri "^" e "$" (descritti di seguito) per il fatto di identificare sempre l'inizio o la fine della stringa oggetto di ricerca a prescindere da quale opzione sia stata attivata. Infatti queste asserzioni non sono alterate da PCRE_MULTILINE oppure da PCRE_DOLLAR_ENDONLY. La differenza tra \Z e \z consiste nel fatto che \Z identifica sia il carattere precedente il newline posto al termine della stringa sia la fine della stringa, mentre \z identifica solo la fine.
In condizioni normali, il carattere "^", posto all'esterno di una classe di caratteri, indica un asserzione che è vera soltanto se il punto da cui si inizia a identificare il testo si trova all'inizio della stringa oggetto della ricerca. Al contrario, se il carattere "^" si trova all'interno di una classe di caratteri, assume altri significati (vedere i capitoli seguenti).
Non è necessario che il carattere "^" sia la prima lettera del criterio di riconoscimento nei casi in cui si utilizzino dei criteri di riconoscimento alternativi. Tuttavia è necessario che sia la prima lettera nei rami alternativi in cui compare. Se si inserisce il carattere "^" in tutte le alternative, caso che ricorre quando si vuole riconoscere un testo a partire dall'inizio della stringa, si dice che si è costruito un criterio di ricerca "ancorato". (Esistono anche altre costruzioni che portano all'ancoraggio di un criterio di ricerca).
Il carattere dollaro "$" è una asserzione che è TRUE soltanto se il punto a cui si è arrivati ad identificare il testo si trova alla fine della stringa oggetto della ricerca, o nella lettera immediatamente precedente il carattere di "a capo", che (per default) è l'ultimo carattere del testo. Il dollaro "$" non deve essere necessariamente l'ultima lettera di un criterio di riconoscimento se in questo si sono utilizzati dei criteri alternativi. Deve, comunque, essere l'ultima lettera nei criteri ove compare. Il carattere dollaro "$" non ha significati speciali all'interno di una classe di caratteri.
Il comportamento del simbolo "$" può essere variato in modo da identificare la reale fine della stringa oggetto di ricerca attivando il flag PCRE_DOLLAR_ENDONLY durante la compila o durante la fase di riconoscimento. Ciò non influisce sull'asserzione \Z.
Il comportamento dei simboli "^" e "$" può essere influenzato dall'opzione PCRE_MULTILINE. Quando viene attivata, questi caratteri identificano rispettivamente, oltre ai tradizionali inizio e fine testo, la lettera immediatamente successiva ed immediatamente precedente il carattere "\n" presente all'interno della stringa oggetto di ricerca. Per esempio il criterio /^abc$/ riconosce il testo "def\nabc" solo in modalità multi-linea. Di conseguenza i criteri di riconoscimento che sono "ancorati" in modalità singola linea, non lo sono in modalità multi-linea. L'opzione PCRE_DOLLAR_ENDONLY viene ignorata se si attiva il flag PCRE_MULTILINE .
Occorre rilevare che le sequenze \A, \Z e \z possono essere utilizzate per riconoscere l'inizio e la fine del testo in entrambe le modalità, e, se tutti i criteri alternativi iniziano con \A, si ha ancora un criterio "ancorato" a prescindere che sia attivata o meno l'opzione PCRE_MULTILINE.
Il carattere punto ".", all'esterno di una classe di caratteri, identifica qualsiasi carattere, anche quelli non stampabili, ma (per default) non il carattere "a capo". Invece se si abilita l'opzione PCRE_DOTALL si avrà anche il riconoscimento del carattere "a capo". La gestione del simbolo "." è svincolata dalla gestione dei simboli "^" ed "$", l'unica relazione che possono avere riguarda il carattere "a capo". Il punto "." non ha significati speciali all'interno delle classi di caratteri.
Un parentesi quadrata aperta "[" inizia una classe di caratteri; una parentesi quadrata chiusa "]" termina la definizione della classe. Di suo il carattere di parentesi quadrata chiusa non ha significati speciali. Se occorre inserire la parentesi chiusa all'interno di una classe di caratteri, questa deve essere la prima lettera (ovviamente deve seguire il carattere "^", se presente) oppure deve essere preceduta dal carattere di escape "\".
Una classe di caratteri identifica un singolo carattere nella stringa oggetto di ricerca; il carattere deve comparire nel set di caratteri definito dalla classe, a meno che il primo carattere della classe non sia l'accento circonflesso "^", in tal caso il carattere non deve essere nel set definito dalla classe. Se è richiesto l'inserimento del carattere "^" nel set definito dalla classe, questo non deve essere la prima lettera dopo la parentesi di apertura, oppure deve essere preceduto dal carattere di escape (\).
Ad esempio, la classe [aeiou] identifica ogni vocale minuscola, mentre [^aeiou] identifica tutti i caratteri che non siano delle vocali minuscole. Occorre notare che il simbolo "^" è un modo pratico per indicare i caratteri che sono nella classe, citando quelli che non lo sono. Questa non è una asserzione: consuma un carattere della stringa oggetto di ricerca e fallisce se ci si trova alla fine del testo.
In un riconoscimento senza distinzione tra minuscole e maiuscole, ogni lettera della classe identifica sia la versione maiuscola sia la minuscola. Così, ad esempio, la classe [aeiou] identifica sia "A" sia "a", e, in questo caso, [^aeiou] non identifica "A", mentre con la distinzione delle maiuscole [^aeiou] identifica la lettera "A".
Il carattere di "a capo" (newline) non viene trattato in modo speciale nelle classi di caratteri, indipendentemente dalle opzioni PCRE_DOTALL o PCRE_MULTILINE. La classe [^a] riconosce sempre il carattere "a capo".
Il segno meno (-) può essere usato per definire un intervallo all'interno della classe. Ad esempio, [d-m] identifica ogni lettera compresa tra d ed m inclusi. Se occorre inserire il segno meno (-) come carattere da riconoscere o lo si fa precedere dal carattere di escape (\), oppure lo si mette in una posizione tale che non possa essere identificato come definizione di un intervallo (ad esempio all'inizio o alla fine della definizione della classe).
Non è possibile usare il carattere "]" come limite di un intervallo. Un criterio definito come [W-]46], viene inteso come una classe di due caratteri (W e -) seguita dalla stringa 46], in tal modo sarebbero riconosciuti i testi "W46]" oppure "-46]". Quindi è necessario precedere la lettera "]" con il carattere di escape (\), in questo modo [W-\]46], viene interpretata correttamente come una singola classe contenente un range seguito da due caratteri separati. In alternativa, per delimitare l'intervallo si può utilizzare la notazione ottale di "]".
Gli intervalli utilizzano la sequenza di caratteri ASCII. Inoltre possono essere utilizzati per definire caratteri con specifica numerica (ad esempio [\000-\037]). Nei casi in cui si abiliti il riconoscimento senza distinzione tra lettere maiuscole e minuscole, gli intervalli comprendenti lettere identificano sia la lettera maiuscola che minuscola. Ad esempio, [W-c] è equivalente ad [][\^_`wxyzabc] (con il riconoscimento a prescindere dalla lettera maiuscole e minuscole), e, se si utilizza la tabella dei caratteri locali francesi "fr", [\xc8-\xcb] identifica la lettera "e" accentata sia maiuscola sia minuscola.
Nelle classi di caratteri si possono utilizzare le sequenze \d, \D, \s, \S, \w e \W per aggiungere altri tipi di caratteri alla classe. Ad esempio, [\dABCDEF] riconosce qualsiasi cifra esadecimale. Il carattere "^" può essere utilizzato con i caratteri maiuscoli per indicare un set di caratteri più ristretto che l'identificazione del set di caratteri minuscoli. Ad esempio, la classe [^\W_] identifica qualsiasi lettera o cifra ma non il trattino basso (_).
Tutti i caratteri non alfabetici, eccetto \, -, ^ (posto all'inizio) e ] non sono speciali per la classi di caratteri, e non sono dannosi se preceduti dal caratteri di escape (\).
La barra verticale (|) viene utilizzata per separare criteri di riconoscimento alternativi. Ad esempio il seguente criterio gilbert|sullivan può riconoscere "gilbert" oppure "sullivan". Ci possono essere innumerevoli alternative, compresa un'alternativa vuota (per identificare una stringa vuota). Il processo di riconoscimento prova tutte le alternative possibili (da sinistra a destra) fino a quando non ne trova una che sia soddisfatta. Se le alternative sono nella definizione di un criterio parziale il riconoscimento ha successo quando avviene su tutto il criterio.
Le opzioni PCRE_CASELESS, PCRE_MULTILINE , PCRE_DOTALL, PCRE_UNGREEDY e PCRE_EXTENDED possono essere cambiate "al volo" dall'interno del criterio di riconoscimento, utilizzando le sequenze di lettere definite per queste opzioni in Perl, racchiuse tra "(?" ed ")". Le lettere utilizzabili sono:
Tabella 1. Lettere per le opzioni interne
i | per PCRE_CASELESS |
m | per PCRE_MULTILINE |
s | per PCRE_DOTALL |
x | per PCRE_EXTENDED |
U | per PCRE_UNGREEDY |
Ad esempio, (?im) abilita il riconoscimento senza distinzione tra lettere maiuscole e minuscole e la modalità multi-linea. E' anche possibile disabilitare queste opzioni facendo precedere la lettera dal segno meno (-), o combinare l'attivazione con la disattivazione come nel caso (?im-sx), in cui si attiva PCRE_CASELESS e PCRE_MULTILINE e si disattiva PCRE_DOTALL e PCRE_EXTENDED. Se la lettera compare sia prima che dopo il segno meno (-) l'opzione resta disabilitata.
L'ambito di validità delle opzioni dipende da dove sono i flag di abilitazione/disabilitazione nel criterio di ricerca. Nei casi in cui il settaggio di un'opzione avvenga all'esterno di un qualsiasi criterio parziale (come definito in seguito) gli effetti sono medesimi di quando l'attivazione/disattivazione avviene all'inizio del criterio di riconoscimento. Gli esempi seguenti si comportano tutti allo stesso modo:
(?i)abc
a(?i)bc
ab(?i)c
abc(?i)
In questi esempi si attiva PCRE_CASELESS per il criterio "abc". In altre parole, questo settaggio compiuto al primo livello si applica a tutto il criterio (a meno che non vi siano altre variazioni nelle sotto-regole di riconoscimento). Qualora vi siano più settaggi per lo stesso parametro, viene utilizzato quello più a destra.
Se si inserisce la variazione di un'opzione in una sotto-regola gli effetti sono differenti. Questa è una variazione rispetto al comportamento di Perl 5.005. Una variazione apportata all'interno di una sotto-regola, vale solo per la parte della sotto-regola che segue la variazione, pertanto (a(?i)b)c identifica abc, aBc e nessuna altra stringa ( si assume che PCRE_CASELESS non sia usato). Da ciò deriva che le opzioni possono avere comportamenti differenti nelle varie parti del criterio di riconoscimento. Ogni variazione apportata ad una ramo alternativo del criterio viene estesa alle alternative successive della medesima sotto-regola. Ad esempio, (a(?i)b|c) identifica "ab", "aB", "c" e "C", anche se per identificare "C" viene scartato il primo ramo prima di incontrare il settaggio dell'opzione. Questo accade perché gli effetti dei settaggi vengono inseriti nella fase di compila. Diversamente si avrebbero dei comportamenti molto bizzarri.
Le opzioni specifiche di PCRE PCRE_UNGREEDY e PCRE_EXTRA possono essere variate nel medesimo modo delle opzioni Perl compatibili, utilizzando rispettivamente i caratteri U e X. Il flag (?X) è particolare poiché deve comparire prima di qualsiasi opzione esso attivi anche quando si trova al primo livello. E' opportuno inserirlo all'inizio.
Le sotto-regole sono delimitate dalle parentesi tonde e possono essere annidate. La definizione di una parte di una regola di riconoscimento come sotto-regola può servire a:
1. Localizzare un set di alternative. Ad esempio nel seguente criterio di riconoscimento cat(aract|erpillar|) si riconosce una tra le parole "cat", "cataract" oppure "caterpil- lar". Se non fossero state usate le parentesi, il criterio avrebbe permesso il riconoscimento delle parole "cataract", "erpillar" oppure una stringa vuota.
2. Identificare e catturare parte del testo riconosciuto dalla sotto-regola (come illustrato in seguito). Quando il riconoscimento dell'intero criterio ha avuto successo, le porzioni della stringa oggetto della ricerca identificate dalle sotto-regole sono restituite alla funzione chiamante tramite l'argomento vettore della funzione pcre_exec(). Per determinare il numero ordinale di ciascuna sotto-regola si contano le parentesi aperte da sinistra verso destra partendo da 1.
Ad esempio, se si esegue un riconoscimento nella frase "the red king" con il seguente criterio the ((red|white) (king|queen)) si ottengono i testi "red king", "red" e "king", rispettivamente identificati dalla sotto-regola 1, 2 e 3.
Il fatto che le parentesi tonde adempiano a due funzioni non sempre porta a situazioni comprensibili. Spesso capita di dovere raggruppare delle sotto-regole senza per questo essere richiesta la cattura del testo. A tale scopo l'uso della sequenza "?:" dopo la parentesi di apertura permette di indicare che questa sotto-regola non deve catturare il testo, e non deve essere conteggiata nel numero d'ordine delle sotto-regole di cattura. Ad esempio, applicando il criterio the ((?:red|white) (king|queen)) alla frase "the white queen", si catturano i testi "white queen" e "queen", rispettivamente numerati 1 e 2. Il numero massimo di testi catturabili è 99, il numero massimo di sotto-regole, a prescindere che siano di cattura o meno, è 200.
Come utile abbreviazione, nei casi in cui l'attivazione di alcune opzioni debba essere fatta all'inizio di una sotto-regola non di cattura, la lettera dell'opzione può comparire tra la "?" e ":". Pertanto i due criteri
(?i:saturday|sunday)
(?:(?i)saturday|sunday)
riconoscono esattamente lo stesso set di parole. Poiché i rami alternativi sono provati da sinistra verso destra, e le opzioni non sono azzerate fino a quando non si è conclusa la sotto-regola, una opzione attivata in un ramo alternativo si applica a tutte le alternative che seguono. Pertanto, nell'esempio di prima, sia la parola "SUNDAY" che la parola "Saturday" sono testi identificati correttamente.
Le ripetizioni sono il numero delle occorrenze che possono essere indicate dopo i seguenti elementi:
un singolo carattere, possibilmente preceduto dal carattere di escape (\)
il metacarattere .
una classe di caratteri
un riferimento all'indietro (vedere la sezione successiva)
una sotto-regola (a meno che non si tratti di una asserzione - vedere più avanti)
In generale una occorrenza specifica un numero minimo e massimo di riconoscimenti previsti tramite la specifica dei due limiti, posti tra parentesi graffe e separati da una virgola. Entrambi i numeri devono essere minori di 65536 ed il primo deve essere minore o uguale rispetto al secondo. Ad esempio: z{2,4} identifica "zz", "zzz" oppure "zzzz". La parentesi graffa chiusa di suo non rappresenta un carattere speciale. Se si omette il secondo numero, ma si lascia la virgola, non si indica un limite superiore; se sia la virgola sia il secondo numero sono omessi, l'occorrenza specifica l'esatto numero di riconoscimenti richiesti. Il criterio [aeiou]{3,} identifica almeno 3 o più vocali consecutive, mentre \d{8} identifica esattamente 8 cifre. Una parentesi graffa aperta che compaia in una posizione in cui non sia prevista una occorrenza, o che comunque non sia riconducibile alla sintassi di una occorrenza, viene tratta come il carattere "{". Ad esempio {,6} non indica delle occorrenze, ma una stringa di 4 caratteri.
L'indicazione {0} è permessa. Indica di comportarsi come se l'elemento precedente all'occorrenza non fosse presente.
Per praticità (e compatibilità verso il passato) si usano 3 abbreviazioni per le occorrenze più comuni:
E' anche possibile creare un ciclo infinito facendo seguire ad una sotto-regola che non identifica alcun carattere una occorrenza priva di limite superiore. Ad esempio: (a?)*
Le versioni precedenti di Perl e di PCRE segnalavano un errore durante la fase di compila per questi criteri. Tuttavia, poiché vi sono casi dove questi criteri possono essere utili, queste regole sono accettate, ma, se la ripetizione non riconosce alcun carattere, il ciclo viene interrotto.
Per default le occorrenze sono "bramose", infatti identificano più testi possibile (fino al numero massimo permesso), senza per questo fare fallire il riconoscimento della parte rimanente del criterio di ricerca. Il classico esempio dove questo comportamento può essere un problema, riguarda il riconoscimento dei commenti nei programmi C. Questi compaiono tra le sequenze /* ed */, ma all'interno, nel commento, si possono usare sia il carattere *, sia il carattere /. Il tentativo di individuare i commenti C con il seguente criterio /\*.*\*/ se applicato al commento /* primo commento */ nessun commento /* secondo commento */ non ha successo, perché identifica l'intera stringa a causa della "bramosia" dell'elemento ".*".
Tuttavia, se un'occorrenza è seguita da un punto interrogativo, questa cessa di essere "bramosa", e identifica il numero minimo di testi permessi. Pertanto il criterio /\*.*?\*/ si comporta correttamente con i commenti C. Il significato delle varie occorrenze non è stato cambiato, si è soltanto modificato il numero delle occorrenze da riconoscere. Attenzione a non confondere questo uso del punto interrogativo con il suo proprio significato. Dati i due utilizzi del ?, può anche capitare di averli entrambi come in \d??\d che, preferibilmente, identifica una cifra, ma può riconoscerne due se questa è l'unica via per soddisfare il riconoscimento dell'intero criterio.
Se si attiva l'opzione PCRE_UNGREEDY (un'opzione disponibile anche in Perl), per default le occorrenze non sono "bramose", ma ogni singola occorrenza può essere resa "bramosa" se seguita dal punto interrogativo. In altre parole si è invertito il normale comportamento.
Quando si indica un numero minimo di occorrenze maggiore di 1, per una sotto-regola posta tra parentesi, oppure si indica un numero massimo di occorrenze, la fase di compila richiede più spazio in proporzione ai valori minimo e massimo.
Se un criterio inizia con .* oppure .{0,} e si è attivata l'opzione PCRE_DOTALL (equivalente al /s di Perl), permettendo al . di identificare il carattere di "a capo", si dice che il criterio è implicitamente ancorato, perché qualsiasi elemento che segue sarà confrontato con ciascun carattere della stringa oggetto della ricerca, e pertanto non vi è nessuna posizione, a parte la prima, da cui ripartire per ritentare il riconoscimento dell'intero criterio. PCRE tratta tale criterio come se fosse preceduto dalla sequenza \A. Nei casi in cui è noto a priori che la stringa oggetto di ricerca non contiene caratteri di "a capo", vale la pena di attivare l'opzione PCRE_DOTALL se il criterio di ricerca inizia con ".*", per ottenere questa ottimizzazione, oppure, in alternativa, usare "^" per indicare in modo esplicito un ancoraggio.
Quando si ripete una sotto-regola di cattura, il testo estrapolato è la parte identificata dall'iterazione finale. Ad esempio se il criterio (tweedle[dume]{3}\s*)+ viene applicato al testo "tweedledum tweedledee", il testo estrapolato sarà "tweedledee". Tuttavia se vi sono delle sotto-regole annidate, il testo catturato può essere determinato dalle iterazioni precedenti. Ad esempio nel criterio /(a|(b))+/ applicato a "aba", la seconda stringa catturata è "b".
Esternamente ad una classe di caratteri, un backslah (\) seguito da una o più cifre maggiori di 0 è un riferimento all'indietro verso testi catturati precedentemente (ad esempio alla sinistra rispetto a dove ci si trova), conteggiati tramite il numero delle parentesi chiuse precedenti.
Tuttavia, se il numero che segue il backslash (\) è un valore inferiore a 10, si assume che si tratti sempre di un riferimento all'indietro, e pertanto viene generato un errore se nel criterio non vi sono almeno altrettante parentesi chiuse di sotto-regole di cattura. In altre parole per i numeri inferiori a 10 non è necessario che il numero parentesi precedenti (a sinistra) alla sotto-regola sia pari o maggiore al numero indicato. Vedere la sezione relativa al backslash per informazioni su come gestire le cifre seguenti il backslash.
Un riferimento all'indietro identifica ciò che è già stato catturato dalla sotto-regola, e non ciò che la sotto-regola stessa possa riconoscere. Ad esempio il criterio (sens|respons)e and \1ibility può riconoscere "sense and sensibility" oppure "response and responsibility", ma non il testo "sense and responsibility". Se al momento del riferimento all'indietro, è attiva la distinzione tra lettere maiuscole e minuscole, il formato della lettera diventa rilevante. Ad esempio, ((?i)rah)\s+\1 può identificare "rah rah" e "RAH RAH", ma non "RAH rah", anche se la sotto-regola originale eseguiva dei riconoscimenti a prescindere dalle lettere maiuscole e minuscole.
Nella medesima sotto-regola si possono avere più di un riferimento all'indietro. Se una sotto-regola non viene utilizzata in un particolare riconoscimento, un riferimento a questa ha sempre esito negativo. Ad esempio il criterio (a|(bc))\2 non avrà mai successo se l'identificazione della stringa inizia con "a" e non con "bc". Dato che sono possibili fino a 99 riferimenti all'indietro, tutte le cifre che seguono un backslash (\) sono considerate come parte di un potenziale numero di riferimento. Se il criterio continua con altri caratteri numerici, occorre stabilire un carattere per delimitare il numero del riferimento. Se si attiva l'opzione PCRE_EXTENDED questo carattere può essere lo spazio. Altrimenti si può usare un commento vuoto.
Un riferimento all'indietro non ha successo se viene inserito in una sotto regola prima che sia applicata. Con questo si intende, ad esempio, che (a\1) non avrà mai successo, ma, nel caso di una sottoregola ripetuta, si avrà un riscontro positivo. Ad esempio (a|b\1)+ identificherà qualsiasi numero di "a", ma anche "aba" oppure "ababaa" eccetera. In pratica a ciascuna iterazione della sotto-regola il riferimento andrà a sostituire la stringa riconosciuta tramite la sotto-regola dell'iterazione precedente. Affinchè il tutto funzioni, è necessario che la prima iterazione sia identificata senza l'ausilio del riferimento "all'indietro". Ciò può essere ottenuto o usando casi alternativi, come nell'esempio precedente, o usando le occorrenze indicando come numero minimo di occorrenze il valore zero.
L'asserzione è un test basato su un carattere, che può precedere o seguire l'attuale punto di riconoscimento, e non consuma alcun carattere. Le semplici asserzioni quali \b, \B, \A, \Z, \z, ^ e $ sono state descritte precedentemente. Asserzioni più complesse possono essere strutturate come delle sotto-regole. Se ne hanno di due tipologie: quelle che "guardano avanti" alla posizione attuale nella stringa oggetto del riconoscimento, e quelle che "guardano dietro" la posizione attuale.
Una asserzione definita come sotto-regola esegue il riconoscimento nel modo usuale, ma tale riconoscimento non sposta la posizione attuale nella stringa. Le asserzioni che "guardano avanti" cominciano per "(?=", se sono positive, per "(?!", se sono asserzioni negative. Ad esempio \w+(?=;) riconosce una parola seguita da ";", ma non include il punto e virgola nel riconoscimento, mentre foo(?!bar) identifica qualsiasi occorrenza di "foo" che non sia seguita da "bar". Attenzione che il criterio, apparentemente simile, (?!foo)bar non riconosce alcuna occorrenza di "bar" se questa è preceduta da qualsiasi testo che non sia "foo"; infatti l'espressione riconosce qualsiasi occorrenza di "bar", poiché l'asserzione (?!foo) è sempre TRUE quando i tre caratteri successivi sono "bar". Pertanto è necessario una asserzione che "guarda" all'indietro per ottenere effetto desiderato.
Le asserzioni che "guardano" indietro positive iniziano con "(?<=", e con "(?<!" le negative. Ad esempio: (?<!foo)bar riconosce una occorrenza di "bar" che non sia preceduta da "foo". Le asserzioni che "guardano" indietro hanno una limitazione: tutte le stringhe che riconoscono devono avere lunghezza fissa. Mentre, se si hanno casi alternativi, la limitazione della lunghezza fissa non sussiste. Quindi (?<=bullock|donkey) è una asserzione permessa, ma (?<!dogs?|cats?) genera un errore durante la fase di compila. Rami alternativi con lunghezze di stringa differenti sono permessi solo al primo livello dell'asserzione. Questa è da considerarsi una estensione rispetto a Perl 5.005, che richiede a tutte le alternative possibili la medesima lunghezza di stringa. Quindi una asserzione tipo (?<=ab(c|de)) non è permessa, poiché il suo singolo ramo di primo livello può identificare testi di due lunghezze differenti, ma è accettabile se riscritta usando due alternative di primo livello: (?<=abc|abde) L'implementazione di questo tipo di asserzioni consiste, per ciascuna alternativa, di uno spostamento all'indietro temporaneo per la lunghezza fissa necessaria, e ad un tentativo di riconoscimento del testo. Se non ci sono sufficienti caratteri precedenti alla posizione attuale, l'asserzione è destinata a fallire. L'uso accoppiato delle asserzioni che "guardano" indietro con sotto-regole a riconoscimento singolo può essere utile per identificare la fine dei testi; un esempio è illustrato al termine della sezione sulle sotto-regole a riconoscimento singolo.
Diverse asserzioni (di qualsiasi tipologia) possono essere utilizzate in modo consecutivo. Ad esempio: (?<=\d{3})(?<!999)foo riconosce "foo" preceduto da tre cifre che non siano "999". Occorre rilevare che ciascuna asserzione viene applicata singolarmente sul medesimo punto nella stringa oggetto di riconoscimento. Nell'esempio precedente per prima cosa si verifica che i tre caratteri precedenti siano cifre, quindi che non siamo "999". Questo esempio non identifica il testo se "foo" è preceduto da sei caratteri di cui i primi tre siano cifre e i secondi tre non siano "999". In pratica il testo "123abcfoo" non viene riconosciuto. Un criterio per riconoscere tale stringa può essere: (?<=\d{3}...)(?<!999)foo
In questo caso la prima asserzione controlla i primi sei caratteri verificando che i primi tre siano cifre, mentre la seconda asserzione verifica che i secondi tre caratteri non siano "999".
Le asserzioni possono essere annidate in qualsiasi combinazione. Il seguente esempio (?<=(?<!foo)bar)baz identifica il testo "baz" se è preceduto da "bar" il quale non deve essere preceduto da "foo", mentre (?<=\d{3}...(?<!999))foo è un'altro criterio che riconosce "foo" preceduto da tre cifre e da tre caratteri che non siano "999".
Le asserzioni definite come sotto-regole non catturano parte del testo e non possono essere ripetute (non avrebbe senso ripetere il medesimo riconoscimento sul medesimo testo). Se una di queste asserzioni contiene una sotto-regola di cattura questa viene conteggiata ai fini della numerazione delle regole di cattura. Tuttavia il testo viene effettivamente catturato solo nelle asserzioni positive, dato che non avrebbe senso farlo in quelle negative.
Le asserzioni possono essere composte fino ad un massimo di 200 sotto-regole. subpatterns.
Con l'indicazione del numero minimo e massimo di ripetizioni, il fallimento del riconoscimento della parte successiva del testo causa una ripetizione dell'identificazione con un numero di occorrenze diverse per verificare se in questa situazione anche il resto del testo viene identificato. In alcune situazioni può essere utile bloccare questo meccanismo, per la cambiata natura del criterio, oppure per fare fallire la ricerca prima di quando potrebbe accadere, oppure quando l'autore sa che non ci sono punti da cui ripartire.
Consideriamo, ad esempio, il criterio \d+foo applicato alla seguente linea 123456bar
Dopo avere identificato le 6 cifre ed avere mancato nel riconoscimento di "foo", il comportamento normale consiste nel tentare di procedere identificando 5 cifre per l'elemento \d+, quindi tentare con 4 e così via, prima di fallire definitivamente. Le sotto-regole a riconoscimento singolo permettono di specificare che, una volta riconosciuta una porzione della regola, questa non debba essere più considerata, in maniera tale da abortire immediatamente il riconoscimento se non si ha successo nell'identificare la parte restante del criterio. L'espressione per definire questo tipo di sotto-regola richiede un'altro tipologia di utilizzo speciale delle parentesi. Infatti iniziano con (?> come nell'esempio seguente: (?>\d+)bar
Questa tipologia di parentesi "inchioda" la parte di criterio una volta che avviene il riconoscimento, e, quindi, un fallimento successivo impedisce la ri-elaborazione di questo segmento. Tuttavia, occorre notare che gli elementi precedenti a questo si comportano in modo normale, e pertanto la ri-elaborazione, pur non toccando questo elemento, passa ai precedenti.
Una descrizione alternativa di questa tipologia di sotto-regola potrebbe essere che questo criterio identifica un testo come avrebbe fatto un singolo criterio se fosse stato ancorato alla posizione corrente.
Le sotto-regole a riconoscimento singolo non compiono la cattura del testo identificato. I casi semplici illustrati in precedenza possono essere considerati come una estremizzazione della ripetizione che porta ad inglobare tutto ciò che può. Pertanto, da una parte \d+ e \d+? sono sequenze che si adattano a riconoscere il numero corretto di cifre affinchè la ricerca abbia successo, dall'altra la sequenza (?>\d+) riconosce soltanto una sequenza di cifre.
Ovviamente queste costruzioni possono contenere diverse sotto-regole sia complesse, sia annidate.
Le sotto-regole a riconoscimento singolo possono essere usate congiuntamente alle asserzioni che guardano indietro, per definire una regola efficiente per riconoscere la fine della stringa. Ad esempio si consideri questo semplice criterio: abcd$ quando viene applicato ad un lungo testo può non avere successo. Questo perché il riconoscimento procede da sinistra verso destra, quindi PCRE prima cerca la "a", e poi cerca di riconoscere la parte restante del criterio. Se si modifica il criterio nel seguente modo ^.*abcd$ allora la sequenza iniziale .* in prima battuta identificherà tutto il testo, ma quando fallisce (poiché non vi sono più "a"), la ricerca tornerà indietro di uno (quindi tutto il testo tranne l'ultimo carattere), quindi, se continua non esserci la "a", si torna indietro di due, e così via. Continuando a tornare indietro alla ricerca della "a" si percorre tutto il testo da destra a sinistra, senza ottenere nulla di valido. Tuttavia se si riscrive il criterio come: ^(?>.*)(?<=abcd) non si attiva più lo scorrimento verso sinistra per .* , ma viene costretto a riconoscere tutto il testo (esito del primo tentativo). La asserzione successiva, esegue una verifica sulle ultime 4 lettere.Se fallisce, ciò avviene immediatamente, provocando un impatto sensibile nei tempi di elaborazione con testi molto lunghi.
Quando un criterio di riconoscimento contiene un elemento ripetuto senza limite all'interno di una sotto-regola che anch'essa possa ripetuta illimitatamente, l'uso delle sotto-regole a riconoscimento singolo è l'unico mezzo per evitare che certi mancati riconoscimenti richiedano molto tempo per essere rilevati. Ad esempio il criterio (\D+|<\d+>)*[!?] riconosce un numero indefinito di frammenti di testo contenenti a loro volta numeri o caratteri non numerici racchiusi tra <>, seguiti dai caratteri ! o ?. Quando il riconoscimento ha successo l'esecuzione è rapida, ma quando viene applicato al testo aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa richiede molto tempo prima di evidenziare l'errore. Questo accade perché la stringa può essere suddivisa tra i due elementi ripetuti in un elevato numero di modi che debbono essere verificati. Nell'esempio si usa [!?] piuttosto che un singolo carattere alla fine, questo perché sia Perl sia PCRE hanno una ottimizzazione che permette un veloce riconoscimento dell'errore se si usa un solo carattere. Infatti memorizzano l'ultimo carattere singolo richiesto per un riconoscimento, e, se non lo trovano nel testo, falliscono subito. Se il criterio viene modificato in ((?>\D+)|<\d+>)*[!?] le sequenze di caratteri non numerici non possono essere interrotte e pertanto il mancato riconoscimento viene rilevato più velocemente.
E' possibile forzare il processo di riconoscimento a obbedire alle sotto-regole in modo condizionato, oppure a scegliere tra due alternative in base al risultato di una asserzione, o piuttosto se la sotto-regola di cattura precedente ha riconosciuto il proprio testo. I due metodi possibili per esprimere una sotto-regola condizionale sono:
(?(condizione)yes-pattern)
(?(condizione)yes-pattern|no-pattern)
Se la condizione è soddisfatta, si usa la regola indicata in yes-pattern, altrimenti si applica il no-pattern (qualora sia specificato). Se nella sotto-regola vi sono più di due alternative, PCRE segnala un errore in fase di compila.
Vi sono due tipi di condizioni. Se il testo tra le parentesi consiste in una sequenza di cifre, allora la condizione è soddisfatta se la sotto-regola di cattura di quel numero è stata precedentemente riconosciuta. Si consideri il seguente criterio contenente degli spazi non significativi per renderlo più leggibile (si assuma che sia attiva l'opzione PCRE_EXTENDED) e lo si divida in tre parti per praticità di discussione: ( \( )? [^()]+ (?(1) \) )
La prima parte riconosce una parentesi aperta opzionale, e, se è presente, indica quello come primo segmento di stringa catturato. La seconda parte riconosce uno o più caratteri che non siano parentesi. Infine la terza parte è una sotto-regola condizionale che verifica se la prima parentesi è stata identifica o meno. Se accade, come nel caso in cui il testo inizi con una parentesi aperta, la condizione è TRUE, e quindi viene eseguito il ramo yes-pattern, richiedendo, conseguentemente, la parentesi chiusa. Diversamente, poiché non è specificato ramo no-pattern, non si esegue nessun altro riconoscimento. In altre parole questo criterio identifica un testo che possa essere racchiuso tra parentesi opzionali.
Se la condizione non è una sequenza di cifre, deve essere una asserzione. Questa può essere sia una asserzione che guarda avanti, sia una asserzione cha guarda indietro, sia positiva sia negativa. Si consideri il seguente criterio, ancora una volta contenente spazi non significativi, e con due alternative nella seconda linea:
(?(?=[^a-z]*[a-z])
\d{2}-[a-z]{3}-\d{2} | \d{2}-\d{2}-\d{2} )
La condizione è una asserzione che guarda avanti positiva, la quale identifica una sequenza opzionale di caratteri non alfabetici seguiti da una lettera. In altre parole, si testa la presenza di almeno una lettera nel testo. Se la lettera viene trovata si applica il primo criterio per il riconoscimento del testo, altrimenti viene applicato il secondo criterio. Questo criterio riconosce stringhe in due formati dd-aaa-dd oppure dd-dd-dd, dove aaa sono lettere e dd sono numeri.
La sequenza (?# indica l'inizio di un commento che si conclude con la successiva parentesi chiusa. Parentesi annidate non sono permesse. I caratteri che fanno parte di un commento non giocano alcun ruolo nella fase di riconoscimento.
Se viene attivata l'opzione PCRE_EXTENDED, un carattere # privo della sequenza di escape (\) all'esterno di una classe di caratteri apre un commento che continua fino al carattere di "a capo".
Si consideri il caso in cui si debba riconoscere una stringa tra parentesi, si supponga inoltre di dovere ammettere un numero arbitrario di parentesi annidate. Senza l'uso della ricorsione, il miglior metodo consiste nel preparare un criterio che identifichi un numero finito di parentesi annidate. Però, in questo modo non si gestisce un numero arbitrario si parentesi annidate. Nella versione 5.6 di Perl è stata introdotta, a livello sperimentale, la possibilità per i criteri di riconoscimento di essere ricorsivi. Allo scopo è stata definita la sequenza speciale (?R). Il criterio illustrato di seguito risolve il problema delle parentesi (si assume che l'opzione PCRE_EXTENDED sia attivata in modo da ignorare gli spazi): \( ( (?>[^()]+) | (?R) )* \)
In principio si identifica la parentesi di apertura. Quindi si cerca un numero indefinito di stringhe che possano essere composte da caratteri che non siano parentesi, oppure che siano riconosciute ricorsivamente dal criterio (ad esempio una stringa correttamente tra parentesi). Infine si cerca la parentesi di chiusura.
In questo particolare esempio si hanno arbitrarie ripetizioni annidate, e quindi l'uso delle sotto-regole a riconoscimento singolo per il riconoscimento della stringa priva di parentesi è particolarmente utile se il criterio viene applicato ad un testo non riconoscibile. Ad esempio, applicando il criterio a (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa() si ottiene un esito di mancato riconoscimento rapidamente. Se, al contrario, non si fosse usato il criterio a riconoscimento singolo, sarebbe occorso molto tempo per avere un esito dato che vi sono moltissimi modi in cui i caratteri di ripetizione + e * possono essere applicati al testo, richiedendo, pertanto, la verifica di tutte le combinazioni prima di fornire l'esito negativo.
Il valori restituiti da una sotto-regola di cattura sono quelli ottenuti dal livello di ricorsione più esterno. Se il criterio illustrato in precedenza venisse applicato al testo (ab(cd)ef) Il valore ottenuto sarebbe "ef", che rappresenta l'ultimo valore catturato al livello più alto. Se si aggiungono altre parentesi al criterio, ottenendo \( ( ( (?>[^()]+) | (?R) )* ) \) allora il testo ottenuto sarebbe "ab(cd)ef", cioè il valore delle parentesi di livello più alto. Se nel criterio vi sono più di 15 sotto-regole di cattura, PCRE ha necessità di ottenere maggiore memoria per archiviare le informazioni durante la ricorsione. Questa memoria è ottenuta utilizzando pcre_malloc, al termine verrà liberata con pcre_free. Se non può essere ottenuta ulteriore memoria, si ha il salvataggio delle informazioni dei primi 15 testi catturati, dato che non vi è modo di restituire un messaggio di memoria insufficiente dalla ricorsione.
Certi elementi utilizzati per i criteri di riconoscimento sono più efficienti di altri. E' più efficiente usare le classi di caratteri come [aeiou] piuttosto che un gruppo di alternative come (a|e|i|o|u). In generale la costruzione più semplice per ottenere un dato scopo è la più efficiente. Nel libro di Jeffrey Friedl sono illustrate varie tecniche sull'ottimizzazione delle espressioni regolari.
Quando un criterio comincia con .* ed è attiva l'opzione PCRE_DOTALL, il criterio è implicitamente ancorato da PCRE, dato che può rico- noscere solo l'inizio della stringa. Tuttavia, se non è attivo PCRE_DOTALL, PCRE non può fare questa ottimizzazione, perché il meta-carattere . non ri- conosce più il carattere di "a capo", e quindi se la stringa contiene dei caratteri di "a capo", il riconoscimento può par- tire dal carattere immediatamente successivo ad uno di questi e non dall'inizio. Ad esempio il criterio (.*) second può eseguire un riconoscimento nel testo "first\nand second" (dove \n indica il carattere "a capo") ottenendo "and" come prima stringa catturata. perché ciò accada è necessario che PCRE possa iniziare il riconoscimento dopo ogni "a capo".
Se si deve usare un simile criterio in stringhe che non conten- gono caratteri di "a capo", le performance migliori si possono ottenere abilitando PCRE_DOTALL, oppure iniziando il criterio con ^.* in modo da richiedere un ancoraggio esplicito. Così si risparmia a PCRE di scandirsi il testo alla ricerca di un "a capo" da cui ripartire per la ri- cerca.
Occorre prestare attenzione ai criteri che contengono ripeti- zioni indefinite annidate. Possono richiedere molto tempo se applicati a stringhe non riconoscibili. Si consideri il fram- mento (a+)*
Questo può riconoscere "aaaa" in 33 modi differenti, e questo numero può crescere molto rapidamente se la stringa da ricono- scere è più lunga. (Il carattere di ripetizione * può eseguire riconoscimenti per 0,1,2,3 o 4 ripetizioni, e per ciascuna di esse, tranne lo 0, il carattere di ripetizione + può esegui- re riconoscimenti per diversi numeri di volte). Quindi se la parte successiva del criterio è tale da non permettere il com- pletamento del riconoscimento, PCRE, per principio, ugualmente tenta tutte le possibili variazioni, richiedendo diverso tempo.
Una ottimizzazione riesce a catturare qualche caso semplice come in (a+)*b dove si indica che seguirà un carattere alfanumerico. PCRE, prima di imbarcarsi nella procedura standard di riconoscimen- to, verifica se nel testo vi è la lettera "b", e se non c'è restituisce immediatamente un esito negativo. Tuttavia se non viene indicata una lettera seguente questa ottimizzazione non può essere utilizzata. Se ne può notare la differenza analiz- zando il comportamento del criterio (a+)*\d rispetto al precedente. Il primo, utilizzato con una stringa composta da "a", fallisce immediatamente, l'ultimo richiede un tempo apprezzabile, soprattutto se applicato a stringhe con più di 20 caratteri.
(PHP 4, PHP 5)
preg_grep -- Restituisce una matrice degli elementi riconosciuti tramite le espressioni regolariLa funzione preg_grep() restituisce una matrice composta dagli elementi dell'array testo che soddisfano i criteri impostati nel parametro espressione_regolare.
Il parametro flags può assumere i seguenti valori:
Con questo valore, la funzione preg_grep()gli elementi della matrice di input che non soddisfano la data espressione_regolare. Questo valore è disponibile a partire da PHP 4.2.0.
A partire dalla versione 4.0.4 di PHP, la matrice risultante dalla funzione preg_grep(), viene indicizzata utilizzando le chiavi dalla matrice di input. Se non si desidera un comportamento simile, applicare la funzione array_values() alla matrice ottenuta da questa funzione per ricalcolare gli indici.
(PHP 3 >= 3.0.9, PHP 4, PHP 5)
preg_match_all -- Esegue un riconoscimento globale con le espressioni regolariLa funzione ricerca tutte le espressioni regolari passate nel parametro espressione_regolare all'interno della stringa testo. I testi riconosciuti sono posti all'interno della matrice TestiRiconosciuti, nell'ordine specificato da flags.
Dopo avere riconosciuto il primo segmento di testo, le ricerche seguenti saranno effettuate a partire dall'ultima ricerca specificata.
Il parametro flags può essere la combinazione dei seguenti flag (da notare che non ha senso utilizzare PREG_PATTERN_ORDER in unione a PREG_SET_ORDER):
I testi riconosciuti saranno organizzati in modo tale da avere in $TestiRiconosciuti[0] la matrice di tutti i testi riconosciuti, in $TestiRiconosciuti[1] la matrice di tutti i testi che soddisfino il primo criterio di riconoscimento posto tra parentesi tonde, in $TestiRiconosciuti[2] si avranno i testi che soddisfino il secondo criterio e cosi via.
<?php preg_match_all("|<[^>]+>(.*)</[^>]+>|U", "<b>example: </b><div align=left>this is a test</div>", $out, PREG_PATTERN_ORDER); echo $out[0][0].", ".$out[0][1]."\n"; echo $out[1][0].", ".$out[1][1]."\n"; ?> |
Questo esempio produrrà:
<b>example: </b>, <div align=left>this is a test</div> example: , this is a test |
Nell'esempio, $out[0] contiene la matrice di tutte le stringhe che soddisfano i criteri impostati, $out[1] contiene la matrice dei testi delimitati dai tag.
Usando questo parametro come ordine dei riconoscimenti, si avrà in $TestiRiconosciuti[0] una matrice con il primo set di testi riconosciuti, in $TestiRiconosciuti[1], la matrice con il secondo set di testi riconosciuti e così via.
<?php preg_match_all("|<[^>]+>(.*)</[^>]+>|U", "<b>example: </b><div align=\"left\">this is a test</div>", $out, PREG_SET_ORDER); echo $out[0][0].", ".$out[0][1]."\n"; echo $out[1][0].", ".$out[1][1]."\n"; ?> |
Questo esempio visualizzerà:
<b>example: </b>, example: <div align="left">this is a test</div>, this is a test |
In questo esempio $out[0] è la matrice del primo set di testi riconosciuti. Nel dettaglio $out[0][0] conterrà il testo che incrocia l'intero criterio impostato, $out[0][1] conterrà il testo riconosciuto tramite il prima regola di riconoscimento presente nel criterio globale. Analogo discorso si può fare per $out[1]. In questo caso il ragionamento verrà svolto su un secondo segmento della stringa che soddisfi le condizioni poste dal criterio di riconoscimento.
Se viene impostato questo flag, per ogni testo riconosciuto viene restituito l'offset della stringa. Occorre notare che questo cambia il tipo di valore restituito nell'array, infatti ogni elemento è, a sua volta, un'array composto dalla stringa riconosciuta, all'indice 0, e dall'offset della stringa nell'indice 1. Questa costante è disponibile a partire dalla versione 4.3.0 di PHP.
Qualora non si specifichi il parametro flags, si assume per default il valore PREG_PATTERN_ORDER.
Normalemente la ricerca parte dall'inizio della stringa oggetto di ricerca. Con il parametro opzionale offset si può specificare da dove cominciare la ricerca. Equivale a passare substr()($testo, $offset) alla funzione preg_match() al posto del parametro testo. Il parametro offset è disponibile a partire dalla versione 4.3.3 di PHP.
La funzione restituisce il numero dei riconoscimenti completi svolti (che possono essere zero), oppure FALSE se si verificano degli errori.
Esempio 2. Ricerca di tag HTML
Questo esempio visualizzerà:
|
Vedere anche preg_match(), preg_replace() e preg_split().
Esegue un riconoscimento nel parametro testo utilizzando l'espressione regolare indicata in criterio.
Se viene fornito il terzo parametro, testi_riconosciuti, questo verrà valorizzato con i risultati della ricerca. In dettaglio $testi_riconosciuti[0] conterrà il testo che si incrocia con l'intero criterio di ricerca, $testi_riconosciuti[1] conterrà il testo che soddisfa il primo criterio posto tra parentesi, $testi_riconosciuti[2] il secondo e così via.
Il parametro flags può assumere i seguenti valori:
Se viene impostato questo flag, per ogni testo riconosciuto viene restituito l'offset della stringa. Occorre notare che questo cambia il tipo di valore restituito nell'array, infatti ogni elemento è, a sua volta, un'array composto dalla stringa riconosciuta, all'indice 0, e dall'offset della stringa nell'indice 1. Questa costante è disponibile a partire dalla versione 4.3.0 di PHP.
Normalemente la ricerca parte dall'inizio della stringa oggetto di ricerca. Con il parametro opzionale offset si può specificare da dove cominciare la ricerca. Equivale a passare substr()($testo, $offset) alla funzione preg_match() al posto del parametro testo. Il parametro offset è disponibile a partire dalla versione 4.3.3 di PHP.
La funzione preg_match() restituisce il numero di volte in cui è avvenuto il riconoscimento del criterio. Questo può essere 0 (nessun riconoscimento) oppure 1 se preg_match() si ferma dopo il primo riconoscimento. In condizioni normali, preg_match_all() continua il riconoscimento fino alla fine del parametro testo. preg_match() restituirà FALSE se si verifica un errore.
Suggerimento: Non utilizzare la funzione preg_match() se si desidera controllare se una stringa è contenuta in un'altra. Piuttosto utilizzare strpos() oppure strstr() che sono più veloci.
Esempio 2. Cerca la parola "web"
|
Esempio 3. Estrapolazione del dominio da un URL
L'esempio visualizzerà:
|
Vedere anche preg_match_all(), preg_replace() e preg_split().
(PHP 3 >= 3.0.9, PHP 4, PHP 5)
preg_quote -- Inserisce il carattere di escape nei caratteri delle espressioni regolariLa funzione preg_quote() inserisce il carattere di escape (\) davanti ad ogni carattere presente in stringa che sia parte della sintassi di una espressione regolare. Questa funzione è utile nei casi in cui si generino, durante l'esecuzione, delle stringhe da usare come criteri di riconoscimento, e queste possano contenere dei caratteri speciali per le espressioni regolari.
Se viene specificato un carattere come parametro delimitatore, anche a questo sarà anteposto il carattere di escape (\). Ciò è particolarmente utile per porre il carattere di escape nei delimitatori richiesti dalle funzioni PCRE. Il carattere di delimitazione più comunemente utilizzato è /.
I caratteri speciali per le espressioni regolari sono: . \\ + * ? [ ^ ] $ ( ) { } = ! < > | :
Esempio 2. Esempio di come rendere in corsivo una qualsiasi parola di un testo
|
Nota: Questa funzione è binary-safe (gestisce correttamente i file binari)
(PHP 4 >= 4.0.5, PHP 5)
preg_replace_callback -- Esegue ricerche e sostituzioni con espressioni regolari usando il callbackFondamentalmente questa funzione si comporta come preg_replace(), eccetto che per la presenza del callback. Con quest'ultimo parametro si indica una funzione da richiamare a cui verrà passata una matrice con i testi riconosciuti in testo. La funzione di callback dovrebbe restituire la stringa da sostituire.
Esempio 1. Esempio dell'uso di preg_replace_callback()
|
Spesso si ha la necessità di richiamare la funzione callback soltanto in un unico posto. In questo caso si può utilizzare create_function() per dichiarare una funzione anonima come callback per preg_replace_callback().In questo modo si hanno tutte le informazioni per la chiamata in un unico posto e non si disperde con funzioni di callback non utilizzate altrove.
Esempio 2. preg_replace_callback() e create_function()
|
Vedere anche preg_replace() create_function(), e information about the callback type.
(PHP 3 >= 3.0.9, PHP 4, PHP 5)
preg_replace -- Esegue una ricerca ed una sostituzione con le espressioni regolariLa funzione ricerca in testo i criteri impostati in espressione_regolare. Se riconosce dei testi, li sostituisce con sostituto. Se si specifica limite, verranno sostituiti solamente limite testi riconosciuti; se viene omesso, oppure impostato a -1, verranno sostituiti tutti i testi riconosciuti.
Il parametro sostituto può contenere riferimenti nella forma di \\n, oppure, a partire dalla versione 4.0.4 di PHP, $n , con la preferenza per la seconda sintassi. Questo tipo di riferimento verrà sostituito dal testo che soddisfa l'n -esimo criterio presente in espressione_regolare . Sono ammessi numeri compresi tra 0 e 99 inclusi. Il valore 0 (\\0 oppure $0) si riferisce al testo riconosciuto tramite tutta l'espressione regolare passata. Nel conteggio dei criteri di riconoscimento presenti, sono contate le parentesi aperte da sinistra verso destra partendo da 1.
Quando si lavora con un criterio di sostituzione in cui un riferimento all'indietro è immediatamente seguito da un'altro numero (ad esempio un numero che segue immediatamente il criterio riconosciuto), non si possono utilizzare le solite notazioni, \\1, per i riferimenti all'indietro. Ad esempio, il testo \\11 confonderebbe preg_replace() poichè non saprebbe se si desidera il riferimento all'indietro \\1 seguito dal numero 1, oppure se è desiderato il riferimento \\11 seguito da niente. In questi casi la soluzione consiste nell'uso di \${1}1. In questo modo si crea un riferimento all'indietro $1 isolato dal numero 1.
Se verranno riconosciuti dei testi, la funzione restituisce la nuova versione di testo, altrimenti il parametro sarà restituito inalterato.
Ogni parametro passato alla funzione preg_replace(), (eccetto limite) può essere una matrice ad una dimensione. Quando si utilizzano matrici con espressione_regolare e sostituto, le chiavi sono processate nell'ordine con cui appaiono nella matrice. Questo non è necessariamente l'ordine numerico dell'indice. Se si utilizzano degli indici per identificare quale espressione_regolare debba essere sostituita da sostituto, occorre eseguire la funzione ksort() su ciascuna matrice prima di eseguire preg_replace().
Esempio 2. Uso di matrici indicizzate con preg_replace()
Output:
Utilizzando ksort su entrambe le matrici otteniamo cio che vogliamo.
Output :
|
Se il campo testo è una matrice, la ricerca e la sostituzione sarà eseguita su ogni elemento della matrice, e conseguentemente la funzione restituirà una matrice.
Se espressione_regolare ed sostituto sono entrambi delle matrici, la funzione preg_replace() utilizza gli elementi di ciascuna matrice per la ricerca e la sostituzione delle stringhe in testo. Nel caso in cui la matrice passata in sostituto abbia meno elementi che espressione_regolare, la funzione utilizzerà una stringa vuota per compensare gli elementi mancanti nella fase di sostituzione. Se, invece, espressione_regolare è una matrice, mentre il campo sostituto è una stringa, quest'ultima sarà usata come valore da sostituire ad ogni testo riconosciuto. Un discorso contrario non ha senso.
Il modificatore /e, permette alla funzione di considerare il testo posto in sostituto come codice PHP dopo aver valorizzato gli opportuni riferimenti. Suggerimento: accertarsi che sostituto sia del codice PHP valido, altrimenti si ottiene un errore di parsing alla linea della funzione preg_replace().
Esempio 5. Esempio di conversione di codice HTML in testo
|
Nota: Il parametro limite è stato aggiunto successivamente alla versione 4.0.1pl2 di PHP.
Vedere anche preg_match(), preg_match_all() e preg_split().
(PHP 3 >= 3.0.9, PHP 4, PHP 5)
preg_split -- Suddivisione di una stringa tramite le espressioni regolariLa funzione restituisce una matrice di parti di testo suddivisi tramite i criteri indicati da espressione_regolare.
Se viene specificato il parametro limite, la funzione restituisce tante parti del testo iniziale quante sono indicate da limite. Può essere usato il valore -1 per indicare "nessun limite". Ciò torna utile in abbinamento all'uso del parametro flags.
Il parametro flags può essere la combinazione dei seguenti flag (la combinazione di più flag avviene con l'operatore |):
Specificando questo flag, la funzione preg_split() restituisce spezzoni di testo non vuoti.
Con l'uso di questo flag, la funzione cattura e restituisce eventuali espressioni poste tra parentesi nel parametro espressione_regolare. Questo flag è stato aggiunto nella versione 4.0.5.
Se viene impostato questo flag, per ogni testo riconosciuto viene restituito l'offset della stringa. Occorre notare che questo cambia il tipo di valore restituito nell'array; infatti ogni elemento è, a sua volta, un'array composto dalla stringa riconosciuta, all'indice 0, e dall'offset della stringa nell'indice 1. Questa costante è disponibile a partire dalla versione 4.3.0 di PHP.
Esempio 3. Suddivisione di una stringa in testi riconosciuti con i relativi offset.
visualizzerà
|
Nota: Il parametro flags è stato aggiunto nella versione 4 Beta 3 di PHP.
Vedere anche spliti(), split(), implode(), preg_match(), preg_match_all() e preg_replace().
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 pdfdoc as its first parameter. Please see the examples below for more information.
Nota: If you're interested in alternative free PDF generators that do not utilize external PDF libraries, see this related FAQ.
Nota: This extension has been moved to PECL as of PHP 4.3.9.
PDFlib is available for download at http://www.pdflib.com/products/pdflib/index.html, but requires that you purchase a license for commercial use. The JPEG and TIFF libraries are required to compile this extension.
Any version of PHP 4 after March 9, 2000 does not support versions of PDFlib older than 3.0.
PDFlib 3.0 or greater is supported by PHP 3.0.19 and later.
This PECL extension is not bundled with PHP. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: http://pecl.php.net/package/pdflib.
To get these functions to work in PHP < 4.3.9, 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.
As of PHP 4.3.9, you must install this extension through PEAR, using the following command: pear install pdflib.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
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.
Tabella 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.
Esempio 1. Creating a PDF document with PDFlib
|
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.)
Esempio 3. 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. Parameters parent and open are optional before PHP 4.3.5 or with PDFlib less than 5.
Esempio 1. pdf_add_bookmark() example
|
Adds a link to a web resource specified by filename. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also pdf_add_locallink().
Add a link annotation to a target within the current PDF file. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
dest is the zoom setting on the destination page, it can be one of retain, fitpage, fitwidth, fitheight or fitbbox.
See also pdf_add_launchlink().
Sets an annotation for the current page. icon is one of comment, insert, note, paragraph, newparagraph, key, or help. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Esempio 1. Adding a note to a PDF document with PDFlib
|
Add a file link annotation (to a PDF target). Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also pdf_add_locallink() and pdf_add_weblink().
Adds an existing image as thumbnail for the current page. Thumbnail images must not be wider or higher than 106 pixels. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also pdf_open_image(), pdf_open_image_file() and pdf_open_memory_image().
Add a weblink annotation to a target url on the Web. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Add a counterclockwise circular arc from alpha to beta degrees with center (x; y) and radius r. Actual drawing of the circle is performed by the next stroke or fill operation.
Esempio 1. pdf_arcn() example
|
See also: pdf_arcn(), pdf_circle(), pdf_stroke(), pdf_fill() and pdf_fill_stroke().
Add a clockwise circular arc from alpha to beta degrees with center (x; y) and radius r. Actual drawing of the circle is performed by the next stroke or fill operation.
Esempio 1. pdf_arcn() example
|
See also: pdf_arc(), pdf_circle(), pdf_stroke(), pdf_fill() and pdf_fillstroke().
Add a file attachment annotation. icon is one of graph, paperclip, pushpin, or tag. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: Only the 'Full' Acrobat software will be able to display these file attachments. All other PDF viewers will either show nothing or display a question mark.
Add a new page to the document. Restituisce TRUE in caso di successo, FALSE in caso di fallimento. The width and height are specified in points, which are 1/72 of an inch.
Tabella 1. Common Page Sizes in Points
name | size |
---|---|
A0 | 2380✗3368 |
A1 | 1684✗2380 |
A2 | 1190✗1684 |
A3 | 842✗1190 |
A4 | 595✗842 |
A5 | 421✗595 |
A6 | 297✗421 |
B5 | 501✗709 |
letter (8.5"✗11") | 612✗792 |
legal (8.5"✗14") | 612✗1008 |
ledger (17"✗11") | 1224✗792 |
11"✗17" | 792✗1224 |
See also pdf_end_page().
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.
See also pdf_end_pattern().
Start a new template definition.
Add a circle with center (x, y) and radius r to the current page. Actual drawing of the circle is performed by the next stroke or fill operation.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Esempio 1. pdf_circle() example
|
See also: pdf_arc(), pdf_arcn(), pdf_curveto(), pdf_stroke(), pdf_fill() and pdf_fill_stroke().
Use the current path as clipping path. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Close an image retrieved with the pdf_open_image() function.
Close the page handle, and free all page-related resources. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Close all open page handles, and close the input PDF document. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also pdf_open_pdi().
Close the generated PDF file, and free all document-related resources. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also pdf_new().
Close the path, fill, and stroke it. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also pdf_closepath() and pdf_closepath_stroke().
Close the path, and stroke it. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also pdf_closepath() and pdf_closepath_fil_stroke().
Close the current path. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also pdf_closepath_stroke() and pdf_closepath_fil_stroke().
Concatenate a matrix to the CTM. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Print text at the next line. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Draw a Bezier curve from the current point, using 3 more control points. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Delete the PDF resource, and free all internal resources. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also pdf_new().
Finish the page. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also pdf_begin_page().
Finish the pattern definition. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also pdf_begin_pattern().
Finish the template definition. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
This function is deprecated, use one of the pdf_stroke(), pdf_clip() or pdf_closepath_fill_stroke() functions instead.
Fill and stroke the path with the current fill and stroke color. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also pdf_setcolor().
Fill the interior of the path with the current fill color. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also pdf_setcolor().
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, a user-defined encoding name or the name of a CMap. Parameter embed is optional before PHP 4.3.5 or with PDFlib less than 5.
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.
Returns the major version number of the PDFlib.
See also pdf_get_minorversion().
Returns the minor version number of the PDFlib.
See also pdf_get_majorversion().
Get the contents of some PDFlib parameter with string type. Parameter modifier is optional before PHP 4.3.5 or with PDFlib less than 5.
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. Parameter modifier is optional before PHP 4.3.5 or with PDFlib less than 5.
Reset all implicit color and graphics state parameters to their defaults. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Draw a line from the current point to (x, y). Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Make a named spot color from the current color. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also pdf_setcolor().
Set the current point to (x, y. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
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 resource, using default error handling and memory management.
See also pdf_close().
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. Parameter filename is optional before PHP 4.3.5 or with PDFlib less than 5. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
The following example shows how to create a pdf document in memory and how to output it correctly.
Esempio 1. Creating a PDF document in memory
|
Open an image file. Supported types are jpeg, tiff, gif, and png. stringparam is either empty, mask, masked, or page. intparam is either 0, the image id of the applied mask, or the page. Parameters stringparam and intparam are optional before PHP 4.3.5 or with PDFlib less than 5.
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 when type is raw, params is only used when type is ccitt.
(PHP 3 >= 3.0.10, PHP 4, PECL)
pdf_open_memory_image -- Opens an image created with PHP's image functionsThe pdf_open_memory_image() function takes an image created with the PHP's image functions and makes it available for the pdf resource. The function returns a pdf image identifier.
See also pdf_close_image() and pdf_place_image().
Prepare a page for later use with pdf_place_image()
Opens an existing PDF document and prepares it for later use.
See also pdf_close_pdi().
Place an image with the lower left corner at (x, y), and scale it. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Place a PDI page with the lower left corner at (x, y), and scale it. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Draw a (width * height) rectangle at lower left (x, y). Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Restore the most recently saved graphics state. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Rotate the coordinate system by phi degrees. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Save the current graphics state. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Scale the coordinate system. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
(PHP 3 >= 3.0.12, PHP 4, PECL)
pdf_set_border_color -- Sets color of border around links and annotationsSet the border color for all kinds of annotations. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Sets the border dash style for all kinds of annotations. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also pdf_setdash().
(PHP 3 >= 3.0.12, PHP 4, PECL)
pdf_set_border_style -- Sets style of border around links and annotationsSets the border style for all kinds of annotations. style is solid or dashed. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
(PHP 3 >= 3.0.6, PHP 4, PECL)
pdf_set_info_author -- Deprecated: Fills the author field of the document(PHP 3 >= 3.0.6, PHP 4, PECL)
pdf_set_info_creator -- Deprecated: Fills the creator field of the document(PHP 3 >= 3.0.6, PHP 4, PECL)
pdf_set_info_keywords -- Deprecated: Fills the keywords field of the document(PHP 3 >= 3.0.6, PHP 4, PECL)
pdf_set_info_subject -- Deprecated: Fills the subject field of the document(PHP 3 >= 3.0.6, PHP 4, PECL)
pdf_set_info_title -- Deprecated: Fills the title field of the documentFill document information field key with value. Restituisce TRUE in caso di successo, FALSE in caso di fallimento. key is one of Subject, Title, Creator, Author, Keywords, or a user-defined key.
Sets some PDFlib parameters with string type. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also pdf_set_value().
Set the text output position specified by x and y. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Set the value of some PDFlib parameter with float type. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also pdf_set_parameter().
Set the current color space and color. Restituisce TRUE in caso di successo, FALSE in caso di fallimento. 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. Parameters c2, c3 and c4 are optional before PHP 4.3.5 or with PDFlib less than 5.
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. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Sets the flatness to a value between 0 and 100 inclusive. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Set the current font in the given size, using a font handle returned by pdf_findfont(). Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also pdf_findfont().
Set the current fill color to a gray value between 0 and 1 inclusive. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: PDFlib V4.0: Deprecated, use pdf_setcolor() instead.
Set the current stroke color to a gray value between 0 and 1 inclusive. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: PDFlib V4.0: Deprecated, use pdf_setcolor() instead.
Set the current fill and stroke color. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: PDFlib V4.0: Deprecated, use pdf_setcolor() instead.
Set the linecap parameter to a value between 0 and 2 inclusive.
Sets the line join parameter to a value between 0 and 2 inclusive. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Sets the current linewidth to width. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Explicitly set the current transformation matrix. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Set the miter limit to a value greater than or equal to 1. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Set the current fill color to the supplied RGB values. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: PDFlib V4.0: Deprecated, use pdf_setcolor() instead.
Set the current stroke color to the supplied RGB values. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: PDFlib V4.0: Deprecated, use pdf_setcolor() instead.
Set the current fill and stroke color to the supplied RGB values. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
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. Parameter feature is optional before PHP 4.3.5 or with PDFlib less than 5.
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 formatting.
Print text in the current font at ( x, y). Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Print text in the current font and size at the current position. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Skew the coordinate system in x and y direction by alpha and beta degrees. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Returns the width of text using the parameters font and size. Please note that font is a font handle returned by pdf_findfont(). Parameters font and size are optional before PHP 4.3.5 or with PDFlib less than 5. If they are not specified, the font set by pdf_setfont() is used.
Nota: Both the font and size parameters must be used together.
See also pdf_setfont() and pdf_findfont().
Stroke the path with the current color and line width, and clear it. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
The PHP Data Objects (PDO) extension defines a lightweight, consistent interface for accessing databases in PHP. Each database driver that implements the PDO interface can expose database-specific features as regular extension functions. Note that you cannot perform any database functions using the PDO extension by itself; you must use a database-specific PDO driver to access a database server.
PDO provides a data-access abstraction layer, which means that, regardless of which database you're using, you use the same functions to issue queries and fetch data. PDO does not provide a database abstraction; it doesn't rewrite SQL or emulate missing features. You should use a full-blown abstraction layer if you need that facility.
PDO ships with PHP 5.1, and is available as a PECL extension for PHP 5.0; PDO requires the new OO features in the core of PHP 5, and so will not run with earlier versions of PHP.
PHP 5.1 and up on Unix systems
If you're running a PHP 5.1 release, PDO is included in the distribution; it will be automatically enabled when you run configure. It is recommended that you build PDO as a shared extension, as this will allow you to take advantage of updates that are made available via PECL. The recommended configure line for building PHP with PDO support should enable zlib support (for the pear installer) as well. You may also need to enable the PDO driver for your database of choice; consult the documentation for database-specific PDO drivers to find out more about that.
./configure --with-zlib --enable-pdo=shared |
After installing PDO as a shared module, you must edit your php.ini file so that the PDO extension will be loaded automatically when PHP runs. You will also need to enable any database specific drivers there too; make sure that they are listed after the pdo.so line, as PDO must be initialized before the database specific extensions can be loaded. If you built the extensions statically, you can skip this step.
extension=pdo.so |
Having PDO as a shared module will allow you to run pear upgrade pdo as new versions of PDO are published, without forcing you to rebuild the whole of PHP. Note that if you do this, you also need to upgrade your database specific PDO drivers at the same time.
PHP 5.0 and up on Unix systems
PDO is available as a PECL extension from http://pecl.php.net/package/pdo. Installation can be performed via the pear tool; this is enabled by default when you configure PHP. You should ensure that PHP was configured --with-zlib in order for pear to be able to handle the compressed package files.
Run the following command to download, build, and install the latest stable version of PDO:
pear install pdo |
If PDO is still in beta (and at the time of writing, it is), you will need to tell the pear tool that it's ok to fetch the beta package. Instead of running the command above, run the following:
pear install pdo-beta |
The pear command automatically installs the PDO module into your PHP extensions directory. To enable the PDO extension on Linux or Unix operating systems, you must add the following line to php.ini:
extension=pdo.so |
For more information about building PECL packages, consult the PECL installation section of the manual.
Windows users running PHP 5.1 and up
PDO and all the major drivers ship with PHP as shared extensions, and simply need to be activated by editing the php.ini file:
extension=php_pdo.dll |
Next, choose the other DB specific DLL files and either use dl() to load them at runtime, or enable them in php.ini below php_pdo.dll. For example:
extension=php_pdo.dll extension=php_pdo_firebird.dll extension=php_pdo_mssql.dll extension=php_pdo_mysql.dll extension=php_pdo_oci.dll extension=php_pdo_oci8.dll extension=php_pdo_odbc.dll extension=php_pdo_pgsql.dll extension=php_pdo_sqlite.dll |
These DLLs should exist in the system's extension_dir.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Per maggiori dettagli sulle costanti PHP_INI_* vedere Appendice G.
Breve descrizione dei parametri di configurazione.
Defines DSN alias. See PDO::__construct for thorough explanation.
The following drivers currently implement the PDO interface:
Driver name | Supported databases |
---|---|
PDO_DBLIB | FreeTDS / Microsoft SQL Server / Sybase |
PDO_FIREBIRD | Firebird/Interbase 6 |
PDO_MYSQL | MySQL 3.x/4.x |
PDO_OCI | Oracle Call Interface |
PDO_ODBC | ODBC v3 (IBM DB2, unixODBC and win32 ODBC) |
PDO_PGSQL | PostgreSQL |
PDO_SQLITE | SQLite 3 and SQLite 2 |
Connections are established by creating instances of the PDO base class. It doesn't matter which driver you want to use; you always use the PDO class name. The constructor accepts parameters for specifying the database source (known as the DSN) and optionally for the username and password (if any).
If there are any connection errors, a PDOException object will be thrown. You may catch the exception if you want to handle the error condition, or you may opt to leave it for an application global exception handler that you set up via set_exception_handler().
Avvertimento |
If your application does not catch the exception thrown from the PDO constructor, the default action taken by the zend engine is to terminate the script and display a back trace. This back trace will likely reveal the full database connection details, including the username and password. It is your responsibility to catch this exception, either explicitly (via a catch statement) or implicitly via set_exception_handler(). |
Upon successful connection to the database, an instance of the PDO class is returned to your script. The connection remains active for the lifetime of that PDO object. To close the connection, you need to destroy the object by ensuring that all remaining references to it are deleted--you do this by assigning NULL to the variable that holds the object. If you don't do this explicitly, PHP will automatically close the connection when your script ends.
Many web applications will benefit from making persistent connections to database servers. Persistent connections are not closed at the end of the script, but are cached and re-used when another script requests a connection using the same credentials. The persistent connection cache allows you to avoid the overhead of establishing a new connection every time a script needs to talk to a database, resulting in a faster web application.
Nota: If you're using the PDO ODBC driver and your ODBC libraries support ODBC Connection Pooling (unixODBC and Windows are two that do; there may be more), then it's recommended that you don't use persistent PDO connections, and instead leave the connection caching to the ODBC Connection Pooling layer. The ODBC Connection Pool is shared with other modules in the process; if PDO is told to cache the connection, then that connection would never be returned to the ODBC connection pool, resulting in additional connections being created to service those other modules.
Now that you're connected via PDO, you should be able to understand how PDO manages transactions before you start issuing queries. If you've never encountered transactions before, they offer 4 major features: Atomicity, Consistency, Isolation and Durability (ACID). In layman's terms, any work carried out in a transaction, even if it is carried out in stages, is guaranteed to be applied to the database safely, and without interference from other connections, when it is committed. Transactional work can also be automatically undone at your request (provided you haven't already committed it), which makes error handling in your scripts easier.
Transactions are typically implemented by "saving-up" your batch of changes to be applied all at once; this has the nice side effect of drastically improving the efficiency of those updates. In other words, transactions can make your scripts faster and potentially more robust (you still need to use them correctly to reap that benefit).
Unfortunately, not every database supports transactions, so PDO needs to run in what is known as "auto-commit" mode when you first open the connection. Auto-commit mode means that every query that you run has its own implicit transaction, if the database supports it, or no transaction if the database doesn't support transactions. If you need a transaction, you must use the PDO::beginTransaction() method to initiate one. If the underlying driver does not support transactions, a PDOException will be thrown (regardless of your error handling settings: this is always a serious error condition). Once you are in a transaction, you may use PDO::commit() or PDO::rollBack() to finish it, depending on the success of the code you run during the transaction.
When the script ends or when a connection is about to be closed, if you have an outstanding transaction, PDO will automatically roll it back. This is a safety measure to help avoid inconsistency in the cases where the script terminates unexpectedly--if you didn't explicitly commit the transaction, then it is assumed that something went awry, so the rollback is performed for the safety of your data.
Avvertimento |
The automatic rollback only happens if you initiate the transaction via PDO::beginTransaction(). If you manually issue a query that begins a transaction PDO has no way of knowing about it and thus cannot roll it back if something bad happens. |
Esempio 5. Executing a batch in a transaction In the following sample, let's assume that we are creating a set of entries for a new employee, who has been assigned an ID number of 23. In addition to entering the basic data for that person, we also need to record their salary. It's pretty simple to make two separate updates, but by enclosing them within the PDO::beginTransaction() and PDO::commit() calls, we are guaranteeing that no one else will be able to see those changes until they are complete. If something goes wrong, the catch block rolls back all changes made since the transaction was started, and then prints out an error message.
|
You're not limited to making updates in a transaction; you can also issue complex queries to extract data, and possibly use that information to build up more updates and queries; while the transaction is active, you are guaranteed that no one else can make changes while you are in the middle of your work. In truth, this isn't 100% correct, but it is a good-enough introduction, if you've never heard of transactions before.
Many of the more mature databases support the concept of prepared statements. What are they? You can think of them as a kind of compiled template for the SQL that you want to run, that can be customized using variable parameters. Prepared statements offer two major benefits:
The query only needs to be parsed (or prepared) once, but can be executed multiple times with the same or different parameters. When the query is prepared, the database will analyze, compile and optimize it's plan for executing the query. For complex queries this process can take up enough time that it will noticably slow down your application if you need to repeat the same query many times with different parameters. By using a prepared statement you avoid repeating the analyze/compile/optimize cycle. In short, prepared statements use fewer resources and thus run faster.
The parameters to prepared statements don't need to be quoted; the driver handles it for you. If your application exclusively uses prepared statements, you can be sure that no SQL injection will occur. (However, if you're still building up other parts of the query based on untrusted input, you're still at risk).
Prepared statements are so useful that they are the only feature that PDO will emulate for drivers that don't support them. This ensures that you will be able to use the same data access paradigm regardless of the capabilities of the database.
Esempio 6. Repeated inserts using prepared statements This example performs an INSERT query by substituting a name and a value for the named placeholders.
|
Esempio 7. Repeated inserts using prepared statements This example performs an INSERT query by substituting a name and a value for the positional ? placeholders.
|
Esempio 8. Fetching data using prepared statements This example fetches data based on a key value supplied by a form. The user input is automatically quoted, so there is no risk of a SQL injection attack.
|
If the database driver supports it, you may also bind parameters for output as well as input. Output parameters are typically used to retrieve values from stored procedures. Output parameters are slightly more complex to use than input parameters, in that you must know how large a given parameter might be when you bind it. If the value turns out to be larger than the size you suggested, an error is raised.
You may also specify parameters that hold values both input and output; the syntax is similar to output parameters. In this next example, the string 'hello' is passed into the stored procedure, and when it returns, hello is replaced with the return value of the procedure.
Esempio 10. Calling a stored procedure with an input/output parameter
|
PDO offers you a choice of 3 different error handling strategies, to fit your style of application development.
PDO::ERRMODE_SILENT
This is the default mode. PDO will simply set the error code for you to inspect using the PDO::errorCode() and PDO::errorInfo() methods on both the statement and database objects; if the error resulted from a call on a statement object, you would invoke the PDOStatement::errorCode() or PDOStatement::errorInfo() method on that object. If the error resulted from a call on the database object, you would invoke those methods on the database object instead.
PDO::ERRMODE_WARNING
In addition to setting the error code, PDO will emit a traditional E_WARNING message. This setting is useful during debugging/testing, if you just want to see what problems occurred without interrupting the flow of the application.
PDO::ERRMODE_EXCEPTION
In addition to setting the error code, PDO will throw a PDOException and set its properties to reflect the error code and error information. This setting is also useful during debugging, as it will effectively "blow up" the script at the point of the error, very quickly pointing a finger at potential problem areas in your code (remember: transactions are automatically rolled back if the exception causes the script to terminate).
Exception mode is also useful because you can structure your error handling more clearly than with traditional PHP-style warnings, and with less code/nesting than by running in silent mode and explicitly checking the return value of each database call.
See Exceptions for more information about Exceptions in PHP.
PDO standardizes on using SQL-92 SQLSTATE error code strings; individual PDO drivers are responsible for mapping their native codes to the appropriate SQLSTATE codes. The PDO::errorCode() method returns a single SQLSTATE code. If you need more specific information about an error, PDO also offers an PDO::errorInfo() method which returns an array containing the SQLSTATE code, the driver specific error code and driver specific error string.
At some point in your application, you might find that you need to store "large" data in your database. Large typically means "around 4kb or more", although some databases can happily handle up to 32kb before data becomes "large". Large objects can be either textual or binary in nature. PDO allows you to work with this large data type by using the PDO::PARAM_LOB type code in your PDOStatement::bindParam() or PDOStatement::bindColumn() calls. PDO::PARAM_LOB tells PDO to map the data as a stream, so that you can manipulate it using the PHP Streams API.
Esempio 11. Displaying an image from a database This example binds the LOB into the variable named $lob and then sends it to the browser using fpassthru(). Since the LOB is represented as a stream, functions such as fgets(), fread() and stream_get_contents() can be used on it.
|
Esempio 12. Inserting an image into a database This example opens up a file and passes the file handle to PDO to insert it as a LOB. PDO will do its best to get the contents of the file up to the database in the most efficient manner possible.
|
Represents a connection between PHP and a database server.
beginTransaction - begins a transaction
commit - commits a transaction
errorCode - retrieves an error code, if any, from the database
errorInfo - retrieves an array of error information, if any, from the database
exec - issues an SQL statement and returns the number of affected rows
getAttribute - retrieves a database connection attribute
lastInsertId - retrieves the value of the last row that was inserted into a table
prepare - prepares an SQL statement for execution
query - issues an SQL statement and returns a result set
quote - returns a quoted version of a string for use in SQL statements
rollBack - roll back a transaction
setAttribute - sets a database connection attribute
Represents a prepared statement and, after the statement is executed, an associated result set.
bindColumn - binds a PHP variable to an output column in a result set
bindParam - binds a PHP variable to a parameter in the prepared statement
bindValue - binds a value to a parameter in the prepared statement
closeCursor - closes the cursor, allowing the statement to be executed again
columnCount - returns the number of columns in the result set
errorCode - retrieves an error code, if any, from the statement
errorInfo - retrieves an array of error information, if any, from the statement
execute - executes a prepared statement
fetch - fetches a row from a result set
fetchAll - fetches an array containing all of the rows from a result set
fetchColumn - returns the data from a single column in a result set
getAttribute - retrieves a PDOStatement attribute
getColumnMeta - retrieves metadata for a column in the result set
nextRowset - retrieves the next rowset (result set)
rowCount - returns the number of rows that were affected by the execution of an SQL statement
setAttribute - sets a PDOStatement attribute
setFetchMode - sets the fetch mode for a PDOStatement
Represents an error raised by PDO. You should not throw a PDOException from your own code. See Exceptions for more information about Exceptions in PHP.
Esempio 13. The PDOException class
|
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Avvertimento |
PDO uses class constants since PHP 5.1. Prior releases use global constants in the form PDO_PARAM_BOOL. |
Represents a boolean data type.
Represents the SQL NULL data type.
Represents the SQL INTEGER data type.
Represents the SQL CHAR, VARCHAR, or other string data type.
Represents the SQL large object data type.
Represents a recordset type. Not currently supported by any drivers.
Specifies that the parameter is an INOUT parameter for a stored procedure. You must bitwise-OR this value with an explicit PDO::PARAM_* data type.
Specifies that the fetch method shall return each row as an object with variable names that correspond to the column names returned in the result set. PDO::FETCH_LAZY creates the object variable names as they are accessed.
Specifies that the fetch method shall return each row as an array indexed by column name as returned in the corresponding result set. If the result set contains multiple columns with the same name, PDO::FETCH_ASSOC returns only a single value per column name.
Specifies that the fetch method shall return each row as an array indexed by column name as returned in the corresponding result set. If the result set contains multiple columns with the same name, PDO::FETCH_NAMED returns an array of values per column name.
Specifies that the fetch method shall return each row as an array indexed by column number as returned in the corresponding result set, starting at column 0.
Specifies that the fetch method shall return each row as an array indexed by both column name and number as returned in the corresponding result set, starting at column 0.
Specifies that the fetch method shall return each row as an object with property names that correspond to the column names returned in the result set.
Specifies that the fetch method shall return TRUE and assign the values of the columns in the result set to the PHP variables to which they were bound with the PDOStatement::bindParam() or PDOStatement::bindColumn() methods.
Specifies that the fetch method shall return only a single requested column from the next row in the result set.
Specifies that the fetch method shall return a new instance of the requested class, mapping the columns to named properties in the class.
Specifies that the fetch method shall update an existing instance of the requested class, mapping the columns to named properties in the class.
If this value is FALSE, PDO attempts to disable autocommit so that the connection begins a transaction.
Setting the prefetch size allows you to balance speed against memory usage for your application. Not all database/driver combinations support setting of the prefetch size. A larger prefetch size results in increased performance at the cost of higher memory usage.
Sets the timeout value in seconds for communications with the database.
See the Errors and error handling section for more information about this attribute.
This is a read only attribute; it will return information about the version of the database server to which PDO is connected.
This is a read only attribute; it will return information about the version of the client libraries that the PDO driver is using.
This is a read only attribute; it will return some meta information about the database server to which PDO is connected.
Force column names to a specific case specified by the PDO::CASE_* constants.
Get or set the name to use for a cursor. Most useful when using scrollable cursors and positioned updates.
Selects the cursor type. PDO currently supports either PDO::CURSOR_FWDONLY and PDO::CURSOR_SCROLL. Stick with PDO::CURSOR_FWDONLY unless you know that you need a scrollable cursor.
Returns the name of the driver.
Convert empty strings to SQL NULL values on data fetches.
Request a persistent connection, rather than creating a new connection. See Connections and Connection management for more information on this attribute.
Prepend the containing catalog name to each column name returned in the result set. The catalog name and column name are separated by a decimal (.) character. Support of this attribute is at the driver level; it may not be supported by your driver.
Prepend the containing table name to each column name returned in the result set. The table name and column name are separated by a decimal (.) character. Support of this attribute is at the driver level; it may not be supported by your driver.
Do not raise an error or exception if an error occurs. The developer is expected to explicitly check for errors. This is the default mode. See Errors and error handling for more information about this attribute.
Issue a PHP E_WARNING message if an error occurs. See Errors and error handling for more information about this attribute.
Throw a PDOException if an error occurs. See Errors and error handling for more information about this attribute.
Leave column names as returned by the database driver.
Force column names to lower case.
Force column names to upper case.
Fetch the next row in the result set. Valid only for scrollable cursors.
Fetch the previous row in the result set. Valid only for scrollable cursors.
Fetch the first row in the result set. Valid only for scrollable cursors.
Fetch the last row in the result set. Valid only for scrollable cursors.
Fetch the requested row by row number from the result set. Valid only for scrollable cursors.
Fetch the requested row by relative position from the current position of the cursor in the result set. Valid only for scrollable cursors.
Create a PDOStatement object with a forward-only cursor. This is the default cursor choice, as it is the fastest and most common data access pattern in PHP.
Create a PDOStatement object with a scrollable cursor. Pass the PDO::FETCH_ORI_* constants to control the rows fetched from the result set.
Corresponds to SQLSTATE '00000', meaning that the SQL statement was successfully issued with no errors or warnings. This constant is for your convenience when checking PDO::errorCode() or PDOStatement::errorCode() to determine if an error occurred. You will usually know if this is the case by examining the return code from the method that raised the error condition anyway.
Turns off autocommit mode. While autocommit mode is turned off, changes made to the database via the PDO object instance are not committed until you end the transaction by calling PDO::commit(). Calling PDO::rollback() will roll back all changes to the database and return the connection to autocommit mode.
Some databases, including MySQL, automatically issue an implicit COMMIT when a database definition language (DDL) statement such as DROP TABLE or CREATE TABLE is issued within a transaction. The implicit COMMIT will prevent you from rolling back any other changes within the transaction boundary.
Esempio 1. Roll back a transaction The following example begins a transaction and issues two statements that modify the database before rolling back the changes. On MySQL, however, the DROP TABLE statement automatically commits the transaction so that none of the changes in the transaction are rolled back.
|
Commits a transaction, returning the database connection to autocommit mode until the next call to PDO::beginTransaction() starts a new transaction.
(no version information, might be only in CVS)
PDO::__construct -- Creates a PDO instance representing a connection to a databaseCreates a PDO instance to represent a connection to the requested database.
The Data Source Name, or DSN, contains the information required to connect to the database.
In general, a DSN consists of the PDO driver name, followed by a colon, followed by the PDO driver-specific connection syntax. Further information is available from the PDO driver-specific documentation.
The dsn parameter supports three different methods of specifying the arguments required to create a database connection:
dsn contains the full DSN.
dsn consists of uri: followed by a URI that defines the location of a file containing the DSN string. The URI can specify a local file or a remote URL.
uri:file:///path/to/dsnfile
dsn consists of a name name that maps to pdo.dsn.name in php.ini defining the DSN string.
Nota: The alias must be defined in php.ini, and not .htaccess or httpd.conf
The user name for the DSN string. This parameter is optional for some PDO drivers.
The password for the DSN string. This parameter is optional for some PDO drivers.
A key=>value array of driver-specific connection options.
PDO::construct() throws a PDOException if the attempt to connect to the requested database fails.
Esempio 1. Create a PDO instance via driver invocation
|
Esempio 2. Create a PDO instance via URI invocation The following example assumes that the file /usr/local/dbconnect exists with file permissions that enable PHP to read the file. The file contains the PDO DSN to connect to a DB2 database through the PDO_ODBC driver:
The PHP script can then create a database connection by simply passing the uri: parameter and pointing to the file URI:
|
Esempio 3. Create a PDO instance using an alias The following example assumes that php.ini contains the following entry to enable a connection to a MySQL database using only the alias mydb:
|
(no version information, might be only in CVS)
PDO::errorCode -- Fetch the SQLSTATE associated with the last operation on the database handleReturns a SQLSTATE, a five-character alphanumeric identifier defined in the ANSI SQL-92 standard. Briefly, an SQLSTATE consists of a two-character class value followed by a three-character subclass value. A class value of 01 indicates a warning and is accompanied by a return code of SQL_SUCCESS_WITH_INFO. Class values other than '01', except for the class 'IM', indicate an error. The class 'IM' is specific to warnings and errors that derive from the implementation of PDO (or perhaps ODBC, if you're using the ODBC driver) itself. The subclass value '000' in any class indicates that there is no subclass for that SQLSTATE.
PDO::errorCode() only retrieves error codes for operations performed directly on the database handle. If you create a PDOStatement object through PDO::prepare() or PDO::query() and invoke an error on the statement handle, PDO::errorCode() will not reflect that error. You must call PDOStatement::errorCode() to return the error code for an operation performed on a particular statement handle.
(no version information, might be only in CVS)
PDO::errorInfo -- Fetch extended error information associated with the last operation on the database handlePDO::errorInfo() returns an array of error information about the last operation performed by this database handle. The array consists of the following fields:
Element | Information |
---|---|
0 | SQLSTATE error code (a five-character alphanumeric identifier defined in the ANSI SQL standard). |
1 | Driver-specific error code. |
2 | Driver-specific error message. |
PDO::errorInfo() only retrieves error information for operations performed directly on the database handle. If you create a PDOStatement object through PDO::prepare() or PDO::query() and invoke an error on the statement handle, PDO::errorInfo() will not reflect the error from the statement handle. You must call PDOStatement::errorInfo() to return the error information for an operation performed on a particular statement handle.
Esempio 1. Displaying errorInfo() fields for a PDO_ODBC connection to a DB2 database
Il precedente esempio visualizzerà:
|
(no version information, might be only in CVS)
PDO::exec -- Execute an SQL statement and return the number of affected rowsPDO::exec() executes an SQL statement in a single function call, returning the number of rows affected by the statement.
PDO::exec() does not return results from a SELECT statement. For a SELECT statement that you only need to issue once during your program, consider issuing PDO::query(). For a statement that you need to issue multiple times, prepare a PDOStatement object with PDO::prepare() and issue the statement with PDOStatement::execute().
PDO::exec() returns the number of rows that were modified or deleted by the SQL statement you issued. If no rows were affected, PDO::exec() returns 0.
Avvertimento |
Questa funzione può restituire il Booleano FALSE, ma può anche restituire un valore non-Booleano valutato come FALSE, come ad esempio 0 o "". Per favore fare riferimento alla sezione Booleans per maggiori informazioni. Usare l'operatore === per controllare il valore restituito da questa funzione. |
The following example incorrectly relies on the return value of PDO::exec(), wherein a statement that affected 0 rows results in a call to die():
<?php $db->exec() or die($db->errorInfo()); ?> |
Esempio 1. Issuing a DELETE statement Count the number of rows deleted by a DELETE statement with no WHERE clause.
Il precedente esempio visualizzerà:
|
(no version information, might be only in CVS)
PDO::getAttribute -- Retrieve a database connection attributeThis function returns the value of a database connection attribute. To retrieve PDOStatement attributes, refer to PDOStatement::getAttribute().
Note that some database/driver combinations may not support all of the database connection attributes.
One of the PDO::ATTR_* constants. The constants that apply to database connections are as follows:
PDO::ATTR_AUTOCOMMIT |
PDO::ATTR_CASE |
PDO::ATTR_CLIENT_VERSION |
PDO::ATTR_CONNECTION_STATUS |
PDO::ATTR_DRIVER_NAME |
PDO::ATTR_ERRMODE |
PDO::ATTR_ORACLE_NULLS |
PDO::ATTR_PERSISTENT |
PDO::ATTR_PREFETCH |
PDO::ATTR_SERVER_INFO |
PDO::ATTR_SERVER_VERSION |
PDO::ATTR_TIMEOUT |
A successful call returns the value of the requested PDO attribute. An unsuccessful call returns null.
Esempio 1. Retrieving database connection attributes
|
(no version information, might be only in CVS)
PDO::getAvailableDrivers -- Return an array of available PDO driversThis function returns all currently available PDO drivers which can be used in DSN parameter of PDO::__construct(). This is a static method.
PDO::getAvailableDrivers() returns an array of PDO driver names. If no drivers are available, it returns an empty array.
(no version information, might be only in CVS)
PDO::lastInsertId -- Returns the ID of the last inserted row or sequence valueReturns the ID of the last inserted row, or the last value from a sequence object, depending on the underlying driver.
Nota: This method may not return a meaningful/consistent result across different PDO drivers, because the underlying database may not even support the notion of auto-increment fields or sequences.
If a sequence name was not specified for the name parameter, PDOStatement::lastInsertId() returns a string representing the row ID of the last row that was inserted into the database.
If a sequence name was specified for the name parameter, PDOStatement::lastInsertId() returns a string representing the last value retrieved from the specified sequence object.
If the PDO driver does not support this capability, PDO::lastInsertID() triggers an IM001 SQLSTATE.
(no version information, might be only in CVS)
PDO::prepare -- Prepares a statement for execution and returns a statement objectPrepares an SQL statement to be executed by the PDOStatement::execute() method. The SQL statement can contain zero or more named (:name) or question mark (?) parameter markers for which real values will be substituted when the statement is executed. You cannot use both named and question mark parameter markers within the same SQL statement; pick one or the other parameter style.
Calling PDO::prepare() and PDOStatement::execute() for statements that will be issued multiple times with different parameter values optimizes the performance of your application by allowing the driver to negotiate client and/or server side caching of the query plan and meta information, and helps to prevent SQL injection attacks by eliminating the need to manually quote the parameters.
PDO will emulate prepared statements/bound parameters for drivers that do not natively support them, and can also rewrite named or question mark style parameter markers to something more appropriate, if the driver supports one style but not the other.
This must be a valid SQL statement for the target database server.
This array holds one or more key=>value pairs to set attribute values for the PDOStatement object that this method returns. You would most commonly use this to set the PDO::ATTR_CURSOR value to PDO::CURSOR_SCROLL to request a scrollable cursor. Some drivers have driver specific options that may be set at prepare-time.
If the database server successfully prepares the statement, PDO::prepare() returns a PDOStatement object.
Esempio 1. Prepare an SQL statement with named parameters
|
Esempio 2. Prepare an SQL statement with question mark parameters
|
(no version information, might be only in CVS)
PDO::query -- Executes an SQL statement, returning a result set as a PDOStatement objectPDO::query() executes an SQL statement in a single function call, returning the result set (if any) returned by the statement as a PDOStatement object.
For a query that you need to issue multiple times, you will realize better performance if you prepare a PDOStatement object using PDO::prepare() and issue the statement with multiple calls to PDOStatement::execute().
Esempio 1. Demonstrate PDO::query A nice feature of PDO::query() is that it enables you to iterate over the rowset returned by a successfully executed SELECT statement.
Il precedente esempio visualizzerà:
|
PDO::quote() places quotes around the input string and escapes and single quotes within the input string, using a quoting style appropriate to the underlying driver.
If you are using this function to build SQL statements, you are strongly recommended to use PDO::prepare() to prepare SQL statements with bound parameters instead of using PDO::quote() to interpolate user input into a SQL statement. Prepared statements with bound parameters are not only more portable, more convenient, and vastly more secure, but are often much faster than interpolating user input into slight variations on the same basic SQL statement.
Not all PDO drivers implement this method (notably PDO_ODBC). Consider using prepared statements instead.
The string to be quoted.
Provides a data type hint for drivers that have alternate quoting styles. The default value is PDO_PARAM_STR.
Returns a quoted string that is theoretically safe to pass into an SQL statement. Returns FALSE if the driver does not support quoting in this way.
Esempio 2. Quoting a dangerous string
Il precedente esempio visualizzerà:
|
Esempio 3. Quoting a complex string
Il precedente esempio visualizzerà:
|
Rolls back the current transaction, as initiated by PDO::beginTransaction(). It is an error to call this method if no transaction is active.
If the database was set to autocommit mode, this function will restore autocommit mode after it has rolled back the transaction.
Some databases, including MySQL, automatically issue an implicit COMMIT when a database definition language (DDL) statement such as DROP TABLE or CREATE TABLE is issued within a transaction. The implicit COMMIT will prevent you from rolling back any other changes within the transaction boundary.
Esempio 1. Roll back a transaction The following example begins a transaction and issues two statements that modify the database before rolling back the changes. On MySQL, however, the DROP TABLE statement automatically commits the transaction so that none of the changes in the transaction are rolled back.
|
Sets an attribute on the database handle. Some of the available generic attributes are listed below; some drivers may make use of additional driver specific attributes.
PDO::ATTR_CASE: Force column names to a specific case.
PDO::CASE_LOWER: Force column names to lower case.
PDO::CASE_NATURAL: Leave column names as returned by the database driver.
PDO::CASE_UPPER: Force column names to upper case.
(no version information, might be only in CVS)
PDOStatement::bindColumn -- Bind a column to a PHP variablePDOStatement::bindColumn() arranges to have a particular variable bound to a given column in the result-set from a query. Each call to PDOStatement::fetch() or PDOStatement::fetchAll() will update all the variables that are bound to columns.
Nota: Since information about the columns is not always available to PDO until the statement is executed, portable applications should call this function after PDO::execute().
Number of the column (1-indexed) or name of the column in the result set. If using the column name, be aware that the name should match the case of the column, as returned by the driver.
Name of the PHP variable to which the column will be bound.
Data type of the parameter, specified by the PDO::PARAM_* constants.
Esempio 1. Binding result set output to PHP variables Binding columns in the result set to PHP variables is an effective way to make the data contained in each row immediately available to your application. The following example demonstrates how PDO allows you to bind and retrieve columns with a variety of options and with intelligent defaults.
Il precedente esempio visualizzerà:
|
PDOStatement::execute() |
PDOStatement::fetch() |
PDOStatement::fetchAll() |
PDOStatement::fetchColumn() |
(no version information, might be only in CVS)
PDOStatement::bindParam -- Binds a parameter to the specified variable nameBinds a PHP variable to a corresponding named or question mark placeholder in the SQL statement that was use to prepare the statement. Unlike PDOStatement::bindValue(), the variable is bound as a reference and will only be evaluated at the time that PDOStatement::execute() is called.
Most parameters are input parameters, that is, parameters that are used in a read-only fashion to build up the query. Some drivers support the invocation of stored procedures that return data as output parameters, and some also as input/output parameters that both send in data and are updated to receive it.
Parameter identifier. For a prepared statement using named placeholders, this will be a parameter name of the form :name. For a prepared statement using question mark placeholders, this will be the 1-indexed position of the parameter.
Name of the PHP variable to bind to the SQL statement parameter.
Explicit data type for the parameter using the PDO::PARAM_* constants. To return an INOUT parameter from a stored procedure, use the bitwise OR operator to set the PDO::PARAM_INPUT_OUTPUT bits for the data_type parameter.
Length of the data type. To indicate that a parameter is an OUT parameter from a stored procedure, you must explicitly set the length.
Esempio 1. Execute a prepared statement with named placeholders
|
Esempio 2. Execute a prepared statement with question mark placeholders
|
Esempio 3. Call a stored procedure with an INOUT parameter
|
(no version information, might be only in CVS)
PDOStatement::bindValue -- Binds a value to a parameterBinds a value to a corresponding named or question mark placeholder in the SQL statement that was use to prepare the statement.
Parameter identifier. For a prepared statement using named placeholders, this will be a parameter name of the form :name. For a prepared statement using question mark placeholders, this will be the 1-indexed position of the parameter.
The value to bind to the parameter.
Explicit data type for the parameter using the PDO::PARAM_* constants.
Esempio 1. Execute a prepared statement with named placeholders
|
Esempio 2. Execute a prepared statement with question mark placeholders
|
(no version information, might be only in CVS)
PDOStatement::closeCursor -- Closes the cursor, enabling the statement to be executed again.PDOStatement::closeCursor() frees up the connection to the server so that other SQL statements may be issued, but leaves the statement in a state that enables it to be executed again.
This method is useful for database drivers that do not support executing a PDOStatement object when a previously executed PDOStatement object still has unfetched rows. If your database driver suffers from this limitation, the problem may manifest itself in an out-of-sequence error.
PDOStatement::closeCursor() is implemented either as an optional driver specific method (allowing for maximum efficiency), or as the generic PDO fallback if no driver specific function is installed. The PDO generic fallback is semantically the same as writing the following code in your PHP script:
<?php do { while ($stmt->fetch()) ; if (!$stmt->nextRowset()) break; } while (true); ?> |
Esempio 1. A PDOStatement::closeCursor() example In the following example, the $stmt PDOStatement object returns multiple rows but the application fetches only the first row, leaving the PDOStatement object in a state of having unfetched rows. To ensure that the application will work with all database drivers, the author inserts a call to PDOStatement::closeCursor() on $stmt before executing the $otherStmt PDOStatement object.
|
(no version information, might be only in CVS)
PDOStatement::columnCount -- Returns the number of columns in the result setUse PDOStatement::columnCount() to return the number of columns in the result set represented by the PDOStatement object.
If the PDOStatement object was returned from PDO::query(), the column count is immediately available.
If the PDOStatement object was returned from PDO::prepare(), an accurate column count will not be available until you invoke PDOStatement::execute().
Returns the number of columns in the result set represented by the PDOStatement object. If there is no result set, PDOStatement::columnCount() returns 0.
Esempio 1. Counting columns This example demonstrates how PDOStatement::columnCount() operates with and without a result set.
Il precedente esempio visualizzerà:
|
(no version information, might be only in CVS)
PDOStatement::errorCode -- Fetch the SQLSTATE associated with the last operation on the statement handleIdentical to PDO::errorCode(), except that PDOStatement::errorCode() only retrieves error codes for operations performed with PDOStatement objects.
(no version information, might be only in CVS)
PDOStatement::errorInfo -- Fetch extended error information associated with the last operation on the statement handlePDOStatement::errorInfo() returns an array of error information about the last operation performed by this statement handle. The array consists of the following fields:
Esempio 1. Displaying errorInfo() fields for a PDO_ODBC connection to a DB2 database
Il precedente esempio visualizzerà:
|
(no version information, might be only in CVS)
PDOStatement::execute -- Executes a prepared statementExecute the prepared statement. If the prepared statement included parameter markers, you must either:
call PDOStatement::bindParam() to bind PHP variables to the parameter markers: bound variables pass their value as input and receive the output value, if any, of their associated parameter markers
or pass an array of input-only parameter values
Esempio 1. Execute a prepared statement with bound variables
|
Esempio 2. Execute a prepared statement with an array of insert values
|
Esempio 3. Execute a prepared statement with question mark placeholders
|
PDO::prepare() |
PDOStatement::bindParam() |
PDOStatement::fetch() |
PDOStatement::fetchAll() |
PDOStatement::fetchColumn() |
(no version information, might be only in CVS)
PDOStatement::fetch -- Fetches the next row from a result setFetches a row from a result set associated with a PDOStatement object.
Controls how the next row will be returned to the caller. This value must be one of the PDO::FETCH_* constants, defaulting to PDO::FETCH_BOTH.
PDO::FETCH_ASSOC: returns an array indexed by column name as returned in your result set
PDO::FETCH_BOTH (default): returns an array indexed by both column name and column number as returned in your result set
PDO::FETCH_BOUND: returns TRUE and assigns the values of the columns in your result set to the PHP variables to which they were bound with the PDOStatement::bindParam() method
PDO::FETCH_LAZY: combines PDO::FETCH_BOTH and PDO::FETCH_OBJ, creating the object variable names as they are accessed
PDO::FETCH_OBJ: returns an anonymous object with property names that correspond to the column names returned in your result set
PDO::FETCH_NUM: returns an array indexed by column number as returned in your result set, starting at column 0
For a PDOStatement object representing a scrollable cursor, this value determines which row will be returned to the caller. This value must be one of the PDO::FETCH_ORI_* constants, defaulting to PDO::FETCH_ORI_NEXT.
For a PDOStatement object representing a scrollable cursor for which the cursor_orientation parameter is set to PDO::FETCH_ORI_ABS, this value specifies the absolute number of the row in the result set that shall be fetched.
For a PDOStatement object representing a scrollable cursor for which the cursor_orientation parameter is set to PDO::FETCH_ORI_REL, this value specifies the row to fetch relative to the cursor position before PDOStatement::fetch() was called.
Esempio 1. Fetching rows using different fetch styles
Il precedente esempio visualizzerà:
|
Esempio 2. Fetching rows with a scrollable cursor
Il precedente esempio visualizzerà:
|
PDO::query() |
PDOStatement::fetchAll() |
PDOStatement::fetchColumn() |
PDOStatement::prepare() |
PDOStatement::setFetchMode() |
(no version information, might be only in CVS)
PDOStatement::fetchAll -- Returns an array containing all of the result set rows
Controls the contents of the returned array as documented in PDOStatement::fetch(). Defaults to PDO::FETCH_BOTH.
To return an array consisting of all values of a single column from the result set, specify PDO::FETCH_COLUMN.
To fetch only the unique values of a single column from the result set, bitwise-OR PDO::FETCH_COLUMN with PDO::FETCH_UNIQUE.
To return an associative array grouped by the values of a specified column, bitwise-OR PDO::FETCH_COLUMN with PDO::FETCH_GROUP.
Returns the indicated 0-indexed column when the value of fetch_style is PDO::FETCH_COLUMN. Defaults to 0.
PDOStatement::fetchAll() returns an array containing all of the remaining rows in the result set. The array represents each row as either an array of column values or an object with properties corresponding to each column name.
Using this method to fetch large result sets will result in a heavy demand on system and possibly network resources. Rather than retrieving all of the data and manipulating it in PHP, consider using the database server to manipulate the result sets. For example, use the WHERE and SORT BY clauses in SQL to restrict results before retrieving and processing them with PHP.
Esempio 1. Fetch all remaining rows in a result set
Il precedente esempio visualizzerà:
|
Esempio 2. Fetching all values of a single column from a result set The following example demonstrates how to return all of the values of a single column from a result set, even though the SQL statement itself may return multiple columns per row.
Il precedente esempio visualizzerà:
|
Esempio 3. Grouping all values by a single column The following example demonstrates how to return an associative array grouped by the values of the specified column in the result set. The array contains three keys: values apple and pear are returned as arrays that contain two different colours, while watermelon is returned as an array that contains only one colour.
Il precedente esempio visualizzerà:
|
PDO::query() |
PDOStatement::fetch() |
PDOStatement::fetchColumn() |
PDOStatement::prepare() |
PDOStatement::setFetchMode() |
(no version information, might be only in CVS)
PDOStatement::fetchColumn -- Returns a single column from the next row of a result setReturns a single column from the next row of a result set.
Number of the column you wish to retrieve from the row. If no value is supplied, PDOStatement::fetchColumn() fetches the first column.
PDOStatement::fetchColumn() returns a single column in the next row of a result set.
Avvertimento |
There is no way to return another column from the same row if you use PDOStatement::fetchColumn() to retrieve data. |
Esempio 1. Return first column of the next row
Il precedente esempio visualizzerà:
|
PDO::query() |
PDOStatement::fetch() |
PDOStatement::fetchAll() |
PDOStatement::prepare() |
PDOStatement::setFetchMode() |
(no version information, might be only in CVS)
PDOStatement::getAttribute -- Retrieve a statement attributeAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
PDOStatement::getColumnMeta -- Returns metadata for a column in a result setAvvertimento |
Questa funzione è SPERIMENTALE. Ovvero, il comportamento di questa funzione, il nome di questa funzione, in definitiva tutto ciò che è documentato qui può cambiare nei futuri rilasci del PHP senza preavviso. Siete avvisati, l'uso di questa funzione è a vostro rischio. |
Retrieves the metadata for a 0-indexed column in a result set as an associative array.
Avvertimento |
Not all PDO drivers support PDOStatement::getColumnMeta(). |
Returns an associative array containing the following values representing the metadata for a single column:
Tabella 1. Column metadata
Name | Value |
---|---|
native_type | The PHP native type used to represent the column value. |
driver:decl_type | The SQL type used to represent the column value in the database. If the column in the result set is the result of a function, this value is not returned by PDOStatement::getColumnMeta(). |
flags | Any flags set for this column. |
name | The name of this column as returned by the database. |
len | The length of this column. Normally -1 for types other than floating point decimals. |
precision | The numeric precision of this column. Normally 0 for types other than floating point decimals. |
pdo_type | The type of this column as represented by the PDO::PARAM_* constants. |
Returns FALSE if the requested column does not exist in the result set, or if no result set exists.
Esempio 1. Retrieving column metadata The following example shows the results of retrieving the metadata for a single column generated by a function (COUNT) in a PDO_SQLITE driver.
Il precedente esempio visualizzerà:
|
(no version information, might be only in CVS)
PDOStatement::nextRowset -- Advances to the next rowset in a multi-rowset statement handleSome database servers support stored procedures that return more than one rowset (also known as a result set). PDOStatement::nextRowSet() enables you to access the second and subsequent rowsets associated with a PDOStatement object. Each rowset can have a different set of columns from the preceding rowset.
Esempio 1. Fetching multiple rowsets returned from a stored procedure The following example shows how to call a stored procedure, MULTIPLE_RESULTS, that returns three rowsets. We use a do / while loop to loop over the PDOStatement::nextRowset() method, which returns false and terminates the loop when no more rowsets can be returned.
Il precedente esempio visualizzerà:
|
PDOStatement::columnCount() |
PDOStatement::execute() |
PDOStatement::getColumnMeta() |
PDOStatement::query() |
(no version information, might be only in CVS)
PDOStatement::rowCount -- Returns the number of rows affected by the last SQL statementPDOStatement::rowCount() returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement executed by the corresponding PDOStatement object.
If the last SQL statement executed by the associated PDOStatement was a SELECT statement, some databases may return the number of rows returned by that statement. However, this behaviour is not guaranteed for all databases and should not be relied on for portable applications.
Esempio 1. Return the number of deleted rows PDOStatement::rowCount() returns the number of rows affected by a DELETE, INSERT, or UPDATE statement.
Il precedente esempio visualizzerà:
|
Esempio 2. Counting rows returned by a SELECT statement For most databases, PDOStatement::rowCount() does not return the number of rows affected by a SELECT statement. Instead, use PDO::query() to issue a SELECT COUNT(*) statement with the same predicates as your intended SELECT statement, then use PDOStatement::fetchColumn() to retrieve the number of rows that will be returned. Your application can then perform the correct action.
Il precedente esempio visualizzerà:
|
(no version information, might be only in CVS)
PDOStatement::setAttribute -- Set a statement attributeAvvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(no version information, might be only in CVS)
PDOStatement::setFetchMode -- Set the default fetch mode for this statement
Esempio 1. Setting the fetch mode The following example demonstrates how PDOStatement::setFetchMode() changes the default fetch mode for a PDOStatement object.
Il precedente esempio visualizzerà:
|
Queste funzioni permettono di accedere a diverse informazioni sul PHP stesso, come la configurazione di runtime, il moduli caricati, la versione e molto altro. Si troveranno anche funzioni per impostare le opzioni di runtime del PHP. Probabilmente la più nota tra queste è - phpinfo() -.
Non è necessaria nessuna installazione per usare queste funzioni, esse fanno parte del core di PHP.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. Parametri di configurazione per PHP Opzioni/informazioni
Nome | Default | Modificabile |
---|---|---|
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 |
max_input_time | "60" | PHP_INI_ALL |
magic_quotes_gpc | "1" | PHP_INI_PERDIR|PHP_INI_SYSTEM |
magic_quotes_runtime | "0" | PHP_INI_ALL |
Breve descrizione dei parametri di configurazione.
Abilita l'analisi degli assert().
Termina uno script a fronte di un assert fallito.
Invia un PHP warning per ogni asserzione fallita.
Funzione utente da richiamare a fronte di un assert fallito
Utilizzare questo parametro di error_reporting() durante l'analisi dei un'asserzione. Se è abilitato, non sono visualizzati gli errori (error_reporting(0)) durante il parsing di una asserzione. Se disabilitato, gli errori saranno visualizzati in base all'impostazione di error_reporting().
Questa direttiva è utile soltanto nella versione di PHP attiva come modulo di Apache. Essa permette di caricare in modo dinamico le estensioni di PHP potendo impostare dl() on oppure off in base al server virtuale o per directory.
La ragione principale per disabilitare il caricamento dinamico dei moduli è la sicurezza. Con il caricamento dinamico è possibile ignorare tutte le restrizioni open_basedir. Per default il caricamento dinamico è attivo tranne quando si utilizza il modalità sicura. In modalità sicura, è sempre impossibile utilizzare dl().
Questo parametro imposta il tempo massimo in secondi concessi ad uno script per l'esecuzione prima di essere interrotto dal parser. Questo aiuta a prevenire che script scritti male blocchino il server. Per default è impostato a 30.
Il tempo massimo di esecuzione non è condizionato dalle chiamate di sistema, dalle operazioni sugli stream, eccetera. Vedere la funzione set_time_limit() per maggiori dettagli.
Non si può cambiare questo parametro con ini_set() quando il PHP gira in modalità sicura. L'unico modo è di disabilitare il safe mode oppure di cambiare il limite di tempo nel php.ini.
Anche il server web ha i propri timeout. Ad esempio Apache ha un proprio parametro Timeout, IIS ha una funzione di timeout sugli script CGI, entrambi con default 300 secondi. Vedere la documentazione del server web per maggiori dettagli.
Impostail tempo massimo in secondi concesso ad uno script per ricevere i dati di input, tipo POST, GET e upload di file. Il valore di default è 60.
Imposta il parametro magic_quote per GPC (Get/Post/Cookie). Quando magic_quote è impostato a on, tutti i ' (apici singoli), " (doppi apici), \ (backslash) e NUL sono vengono preceduti in automatico dal backslash.
Nota: Se il parametro magic_quotes_sybase è impostato a ON, questo è prioritario rispetto a magic_quotes_gpc. Avere entrambi i parametri attivi significa che soltanto gli apici singoli sono preceduti dal carattere di escape come ''. Doppi apici, backslash, e NUL non vengono toccati.
Vedere anche get_magic_quotes_gpc()
Se si abilita magic_quotes_runtime, diverse funzioni che restituiscono dati da ogni tipo di fonte esterna, compresi i database ed i file di testo, avranno gli apici preceduti dal backslash. Se è anche attivato magic_quotes_sybase, soltanto l'apice singolo sarà preceduto dal carattere di escape costituito da un apice singolo anzichè il backslash.
Le costanti qui elencate sono sempre disponibili in quanto parte del core di PHP.
Tabella 2. Costanti predefinite per phpcredits()
Costante | Valore | Descrizione |
---|---|---|
CREDITS_GROUP | 1 | Lista degli sviluppatori principali |
CREDITS_GENERAL | 2 | Lista generale: design e progetto del linguaggio, autori del PHP e del modulo SAPI. |
CREDITS_SAPI | 4 | Lista delle API server e dei loro sviluppatori. |
CREDITS_MODULES | 8 | Lista dei moduli e dei loro sviluppatori. |
CREDITS_DOCS | 16 | La lista del gruppo di documentazione. |
CREDITS_FULLPAGE | 32 | Solitamente utilizzato in combinazione con altri flag. Indica che la pagina completa HTML deve essere stampata includendo le infomazioni di altri flag. |
CREDITS_QA | 64 | Elenca i riconoscimenti per il gruppo della qualità. |
CREDITS_ALL | -1 | Tutta la lista dei meriti, equivale a CREDITS_DOCS + CREDITS_GENERAL + CREDITS_GROUP + CREDITS_MODULES + CREDITS_FULLPAGE. Genera una pagina HTML completa. Questa è l'impostazione di default. |
Tabella 3. Costanti di phpinfo()
Costante | Valore | Descrizione |
---|---|---|
INFO_GENERAL | 1 | La linea di configurazione, php.ini luogo, data di compila, Web Server, sistema e altro. |
INFO_CREDITS | 2 | PHP Credits. Vedere anche phpcredits(). |
INFO_CONFIGURATION | 4 | Impostazioni correnti e di base delle opzioni PHP. Vedere anche ini_get(). |
INFO_MODULES | 8 | Moduli caricati e le loro impostazioni. |
INFO_ENVIRONMENT | 16 | Variabili d'ambiente disponibili in $_ENV. |
INFO_VARIABLES | 32 | Visualizza tutte le variabili predefinite da EGPCS (Environment, GET, POST, Cookie, Server). |
INFO_LICENSE | 64 | Informazioni sulla licenza di PHP. Vedere anche faq sulla licenza. |
INFO_ALL | -1 | Visualizza tutto quanto descritto. Questo è il valore dei default. |
Usando assert_options() si è in grado di impostare vari parametri di controllo per la funzione assert(), oppure ottenerne l'impostazione corrente.
Tabella 1. Opzioni di assert
opzione | parametro ini | default | descrizione |
---|---|---|---|
ASSERT_ACTIVE | assert.active | 1 | abilita l'assert() |
ASSERT_WARNING | assert.warning | 1 | indica a PHP i generare un warning per ogni asserzione fallita |
ASSERT_BAIL | assert.bail | 0 | termina l'esecuzione alla prima asserzione fallita |
ASSERT_QUIET_EVAL | assert.quiet_eval | 0 | disabilita la gestione degli errori nelle espressioni di asserzione |
ASSERT_CALLBACK | assert.callback | (NULL) | funzione utente da richiamare per le asserzioni fallite |
assert_options() restituirà l'impostazione originale di ogni opzione, oppure FALSE se fallisce.
assert() verifica se la data assertion è FALSE, nel caso intraprende le opportune azioni.
Se il parametro assertion è una stringa questo sarà considerato da assert() come codice PHP. I vantaggi di usare le stringhe con assertion sono che si ha meno overhead nella verifica e la visualizzazione dei messaggi che contengono assertion quando questa fallisce. Ciò significa che se si passa una condizione booleana come assertion, questa condizione non sarà mostrata come parametro della funzione che può essere definita con assert_options(), la condizione sarò in stringa prima di chiamare la funzione handler, e il valore booleano FALSE viene convertito in una stringa vuota.
Le asserzioni dovrebbero essere utilizzate solo per il debug. Si possono usare per controlli di coerenza che sono sempre TRUE e che, in caso contrario, indichino errori di programmazione, oppure per verificare la presenza o meni di certe caratteristiche, tipo le estensioni, oppure certi limiti di sistema o caratteristiche.
Le asserzioni non dovrebbero essere utilizzate per le normali operazioni di runtime quali il controllo dei parametri di input. Come regola si deve avere che il programma possa girare senza la presenza delle regole di asserzione.
Il comportamento di assert() può essere impostato tramite assert_options() oppure tramite .ini-settings come descritto nel pagine del manuale relative a quelle funzioni.
La funzione assert_options() e/o il parametro ASSERT_CALLBACK permetto di attivare una funzione di callback per gestire una asserzione fallita.
I callback di assert() sono particolarmente utili per costruire suite di test poiché permettono di catturare facilmente il codice passato all'assert, oltre alle informazioni su dove l'assert è scattato. Sebbene quest'ultime informazioni siano rilevabili anche con altri metodi, l'uso delle asserzione rende il tutto più semplice!
Le funzioni di callback devono accettare tre parametri. Il primo conterrà il nome del file in cui si trova l'asserzione fallita. Il secondo parametro conterrà il numero di linea dell'asserzione fallita, ed il terzo conterrà l'espressione dell'asserzione (se fornito - valori alfanumerici quali 1 o due" non saranno passati a questo parametro).
Esempio 1. Gestione di una asserzione fallita con codice personalizzato
|
La funzione carica il modulo di PHP passato nel parametro library. Il parametro library indica soltanto il nome del file del modulo da caricare il quale può dipendere dal piattaforma utilizzata. Ad esempio il modulo sockets (se compilato come modulo condiviso, non è il default!) sulle piattaforme Unix si chiama sockets.so, mentre in Windows si chiama php_sockets.dll.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento. Se la funzionalità di carico dei moduli non è disponibile (vedi note), oppure è stata disabilitata (sia disabilitando enable_dl oppure attivando modalità sicura nel php.ini), sarà generato un E_ERROR e sarà bloccata l'esecuzione dello script. Se dl() fallisce perché non riesce a caricare la libreria indicata, oltre a restituire FALSE verrà generato un messaggio di tipo E_WARNING.
Si può utilizzare extension_loaded() per testare se un modulo è veramente affidabile o meno. Questa funzione si applica sia a moduli built-in sia ai moduli caricati (tramite php.ini oppure dl()).
La funzione dl() è deprecata dal PHP 5. Piuttosto utilizzare Parametri per il carico dei moduli.
Esempio 1. Esempio di uso di dl()
|
La directory da cui vengono caricate le estensioni dipende dal sistema operativo della macchina:
Windows - Se non viene impostato esplicitamente nel php.ini, i moduli sono caricati da c:\php4\extensions\ .
Unix - Se non viene impostato esplicitamente nel php.ini, la directory di default dipenda da
se il PHP è stato compilato con --enable-debug o meno
se il PHP è stato compilato con (versione sperimentale) ZTS (Zend Thread Safety) o meno
il valore attuale di ZEND_MODULE_API_NO (numero interno del modulo API Zend, il quale indica la data in cui si sono apportate le maggiori modifiche al modulo, ad esempio 20010901)
Nota: La funzione dl() non è supportata dai web server multithread. Utilizzare il parametro del php.ini extensions quando si debba utilizzare tali server. Mentre le versioni CGI e CLI non hanno questa limitazione.
Nota: La dl() è sensibile alla maiuscole sulle piattaforme Unix.
Nota: Questa funzione è disabilitata nella modalitàsafe-mode
Vedere anche Direttive per il carimaneto dei moduli e extension_loaded().
Restituisce TRUE se il modulo specificato da name è caricato, oppure FALSE.
Si può verificare il nome dei vari moduli caricati tramite phpinfo(), o, se si sta utilizzando le versioni CGI o CLI di PHP, si può utilizzare l'opzione -m:
$ php -m [PHP Modules] xml tokenizer standard sockets session posix pcre overload mysql mbstring ctype [Zend Modules] |
Nota: La funzione extension_loaded() utilizza i nomi interni dei moduli per verificare se tale modulo è disponibile o meno. La maggior parte dei nomi interni sono scritti in minuscolo, ma possono esserci moduli con nomi contenenti lettere maiuscole. Fare attenzione che questa funzione distingue tra lettere minuscole e maiuscole
Vedere anche get_loaded_extensions(), get_extension_funcs(), phpinfo() e dl().
Restituisce il valore corrente della variabile di configurazione indicata da varname, oppure FALSE se si verifica un errore.
La funzione non restituisce informazioni di configurazione nel caso in cui il PHP è compilato, o caricato da un file di configurazione di Apache (tramite le direttive php3_configuration_option).
Per verificare se il sistema utilizza un file di configurazione, tentare di ricavare il valore di cfg_file_path. Se è disponibile significa che si utilizza un file di configurazione.
Vedere anche ini_get().
Restituisce il nome del proprietario dello script PHP.
Vedere anche getmyuid(), getmygid(), getmypid(), getmyinode() e getlastmod().
(PHP 4 >= 4.1.0, PHP 5)
get_defined_constants -- Restituisve un array associativo con i nomi di tutte le costanti ed i loro valoriQuesta funzione restituisce i nomi ed i valori di tutte le costanti attualmente definite. Queste includono sia quelle create dalle estensioni sia quelle create con la funzione define().
Ad esempio la linea seguente:
<?php print_r(get_defined_constants()); ?> |
visualizzerà il seguente elenco:
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 ) |
Vedere anche: defined(), get_loaded_extensions(), get_defined_functions() e get_defined_vars().
Questa funzione restituisce i nomi di tutte le funzioni definite all'interno del modulo indicato da module_name.
Nota: Il parametro module_name deve essere in minuscolo.
Ad esempio, il seguente comando:
<?php print_r(get_extension_funcs("xml")); print_r(get_extension_funcs("gd")); ?> |
visualizzerà l'elenco delle funzioni definite nei moduli xml e gd.
Vedere anche: get_loaded_extensions()
(PHP 4 >= 4.3.0, PHP 5)
get_include_path -- Restituisce il valore del parametro di configurazione include_pathRestituisce il valore di include_path.
Vedere anche ini_get(), restore_include_path(), set_include_path() e include().
Restituisce una matrice contenente i nomi di tutti i file che sono stati includi tramite le funzioni include(), include_once(), require() oppure require_once().
Lo script originario viene considerato come 'file incluso', pertanto sarà elencato insieme agli altri file referenziati da include() e simili.
File che sono inclusi più volte saranno elencati soltanto una volta sola
Nota: File inclusi tramite la direttiva auto_prepend_file non saranno inseriti nella matrice.
Esempio 1. Esempio di uso di get_included_files() del file (abc.php)
l'esempio visualizzerà:
|
Nota: In PHP 4.0.1pl2 e nelle versioni precedenti get_included_files() assumeva che i file inclusi avessero come estensione .php; file con altre estensioni erano ignorati. La matrice restituita da get_included_files() era una matrice associativa e riportava soltanto i file inclusi con include() e include_once().
Vedere anche include(), include_once(), require(), require_once() e get_required_files().
(PHP 4, PHP 5)
get_loaded_extensions -- Restituisce una matrice con il nome di tutti i moduli compilati e caricatiRestituisce una matrice con il nome di tutti i moduli compilati e caricati nell'interprete PHP.
Ad esempio la seguente linea:
<?php print_r(get_loaded_extensions()); ?> |
restituirà qualcosa simile a:
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 ) |
Vedere anche get_extension_funcs(), extension_loaded(), dl() e phpinfo().
(PHP 3 >= 3.0.6, PHP 4, PHP 5)
get_magic_quotes_gpc -- Restituisce l'attuale configurazione di magic quotes gpcRestituisce l'impostazione attuale della direttiva di configurazione magic_quotes_gpc (0 uguale a off, 1 per on).
Nota: Se la direttiva magic_quotes_sybase è impostata a ON, questa è prioritaria rispetto a magic_quotes_gpc. Pertanto, anche se get_magic_quotes() restituisce TRUE ne i doppi apici, ne i backslashes o i NUL saranno preceduti dal caratteri di escape. Lo saranno soltanto gli apici singoli. In questo caso saranno: ''
Si ricordi che magic_quotes_gpc non può essere impostata a runtime.
Esempio 1. Esempio di uso di get_magic_quotes_gpc()
|
Nell'ottica di scrittura di codice portabile (codice che funzioni in qualsiasi ambiente), o, se non si hanno i permessi di modifica del php.ini, è possibile disabilitare gli effetti della funzione da script. Questo può essere fatto in due modi, o con una impostazione da .htaccess (php_value magic_quotes_gpc 0), oppure aggiungendo il codice sottostante allo script.
Esempio 2. Disattivare magic quotes da script
|
Vedere anche addslashes(), stripslashes(), get_magic_quotes_runtime() e ini_get().
(PHP 3 >= 3.0.6, PHP 4, PHP 5)
get_magic_quotes_runtime -- Restituisce l'impostazione corrente della direttiva magic_quotes_runtimeRestituisce l'impostazione corrente della direttiva magic_quotes_runtime (0 per off, 1 per on).
Vedere anche get_magic_quotes_gpc() e set_magic_quotes_runtime().
Restituisce il valore della variabile d'ambiente varname, oppure FALSE in caso di errore.
Si può accedere all'elenco di tutte le variabili d'ambiente utilizzando phpinfo(). Si può avere una descrizione della maggior parte di queste alla pagina specifiche CGI , in modo particolare nella pagina delle variabili d'ambiente.
Nota: Questa funzione non gira in modalità ISAPI.
Vedere anche putenv().
Restituisce la data dell'ultima modifica alla pagina corrente. Il valore restituito è un timestamp, può essere elaborato con la funzione date(). Restituisce FALSE su errore.
Nota: Se si è interessati ad avere la data dell'ultima modifica di un'altro file, si consideri l'uso di filemtime().
Vedere anche date(), getmyuid(), getmygid(), get_current_user(), getmyinode(), getmypid() e filemtime().
Restituisce l'ID del gruppo del proprietario dello script, oppure FALSE per errore.
Vedere anche getmyuid(), getmypid(), get_current_user(), getmyinode() e getlastmod().
Restituisce l'inode dello script, oppure FALSE su errore.
Vedere anche getmygid(), getmyuid(), get_current_user(), getmypid() e getlastmod().
Nota: Questa funzione non è implementata su piattaforme Windows
Restituisce l'ID del processo PHP, oppure FALSE in caso errore.
Avvertimento |
Gli ID di processo non sono univoci, poichè sono sorgenti di bassa entropia. Si raccomanda di non basarsi sul pid nei contesti basati sulla sicurezza. |
Vedere anche getmygid(), getmyuid(), get_current_user(), getmyinode() e getlastmod().
Restituisce l'ID utente del proprietario dello script, oppure FALSE in caso di errore.
Vedere anche getmygid(), getmypid(), get_current_user(), getmyinode() e getlastmod().
Restituisce una matrcie associativa con l'accoppiata opzione / valore basata sulle opzioni attese indicate in options, oppure FALSE in caso di errore.
Sulle piattaforme che supportano la funzione C getopt_long, le opzioni 'lunghe' possono essere spcificate con il parametro longopts (dal PHP 4.3.0).
Il parametro options può contenere i seguenti elementi: caratteri individualie e caratteri seguiti dai due punti per indicare un'opzione seguita da un valore. Ad esempio, la stringa di opzione x identifica il parametro -x, e una stringa x: identifica un parametro ed il suo valore -x argument. Non è rilevante se il vlore è precedeuto da spazio.
Questa funzione restituisce l'accoppiata opzione / valore. Se l'opzione non ha valori, il valore restituito sarà FALSE.
Nota: Questa funzione non è implementata su piattaforme Windows
Questa funzione è un interfaccia a getrusage(2). Restituisce una matrice associativa contente le informazioni restituite dalla chiamata di sistema. Se il parametro who vale 1, getrusage()sarà eseguita con RUSAGE_CHILDREN.
Tutte le informazioni sono accessibili tramite i nomi dei campi documentati.
Nota: Questa funzione non è implementata su piattaforme Windows
Restituisce tutte le opzioni di configurazione come una matrice associativa. Se viene specificato il parametro opzionale extension La funzione restituirà solo le opzioni specifiche per quel modulo.
I nomi delle opzioni faranno da indice per la matrcie restituita, quindi gli elementi potranno essere: global_value (impostata in php.ini), local_value (impostata in ini_set() oppure in .htaccess), e access (il livello di accesso). Per avere informazioni su cosa siano i livello di accesso, vedere la pagina del manuale su modifiche di configurazione
Nota: Per le direttive è possibile avere più livelli di accesso, è per questo che access restituisce le appropriate maschere di bit.
Esempio 1. Esempio di uso di ini_get_all()
Parte dell'aoutput potrebbe essere:
|
Vedere anche ini_get(), ini_restore(), ini_set(), get_loaded_extensions() e phpinfo().
Restituisce il valore delle opzioni di configurazione. In caso di errore, tipo la richiesta per un valore inesistente, sarà restituita una stringa vuota.
Richieste per valori booleani: Nel file ini, il valore booleano off sarà restituito come stringa vuota o "0", mentre il valore on sarà restituito come "1".
Richieste per le dimensioni della memoria: Diversi parametri attinenti alle dimensioni di memoria, tipo upload_max_filesize sono registrati nel php.ini in notazione abbreviata. La funzione ini_get() restituirà l'esatto valore presente nel php.ini, e NON l'intero equivalente. L'esecuzione delle normali funzioni aritmetiche su questi valori potrà dare risultati inattesi. L'esempio seguente illustra come si possa convertire la notazione breve in byte in modo molto simile a come fa il PHP.
Esempio 1. Qualche esempio di ini_get()
Lo script produrrà:
|
Vedere anche: get_cfg_var(), ini_get_all(), ini_restore() e ini_set().
Ripristina il valore della data opzione di configurazione allo stato originale.
Vedere anche ini_get(), ini_get_all() e ini_set().
Imposta il valore di una data opzione di configurazione. Se l'operazione riesce restituisce il vecchio valore, oppure FALSE se fallisce. Le opzioni di configurazione manterranno il nuovo valore durante l'esecuzione dello script, e saranno ripristinate al termine dello stesso.
Non tutte le opzioni disponibili possono essere modificate da ini_set(). Nell'appendix vi è un elenco di tutte le opzioni disponibili.
Vedere anche: get_cfg_var(), ini_get(), ini_get_all() e ini_restore()
Non esiste una funzione main() tranne che nel sorgente PHP. Dal PHP 4.3.0 è stata introdotta nel sorgente una nuova tipologia di errore gestibile (php_error_docref). Una caratteristica di questa è quella di fornire il link alla pagina del manuale nel messaggio di errore nel caso in cui la direttiva html_errors (on per default) e docref_root (on per default dal PHP 4.3.2) siano impostate.
Qualche volta gli errori fanno riferimento alla pagina del manuale per la funzione main() ed è per questo che esiste questa pagina. Si prega di aggiungere nei commenti sottostanti quale funzione PHP ha cusato l'errore che punta a main(), e questo sarà prontamente corretto e documentato.
Tabella 1. Errori noti che punatno a main()
Nome della funzione | Non punta più qui da |
---|---|
include() | 4.3.2 |
include_once() | 4.3.2 |
require() | 4.3.2 |
require_once() | 4.3.2 |
Vedere anche html_errors e display_errors.
Restituisce la quantità di memoria, in byte, allocata dal PHP per lo script.
memory_get_usage() sarà disponibile solo se il PHP viene compilato con la configurazione --enable-memory-limit
Vedere anche memory_limit.
(PHP 4 >= 4.3.0, PHP 5)
php_ini_scanned_files -- Restituisce l'elenco dei file .ini leti dalla directory ini aggiuntivaphp_ini_scanned_files() restituisce un elenco separato da virgola dei file di configurazione letti dopo il php.ini. Questi file sono cercati nella directory specificata dall'opzione --with-config-file-scan-dir impostata al momento della compila.
La funzione restituisce la lista separata da virgola se riesce. Al contrario, se l'impostazione --with-config-files-scan-dir non è configurata la funzione resttuisce FALSE. Se un file non è riconoscibile, questo sarà inserito nell'elenco restituito, ma il PHP darà errore. Questo errore sarà visualizzato sia al momento della compila sia utilizzando php_ini_scanned_files().
La lista restituita comprende anche il percorso di include specificato in --with-config-file-scan-dir. Ogni virgola è seguita da un carattere di a capo (newline).
Questa funzione restituisce l'ID che può essere utlizzato per visualizzar il logo PHP pre-inserito.
Vedere anche phpinfo(), phpversion(), phpcredits() e zend_logo_guid().
(PHP 4 >= 4.0.1, PHP 5)
php_sapi_name -- Restituisce il tipo di interfaccia tra il PHP ed il server webphp_sapi_name() restituisce un testo minuscolo che descrive il tipo di interfaccia tra il PHP ed il server web (Server API, SAPI). In caso di CGI PHP, la stringa è "cgi", nel caso si usi mod_php per Apache, il testo sarà "apache" e così via.
(PHP 4 >= 4.0.2, PHP 5)
php_uname -- Restituisce informazioni sul sistema operativo su cui gira il PHPphp_uname() restituisce una stringa con la descrizione del sistema operativo su cui gira PHP. Se si desidera semplicemente il nome del sistema operativo, si utilizzi la costante PHP_OS, ma si ricordi che questa costante contiene il nome del sistema operativo su cui il PHP è stato compilato.
Sui sistemi Unix, la funzione passa a visualizzare il sistema operativo su cui il PHP è stato compilato, se non è in grado di determinare le imformazioni del sistema operativo su cui il PHP gira.
mode definisce quali informazioni debbano essere restituite:
'a': Questo è il default. Contiene tutte le modalità nella sequenza "s n r v m".
's': Nome del sistema operativo. Es. FreeBSD.
'n': Nome del server. Es. localhost.example.com.
'r': Nome del rilascio. Es. 5.1.2-RELEASE.
'v': Informazioni sulla versione. Varia molto in base al sistema operativo.
'm': Tipo di macchina. Es. i386.
Esempio 1. Alcuni esempi di php_uname()
|
Esistono alcune Costanti PHP predefinite che possono essere di aiuto, ad esempio:
Vedere anche phpversion(), php_sapi_name() e phpinfo().
Questa funzione visualizza la lista dei riconoscimenti per gli sviluppatori del PHP, dei vari moduli, eccetera. Genera il codice HTML appropriato per inserire l'informazine in una pagina. IL parametro opzionale flag, per default vale CREDITS_ALL, permette di selezionare di personalizzare la lista. Ad esempio per stampare l'elenco generale, utilizzare:
Se si vuole stampare l'elenco degli sviluppatori principali e del grupo di documentazione, in una pagina proprio conto, utilizzare:
E se si desidera inserire l'elenco completo nella propria pagina, utilizzare un codice simile al seguente:
<html> <head> <title>My credits page</title> </head> <body> <?php // some code of your own phpcredits(CREDITS_ALL - CREDITS_FULLPAGE); // some more code ?> </body> </html> |
Tabella 1. Flag pre-definiti phpcredits()
nome | descrizione |
---|---|
CREDITS_ALL | Tutta la lista dei meriti, equivale a CREDITS_DOCS + CREDITS_GENERAL + CREDITS_GROUP + CREDITS_MODULES + CREDITS_FULLPAGE. Genera una pagina HTML completa. |
CREDITS_DOCS | La lista del gruppo di documentazione |
CREDITS_FULLPAGE | Solitamente utilizzato in combinazione con altri flag. Indica che la pagina completa HTML deve essere stampata includendo le infomazioni di altri flag. |
CREDITS_GENERAL | Lista generale: design e progetto del linguaggio, autori del PHP 4.0 e del modulo SAPI. |
CREDITS_GROUP | Lista degli sviluppatori principali |
CREDITS_MODULES | Lista dei moduli e dei loro sviluppatori |
CREDITS_SAPI | Lista delle API server e dei loro sviluppatori |
Vedere anche phpinfo(), phpversion() e php_logo_guid().
Visualizza molte informazioni sullo stato corrente del PHP Queste includono informazioni sulle opzioni di compila del PHP, sui moduli, la versioen di PHP, informazioni sul server e sull'ambiente (se compilato come modulo), l'ambiente PHP, la versione di OS, percorsi, valori delle configurazioni base e attauli, intestazioni HTTP e la licenza del PHP.
Dato che ogni sistema ha una cofigurazione differente, phpinfo() viene comunemente utilizzato per verificare le impostazioni di configurazione e le variabili predefinite disponibili in un dato sistema. Inoltre, phpinfo() è utili come strumento di debug poichè visualizza tutti i dati EGPCS (Environment, GET, POST, Cookie, Server).
L'output può essere personalizzato passando una o più delle seguenti costanti sommate a livello di bit nel parametro opzionale what. Le costanti, o i rispettivi valori, possono essere combinati anche con l'operatore or.
Tabella 1. Opzioni di phpinfo()
Nome (constant) | Valore | Descrizione |
---|---|---|
INFO_GENERAL | 1 | La linea di configurazione, php.ini luogo, data di compila, Web Server, sistema e altro. |
INFO_CREDITS | 2 | PHP 4 Credits. Vedere anche phpcredits(). |
INFO_CONFIGURATION | 4 | Impostazioni correnti e di base delle opzioni PHP. Vedere anche ini_get(). |
INFO_MODULES | 8 | Moduli caricati e le loro impostazioni. Vedere anche get_loaded_extensions(). |
INFO_ENVIRONMENT | 16 | Variabili d'ambiente disponibili in $_ENV. |
INFO_VARIABLES | 32 | Visualizza tutte le variabili predefinite da EGPCS (Environment, GET, POST, Cookie, Server). |
INFO_LICENSE | 64 | Informazioni sulla licenza di PHP. Vedere anche faq sulla licenza. |
INFO_ALL | -1 | Visualizza tutto quanto descritto. Questo è il valore dei default. |
Nota: La visualizzazione di parte delle informazioni è disabilitata quando expose_php viene impostato a off. Queste includono i loghi PHP e Zend, e i credits.
Nota: La funzione phpinfo() produce un testo normale anzichè un file HTML quando è utilizzata in modalità CLI.
Vedere anche phpversion(), phpcredits(), php_logo_guid(), ini_get(), ini_set(), get_loaded_extensions() e la sezione sulle Variabili Predefinite.
Restituisce una stringa contenente la versione dell'interprete PHP.
Nota: Questa informazione è anche disponibile come costante predefinita PHP_VERSION.
Vedere anche version_compare(), phpinfo(), phpcredits(), php_logo_guid() e zend_version().
Imposta una variable nell'ambiente del server. La variabile d'ambiente esisterà solo per lòa durata dsello script Alla fine di questo l'ambiente sarà ripristinato allo stato originario.
L'impostazione di certe variabili d'ambiente può causare dei problemi di sicurezza. La direttiva safe_mode_allowed_env_vars contiene un'elenco separato da virgole di prefissi. In Mpodlità Sicura, l'utente può soltanto alterare le variabili d'ambiente il cui nome inizia con il prefisso indicato da questa direttiva. Per default, gli utenti sono abilitati ad impostare le variabili d'ambiente con inizino con PHP_ (ad esempio PHP_FOO=BAR). Nota: Se questa direttiva è vuota, il PHP permetterà all'utente di modificare QUALSIASI variabile d'ambiente!
La direttiva safe_mode_protected_env_vars contiene un elenco separato da virgola di variabili d'ambiente, che l'utente non può modificare tramite putenv(). Questa variabili saranno protette anche se safe_mode_allowed_env_vars autorizza la modifica a queste.
Avvertimento |
Queste impostazioni hanno effetto soltanto se safe-mode è impostato! |
Vedere anche getenv().
Ripristina il valore del parametro di configurazione include_path al valore impostato in php.ini
Esempio 1. Esempio di uso di restore_include_path()
|
Vedere anche ini_restore(), set_include_path(), get_include_path() e include().
Imposta il parametro di configurazione include_path per la durata dello script. La funzione restituisce la vecchia impostazione di include_path se ha successo, oppure FALSE se non riesce.
Vedere anche ini_set(), get_include_path(), restore_include_path() e include().
(PHP 3 >= 3.0.6, PHP 4, PHP 5)
set_magic_quotes_runtime -- Imposta il valore attuale di magic_quotes_runtimeImposta il valore del parametro di configurazione magic_quotes_runtime (0 per off, 1 per on).
Vedere anche get_magic_quotes_gpc() e get_magic_quotes_runtime().
Imposta il limite massimo in secondi di durata dello script. Se si raggiunge questo limite, lo script viene interrotto con un errore fatale. Per default questo limite è impostato a 30 secondi o, se esiste, al valore di max_execution_time nel php.ini. Se il parametro seconds viene impostato a zero, non si impone alcun limite di tempo.
Quando viene eseguita la funzione set_time_limit(), questa re-imposta il il contatore del tempo di esecuzione a zero. In altre parole, se il timeout è impostato al default di 30 secondi, e dopo 25 secondi di esecuzione si richiama la funzione con set_time_limit(20), lo script potrà girare per 45 secondi.
Avvertimento |
La funzione set_time_limit() non ha effetto quando il PHP gira in modalità sicura. Non esistono soluzioni alternative se non quella di disabilitare la modalità sicura o modificare il limite nel php.ini. |
Nota: La funzione set_time_limit() e la configurazione max_execution_time agiscono solo sull'esecuzione dello script in cui sono. Qualsiasi tempo perso in attività esterno allo script, tipo le chiamate di sistema tramite system(), operazioni sugli stream, query di database, ecc non sono incluse nel conteggio del tempo massimo che ha lo script per girare.
Vedere anche max_execution_time e la direttiva max_input_time.
(PHP 4 >= 4.1.0, PHP 5)
version_compare -- Confronta due stringhe contenenti il numero di versione di "PHP-standardized"version_compare() confronta due numeri di versione "PHP-standardized" . Questa funzione è utile quando si desideri che funzioni solo con alcune versioni di PHP.
La funzione version_compare() restituisce -1 se la prima verisone è minore della seconda, 0 se sono uguali, +1 se la sceonda è inferiore.
Per prima cosa la funzione sostituisce nella strina di versione le lettere _, - e + con un puntot . ed inserisce un punto . prima e dopo ogni carattere non numerico, in modo che, ad esempio, '4.3.2RC1' diventi ''4.3.2.RC.1'. Quindi divite il testo come se usasse explode('.', $ver). Poi confronta le parti cominciando da sinistra verso destra Se una parte contiene versioni speciali queste sono gestite nel seguente modo: dev < alpha = a < beta = b < RC < pl. In quest modo possono essere confrontati non solo differenti livelli di versioni quali '4.1' e '4.1.2', ma anche versioni di PHP in fase di sviluppo.
Specificando il terzo parametro opzionale operator si possono testare particolari relazioni. I possibili operatori sono: <, lt, <=, le, >, gt, >=, ge, ==, =, eq, !=, <>, ne. Utilizzando questi parametri, la funzione restituirà 1 se la relazione è una di quelle specificate dall'operatore, altrimenti 0.
Questa funzioen restituisce l'ID che può essere utilizzato per visualizzare il logo Zend usando l'immagine inserita nel PHP.
Vedere anche php_logo_guid().
Restituisce una stringa contenente il numero di versione dell'engine Zend.
Vedere anche phpinfo(), phpcredits(), php_logo_guid() e phpversion().
Questo modulo contiene un'interfaccia alle funzioni definite dallo standard IEEE 1003.1 (POSIX.1) che non sono accessibili in altro modo. Ad esempio lo standard POSIX.1 definisce le funzioni open(), read(), write() e close() che tradizionalmente sono parte di PHP 3 da lungo tempo. Altre funzioni più specifiche del sistema operativo non sono disponibili, e quindi con questo modulo si cerca di porre rimedio a questa mancanza dando un facile accesso a queste funzioni.
Avvertimento |
Con le funzioni POSIX si possono ricavare informazioni sensibili tipo posix_getpwnam() e simili. Nessuna delle funzioni POSIX esegue alcun tipo di controllo di accesso quando è abilitata la modalità sicura. Pertanto è vivamente consigliato di disabilitare l'estensione POSIX (impostare --disable-posix nella linea di configurazione) se si opera con la modalità sicura. |
Nota: Questo modulo non è disponibile su piattaforme Windows.
Le funzioni POSIX sono abilitate per default. Si possono disabilitare con --disable-posix.
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Check whether the file exists.
Check whether the file exists and has read permissions.
Check whether the file exists and has write permissions.
Check whether the file exists and has execute permissions.
Block special file
Character special file
FIFO (named pipe) special file
Normal file
Socket
Nota: These constants are available since PHP 5.1.0. Please also note that some of them may not be available in your system.
posix_access() checks the user's permission of a file.
Nota: Quando safe-mode è abilitato, PHP controlla che i file o le directory sulle quali si sta andando a lavorare, abbiano lo stesso UID dello script che è in esecuzione.
The name of the file to be tested.
A mask consisting of one or more of POSIX_F_OK, POSIX_R_OK, POSIX_W_OK and POSIX_X_OK. Defaults to POSIX_F_OK.
POSIX_R_OK, POSIX_W_OK and POSIX_X_OK request checking whether the file exists and has read, write and execute permissions, respectively. POSIX_F_OK just requests checking for the existence of the file.
Esempio 1. posix_access() example This example will check if the $file is readable and writable, otherwise will print an error message.
|
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
(PHP 4 >= 4.2.0, PHP 5)
posix_get_last_error -- Recupera il numero di errore dell'ultima funzione posix non riuscitaRestituisce il codice di errore impostato dall'ultima funzione posix che non è terminata correttamente. Se non vi sono errori la funzione restituisce 0. Se si desidera il messaggio corrispondente al codice utilizzare posix_strerror().
Vedere anche posix_strerror().
La funzione posix_getcwd() restituisce il percorso assoluto della corrente directory di lavoro.La funzioneposix_getcwd() restituisce FALSE se si verifica un errore.
(PHP 3 >= 3.0.10, PHP 4, PHP 5)
posix_getegid -- Restituisce l'ID del gruppo per il processo correnteLa funzione restituisce l'ID del gruppo per il processo corrente. Vedere anche posix_getgrgid() per dettagli su come convertire il numero nel nome effettivo del gruppo.
(PHP 3 >= 3.0.10, PHP 4, PHP 5)
posix_geteuid -- Restituisce l'ID dell'utente per il processo correnteRestituisce il valore numerico dell'ID dell'utente per il processo corrente. Vedere posix_getpwuid() per maggiori dettagli su come convertire il numero nel nome dell'utente.
(PHP 3 >= 3.0.10, PHP 4, PHP 5)
posix_getgid -- Restituisce il reale ID del gruppo per il processo correnteLa funzione restituisce il reale ID del gruppo del processo. Vedere anche posix_getgrgid() per dettagli su come convertire il numero nel nome effettivo del gruppo.
(PHP 3 >= 3.0.13, PHP 4, PHP 5)
posix_getgrgid -- Restituisce informazioni su un gruppo dato il suo IDRestituisce un array con le informazioni del gruppo, oppure FALSE se si verifica un errore. Se gid non è un numero la funzione restituisce NULL e genera un errore di tipo E_WARNING.
Nota: A partire da PHP 4.2.0, la funzione restituisce l'elenco dei membri del gruppo in un array ordinato per nome. Precedentemente si restituiva un intero (il numero dei membri del gruppo) ed i nomi dei membri doveva essere recuperato tramite l'indice numerico.
Vedere anche posix_getegid(), filegroup(), stat() e safe_mode_gid.
(PHP 3 >= 3.0.13, PHP 4, PHP 5)
posix_getgrnam -- Restituisce le informazioni di un gruppo dato il nome
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
La funzione restituisce una matrcie di interi contenente gli ID dei gruppi per il processo corrente. Vedere anche posix_getgrgid() per informazioni su come convertire questo numero nel nome del gruppo.
Restituisce il nome dell'utente proprietario del processo corrente. Vedere posix_getpwnam() per dettagli su come ottenere maggiori informazioni sull'utente.
(PHP 3 >= 3.0.10, PHP 4, PHP 5)
posix_getpgid -- Restituisce l'id del gruppo del processo per il controllo dei jobLa funzione restituisce l'id del gruppo per il processo indicato da pid.
Questa non è una funzione POSIX, ma è comune sui sistemi BSD e System V. Se il vostro sistema non supporta questa funzione, la funzione PHP restituirà sempre FALSE.
(PHP 3 >= 3.0.10, PHP 4, PHP 5)
posix_getpgrp -- Restituisce l'identificatore di gruppo per il processo correnteRestituisce l'identificatore del gruppo di processo per il processo corrente. Vedere le pagine del manuale del vostro sistema POSIX relativamente a POSIX.1 e getpgrp(2) per avere maggiori dettagli sui gruppi di processo.
Restituisce l'ID del processo genitore per il processo corrente.
La funzione restituisce un array associativo contenente le informazioni sull'utente con nome specificato nel parametro username.
Gli elementi dell'array sono:
Tabella 1. Array delle informazioni utente
Elemento | Descrizione |
---|---|
name | L'elemento name solitamente contiene il nome dell'utente. Questo è un nome corto, di solito meno di 16 caratteri, non il nome reale, completo, dell'utente. Questo dovrebbe essere uguale al parametro username passato alla funzione e quindi ridondante. |
passwd | L'elemento passwd contiene la password dell'utente in formato criptato. Spesso, ad esempio nei sistemi utilizzano password "shadow", vengono restituiti degli asterischi. |
uid | ID dell'utente in formato numerico. |
gid | ID del gruppo a cui appartiene l'utente. Utilizzare la funzione posix_getgrgid() per ottenere il nome del gruppo e l'elenco dei suoi membri. |
gecos | GECOS è un termine obsoleto che si riferisce a campi del comando finger su sistemi Honeywell. Tuttavia il campo è sopravvissuto ed il suo contenuto è stato formalizzato in POSIX. Il campo contiene le informazioni separate da virgola relative a nome completo dell'utente, numero telefonico dell'ufficio, numero dell'ufficio, numero telefonico di casa. In molti sistemi è disponibile solo il nome completo dell'utente. |
dir | Questo elemento contiene il percorso assoluto alla home directory dell'utente. |
shell | L'elemento shell contiene il percorso assoluto alla shell di default per l'utente. |
(PHP 3 >= 3.0.13, PHP 4, PHP 5)
posix_getpwuid -- Restituisce le informazioni di un utente dato il suo IDLa funzione restituisce un array associativo contenente le informazioni sull'utente il cui ID è stato fornito nel parametro uid.
Gli elementi dell'array sono:
Tabella 1. Array delle informazioni utente
Elemento | Descrizione |
---|---|
name | L'elemento name solitamente contiene il nome dell'utente. Questo è un nome corto, di solito meno di 16 caratteri, non il nome reale, completo, dell'utente. Questo dovrebbe essere uguale al parametro username passato alla funzione e quindi ridondante. |
passwd | L'elemento passwd contiene la password dell'utente in formato criptato. Spesso, ad esempio nei sistemi utilizzano password "shadow", vengono restituiti degli asterischi. |
uid | ID dell'utente in formato numerico. |
gid | ID del gruppo a cui appartiene l'utente. Utilizzare la funzione posix_getgrgid() per ottenere il nome del gruppo e l'elenco dei suoi membri. |
gecos | GECOS è un termine obsoleto che si riferisce a campi del comando finger su sistemi Honeywell. Tuttavia il campo è sopravvissuto ed il suo contenuto è stato formalizzato in POSIX. Il campo contiene le informazioni separate da virgola relative a nome completo dell'utente, numero telefonico dell'ufficio, numero dell'ufficio, numero telefonico di casa. In molti sistemi è disponibile solo il nome completo dell'utente. |
dir | Questo elemento contiene il percorso assoluto alla home directory dell'utente. |
shell | L'elemento shell contiene il percorso assoluto alla shell di default per l'utente. |
(PHP 3 >= 3.0.10, PHP 4, PHP 5)
posix_getrlimit -- Restituisce informazioni sui limiti delle risorse del sistema
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
La funzione restituisce il sid per il processo indicato in pid. Se pid è impostato a 0, la funzione restituisce il sid del processo corrente.
Questa non è una funzione POSIX, ma è comune sui sistemi System V. Se il vostro sistema non supporta questa funzione, la funzione PHP restituirà sempre FALSE.
(PHP 3 >= 3.0.10, PHP 4, PHP 5)
posix_getuid -- Restituisce il reale ID dell'utente per il processo correnteLa funzione restituisce il reale ID dell'utente per il processo corrente. Vedere anche posix_getpwuid() per dettagli su come convertire questo nel nome dell'utente.
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
La funzione invia il segnale sig al processo il cui identificatore è pid. La funzione restituisce FALSE, se non riesce ad inviare il segnale, TRUE altrimenti.
Vedere anche anche kill(2) nel manuale del vostro sistema POSIX per avere informazioni sui processi con identificatore negativo, lo speciale pid 0, -1 ed il segnale 0.
(PHP 3 >= 3.0.13, PHP 4, PHP 5)
posix_mkfifo -- Crea un file speciale di tipo fifo (una pipe nominata)La funzione posix_mkfifo() un file speciale FIFO che esiste nel file system e agisce come teminale per comunicazioni bidirezionali tra processi.
Il secondo parametro, mode deve essere passato con notazione ottale (ad esempio 0644). I permessi della nuova FIFO dipendono anche dall'impostazione corrente di umask(). I permessi del file creato sono (mode & ~umask).
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: Quando safe-mode è abilitato, PHP controlla che la directory nella quale si sta lavorando, abbia lo stesso UID dello script che è in esecuzione.
posix_mknod() creates a special or ordinary file.
The file to create
This parameter is constructed by a bitwise OR between file type (one of the following constants: POSIX_S_IFREG, POSIX_S_IFCHR, POSIX_S_IFBLK, POSIX_S_IFIFO or POSIX_S_IFSOCK) and permissions.
The major device kernel identifier
The minor device kernel identifier
La funzione imposta l'effettivo ID di gruppo per il processo. Poichè questa è una funzione privilegiata occorre avere gli opportuni privilegi (solitamente di root) per poterla eseguire.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento..
Imposta lo user ID per il processo corrente. Poichè questa è una funzione privilegiata occorre avere gli opportuni privilegi (solitamente di root) per poterla eseguire.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere anche posix_setgid().
La funzione imposta il reale ID di gruppo per il processo. Poichè questa è una funzione privilegiata occorre avere gli opportuni privilegi (solitamente di root) per poterla eseguire. L'ordine corretto per richiamare la funzione è: posix_setgid() prima, posix_setuid() poi.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
La funzione permette al processo identificato da pid di unirsi al gruppo di processi identificati da pgid. Vedere POSIX.1 e setsid(2) nel manuale del vostro sistema POSIX per avere maggiori dettagli sui gruppi di processi e sul controllo dei job. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
La funzione rende il processo corrente leader di sessione. Vedere POSIX.1 e setsid(2) nelle pagine del manuale del vostro sistema POSIX per maggiori dettagli sui gruppi di processi e sul controllo dei job. La funzione restituisce l'id di sessione.
La funzione imposta il reale ID di utente per il processo corrente. Questa è una funzione privilegiata e pertanto richiede gli opportuni privilegi (di solito root) per potere essere eseguita.
Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere anche posix_setgid().
(PHP 4 >= 4.2.0, PHP 5)
posix_strerror -- Recupera il messaggio di errore di un dato codice di erroreLa funzione restiruisce il messaggio di erore POSIX associato aa un dato codice di errore. Se il parametro errno è impostato a 0, viene restituita la stringa "Success". Utilizzare la funzione posix_get_last_error() per ottenere il codice di errore.
Vedere anche posix_get_last_error().
Restituisce una serie di stringhe con le imformazioni sull'utilizzo di CPU del processo. L'indice della matrice è:
ticks - il numero di ticks dall'ultimo rebbot.
utime - user time utilizzato dal processo.
stime - system time utilizzato dal processo.
cutime - user time uutilizzato dal processo e dai suoi figli.
cstime - system time uutilizzato dal processo e dai suoi figli.
Avvertimento |
Questa funzione non è affidabile nell'uso, può restituire valori negativi per tempi molto elevati. |
Avvertimento |
Questa funzione, al momento non è documentata; è disponibile soltanto la lista degli argomenti. |
La funzione restituisce un array con informazioni sul sistema. Le chiavi dell'array sono:
sysname - nome del sistema operativo (es. Linux)
nodename - nome del sistema (es. valiant)
release - release del sistema operativo (es. 2.2.10)
version - versione del sistema operativo (es. #4 Tue Jul 20 17:01:36 MEST 1999)
machine - architettura del sistema (es. i586)
domainname - nome del dominio DNS (es. example.com)
La chiave domainname è una estensione GNU e non è parte di POSIX.1, quindi questo campo è disponibile soltanto su sistemi GNU o quando si utilizza la libc di GNU.
Lo standard POSIX richiede di non fare affidamento sul formato dei valori restituiti, ad esempio non aspettarsi di avere sempre tre cifre nel numero di versione.
Suggerimento: Il PHP, utilizzando le funzioni PCRE, supporta anche le espressioni regolari con una sintassi compatibile con Perl. Queste funzioni supportano riconoscimenti "pigliatutto", asserzioni, criteri condizionali, e diverse altre caratteristiche che non sono supportate dalla sintassi POSIX estesa.
Avvertimento |
Queste funzioni per l'espressioni regolari non sono binary-safe. Le funzioni PCRE lo sono. |
In PHP, le espressioni regolari sono utilizzate per complesse manipolazioni di stringhe. Le espressioni regolari utilizzate da PHP sono di tipo POSIX esteso così come definito in POSIX 1003.2. Per una descrizione completa delle espressione regolari POSIX, vedere la pagina del manuale di regex inclusa nella directory di regex nella distribuzione di PHP. Questa è in formato man, pertanto per poterle leggere occorre eseguire man /usr/local/src/regex/regex.7.
Avvertimento |
Non variare TYPE se non si sa cosa si sta facendo. |
Per abilitare il supporto a regex occorre configurare il PHP con --with-regex[=TYPE]. TYPE può essere: system, apache, php. Per default si usa php.
La versione per Windows di PHP ha già compilato il supporto per questo modulo. Non occorre caricare alcun modulo addizionale per potere utilizzare queste funzioni.
Questa estensione non definisce alcuna direttiva di configurazione in php.ini
Esempio 1. Esempi di espressione regolare
|
Per maggiori dettagli sulle espressioni regolari compatibili con Perl vedere il capitolo sulle funzioni PCRE. La funzione fnmatch() fornisce il riconoscimento dei caratteri jolly tipici della linea di comando.
La funzione ricerca all'interno del parametro stringa sottostringhe che incrocino con le condizioni specificate in espressione_regolare. Quando sono trovate, queste vengono sostituite con il testo specificato in testo_sostitutivo.
La funzione restituisce la stringa modificata. (Ciò implica che se non ci sono sottostringhe che soddisfino l' espressione regolare, la funzione restituisce la stringa originaria).
Se in espressione_regolare si specificano delle sottostringhe utilizzando le parentesi, anche nel campo testo_sostitutivo si possono specificare delle sottostringhe di formato \\digit , che saranno sostituite dalle stringhe soddisfacenti la digit'esima condizione posta tra parentesi; \\0 indica l'intera stringa. La funzione prevede che si possano utlizzare fino a nove sottostringhe. E' previsto che le parentesi siano nidificate, in questo caso il conteggio si basa sulle parentesi aperte.
Se nessuna parte di stringa viene riconosciuta, il parametro viene restituito invariato.
Come esempio il seguente frammento di codice visualizzerà la frase "Questo fu un test" tre volte:
Un aspetto a cui occorre prestare attenzione riguarda l'uso di numero intero per il parametro testo_sostitutivo, si potrebbero ottenere risultati diversi da quanto atteso. Questo accade perchè la funzione ereg_replace() interpreta il numero come posizione ordinale di un carattere comportandosi di conseguenza. Ad esempio:
Esempio 2. ereg_replace() esempio
|
Suggerimento: Poichè utilizza espressioni regolari con sintassi compatibile con Perl, preg_replace(), è spesso una alternativa più veloce a ereg_replace().
Vedere anche ereg(), eregi(), eregi_replace(), str_replace() e preg_match().
Nota: Poichè utilizza espressioni regolari con sintassi compatibile con PERL, preg_match(), è spesso una alternativa più veloce a ereg().
Ricerca in stringa testi che possano incrociarsi con l'espressione regolare indicata in espressione_regolare distinguendo tra lettere minuscole e maiuscole.
Se le parti di testo poste tra parentesi nel campo espressione_regolare sono incontrate nella stringa e la funzione viene chiamata utilizzando il terzo parametro regs, il testo riconosciuto sarà memorizzato nella matrice regs. L'indice 1, $regs[1], conterrà la sottostringa che parte dalla prima parentesi sinistra; $regs[2] conterrà la sottostringa a partire dalla seconda e così via. L'indice 0, $regs[0], conterrà la copia completa della stringa riconosciuta.
Nota: Fino alla versione di PHP 4.1.0 compresa, $regs conterrà esattamente 10 elementi, anche se il numero delle stringhe riconosciute sia maggiore o minore di 10. Ciò non limita ereg() nella ricerca di più sottostringhe. Se non si riconoscono testi, $regs non sarà modificato da ereg().
La funzione ritorna la lunghezza della stringa riconosciuta se le ricerche previste da espressione_regolare sono riscontrate in stringa. Viene restituito FALSE se non si hanno riscontri, oppure si verificano degli errori. Se non si fornisce il parametro opzionale regs oppure la lunghezza della stringa riconosciuta è 0, questa funzione restituisce 1.
Nel seguente frammento di codice, una data in formato ISO (YYYY-MM-DD) verrà visualizzata nel formato DD.MM.YYYY:
Vedere anche eregi(), ereg_replace(), eregi_replace(), preg_match(), strpos() e strstr().
(PHP 3, PHP 4, PHP 5)
eregi_replace -- Sostituzioni con espressioni regolari senza distinzione tra maiuscole e minuscoleQuesta funzione è identica a ereg_replace(), tranne che per il fatto che non distingue tra lettere maiuscole e lettere minuscole.
Vedere anche ereg(), eregi() e ereg_replace().
(PHP 3, PHP 4, PHP 5)
eregi -- Riconoscimento di espressioni regolari senza distinzione tra maiuscole e minuscoleQuesta funzione è identica a ereg(), tranne che per il fatto che non distingue tra lettere maiuscole e lettere minuscole.
Vedere anche ereg(), ereg_replace(), eregi_replace(), stripos() e stristr().
(PHP 3, PHP 4, PHP 5)
split -- Suddivide una stringa in una matrice utilizzando le espressioni regolariSuggerimento: Poichè utilizza espressioni regolari con sintassi compatibile con Perl, preg_split(), è spesso una alternativa più veloce a split(). Se non si ha necessità delle capacità delle espressioni regolari, è più veloce l'utilizzo di explode(), che non richiede l'overhead del motore delle espressioni regolari.
La funzione restituisce una matrice di stringhe che sono delle sottostringhe del parametro stringa. Queste sono ottenute suddividendo il parametro secondo i limiti indicati dal parametro sensibile alle maiuscole espressione_regolare. Se viene specificato il parametro limite, la funzione restituisce una matrice con un numero di elementi al massimo pari a limite. L'ultimo elemento della matrice contiene la parte restante del parametro stringa fornito. Se si verificano errori la funzione split() restituisce FALSE.
Esempio di come estrapolare i primi 4 campi da una linea del file /etc/passwd:
Se nella stringa passata vi sono n occorrenze del parametro espressione_regolare, la matrice restituita conterrà n+1 elementi. Invece, nel caso in cui non vi siano occorrenze della espressione_regolare, la matrice restituita conterrà un solo elemento. Ovviamente questo è valido anche nel caso in cui il parametro stringa è vuoto.
Nell'esempio che segue, si vedrà come analizzare una data il cui testo può contenere barre, punti o trattini:
Gli utenti che cercano un modo di emulare il comportamento di Perl @chars = split('', $str), sono rimandati agli esempi di preg_split().
Occorre fare attenzione al fatto che il parametro espressione_regolare è una espressione regolare e, pertanto, se si devono riconoscere caratteri che sono considerati speciali per le espressioni regolari, occorre codificarli con i caratteri di escape. Se si ritiene che la funzione split () ( o anche le altre funzioni derivate da regex ) si comportino in modo anomalo, è opportuno leggere il file regex.7, incluso nella cartella regex/ della distribuzione di PHP. Questo file è nel formato del manuale di unix (man), pertanto per visualizzarlo occorre eseguire il comando man /usr/local/src/regex/regex.7.
Vedere anche: preg_split(), spliti(), explode(), implode(), chunk_split() e wordwrap().
(PHP 4 >= 4.0.1, PHP 5)
spliti -- Suddivide una stringa in una matrice usando le espressioni regolari senza distinguere tra maiuscole e minuscoleQuesta funzione ha un comportamento identico a split() tranne che per il fatto di non distinguere tra lettere maiuscole e minuscole. characters.
Il seguente esempio suddivide una stringa utilizzando la lettera 'a' come separatore:
Vedere anche preg_split(), split(), explode(), e implode().
(PHP 3, PHP 4, PHP 5)
sql_regcase -- Genera una espressione regolare per riconoscimenti senza distinguere tra maiuscole e minuscoleLa funzione restituisce una espressione regolare che sia in grado di riconoscere il parametro stringa, a prescindere dalle lettere maiuscole minuscole. L'espressione regolare restituita corrisponde a stringa con ciascun carattere alfabetico riportato tra parentesi. Ogni parentesi contiene il singolo carattere in maiuscolo ed in minuscolo. I rimanenti caratteri sono riportati immutati.
Questa funzione torna utile quando si devono ottenere espressioni regolari non distinguono tra lettere maiuscole e minuscole da passare a prodotti che supportano espressioni regolari che distinguono il tipo di lettera.
Il database PostgreSQL è un prodotto OpenSource ed è disponibile gratuitamente. Postgres, sviluppato originariamente nel Dipartimento di Informatica dell'Università di Berkeley, ha anticipato molti dei concetti su oggetti e relazioni che ora stanno diventando disponibili in alcuni database commerciali. Postgres fornisce supporto per il linguaggio SQL/92/SQL99, transazioni, integrità referenziale, stored procedures ed estensibilità dei tipi. PostgreSQL è un discendente open source dell'originario codice di Berkeley.
Per utilizzare il supporto a PostgreSQL, occorre PostgreSQL 6.5 o versioni più recenti. PostgreSQL 7.0 o successivi permettono di abilitare tutte le funzionalità di questo modulo. PostgreSQL ammette molte codifiche di carattere, tra cui la codifica multibyte. La versione corrente e maggiori informazioni su PostgreSQL sono disponibili su http://www.postgresql.org/ e http://techdocs.postgresql.org/.
In order to enable PostgreSQL support, --with-pgsql[=DIR] is required when you compile PHP. DIR is the PostgreSQL base install directory, defaults to /usr/local/pgsql. If shared object module is available, PostgreSQL module may be loaded using extension directive in php.ini or dl() function.
Il comportamento di queste funzioni è influenzato dalle impostazioni di php.ini.
Tabella 1. PostgreSQL configuration options
Name | Default | Changeable | Changelog |
---|---|---|---|
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 | Available since PHP 4.2.0. |
pgsql.ignore_notice | "0" | PHP_INI_ALL | Available since PHP 4.3.0. |
pgsql.log_notice | "0" | PHP_INI_ALL | Available since PHP 4.3.0. |
Breve descrizione dei parametri di configurazione.
Whether to allow persistent Postgres connections.
The maximum number of persistent Postgres connections per process.
The maximum number of Postgres connections per process, including persistent connections.
Detect broken persistent links with pg_pconnect(). Needs a little overhead.
Whether or not to ignore PostgreSQL backend notices.
Whether or not to log PostgreSQL backends notice messages. The PHP directive pgsql.ignore_notice must be off in order to log notice messages.
Avvertimento |
L'utilizzo del modulo PostgreSQL con PHP 4.0.6 non è raccomandato a causa di un bug nella gestione dei messaggi. Si usi PHP 4.1.0 o successivi. |
Avvertimento | ||||||||||||||||||||||||||||||||||||||||||||
I nomi delle funzioni relative a PostgreSQL verranno cambiate a partire dalla versione 4.2.0 per conformarsi agli standard di sviluppo attuali. La maggior parte dei nuovi nomi avrà underscore aggiuntivi, per esempio pg_lo_open(). Alcune funzioni verranno rinominate per dare consistenza. Per esempio pg_exec() diventerà pg_query(). I vecchi nomi potranno essere usati nella versione 4.2.0 e in alcune versioni successive alla 4.2.0, ma potranno essere cancellati in futuro. Tabella 2. Nomi di funzione cambiati
La vecchia sintassi di pg_connect()/pg_pconnect() sarà deprecata per supportare, in futuro, connessioni asincrone. Si usi una stringa di connessione con pg_connect() e pg_pconnect(). |
Non tutte le funzioni sono supportate su tutte le architetture. Dipende dalla versione di libpq (L'interfaccia Client C per PostgreSQL) e da come libpq è compilato. Se c'è una funzione mancante, libpq non supporta la feature richiesta per quella funzione.
È importante usare versioni di libpq più recenti rispetto al Server PostgreSQL al quale ci si vuole collegare. Se si usa una versione di libpq più vecchia rispetto al Server PostgreSQL al quale ci si vuole collegare, si andrà probabilmente incontro a problemi.
Fin dalla versione 6.3 (03/02/1998) PostgreSQL usa gli unix domain socket di default. La porta TCP, di default, NON verrà aperta. La tabella sottostante descrive queste nuove possibilità di connessione. Questo socket può essere trovato in /tmp/.s.PGSQL.5432. Questa opzione può venire abilitata con la flag '-i' da postmaster e il suo significato è: "ascolta i socket TCP/IP così come gli Unix domain socket".
Tabella 3. Postmaster e PHP
Postmaster | PHP | Status |
---|---|---|
postmaster & | pg_connect("dbname=NomeMioDatabase"); | OK |
postmaster -i & | pg_connect("dbname=NomeMioDatabase"); | OK |
postmaster & | pg_connect("host=localhost dbname=NomeMioDatabase"); | 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=NomeMioDatabase"); | OK |
Si può stabilire una connessione al server PostgreSQL usando le seguenti coppie di valori impostate nella stringa di comando: $conn = pg_connect("host=IlMioHost port=LaMiaPorta tty=myTTY options=LeMieOpzioni dbname=IlMioDB user=IlMioUtente password=LaMiaPassword ");
L'uso della sintassi in uso precedentemente: $conn = pg_connect ("host", "port", "options", "tty", "dbname") è deprecato.
Le variabili d'ambiente modificano il comportamento server/client di PostgreSQL. Per esempio, il modulo PostgreSQL si baserà sulla variabile PGHOST quando il nome dell'host è omesso nella stringa di connessione. Le variabili d'ambiente riconosciute sono diverse da versione a versione. Consultare il Manuale del Programmatore PostgreSQL (libpq - Variabili d'Ambiente) per ulteriori dettagli.
Assicurarsi di aver impostato le variabili d'ambiente per l'utente appropriato. Usare $_ENV o getenv() per controllare quali variabili d'ambiente sono disponibili al processo corrente.
Queste costanti sono definite da questa estensione e sono disponibili solo se l'estensione è stata compilata nel PHP o se è stata caricata dinamicamente a runtime.
Passed to pg_fetch_array(). Return an associative array of field names and values.
Passed to pg_fetch_array(). Return a numerically indexed array of field numbers and values.
Passed to pg_fetch_array(). Return an array of field values that is both numerically indexed (by field number) and associated (by field name).
Passed to pg_connect() to force the creation of a new connection, rather then re-using an existing identical connection.
Returned by pg_connection_status() indicating that the database connection is in an invalid state.
Returned by pg_connection_status() indicating that the database connection is in a valid state.
Passed to pg_lo_seek(). Seek operation is to begin from the start of the object.
Passed to pg_lo_seek(). Seek operation is to begin from the current position.
Passed to pg_lo_seek(). Seek operation is to begin from the end of the object.
Returned by pg_result_status(). The string sent to the server was empty.
Returned by pg_result_status(). Successful completion of a command returning no data.
Returned by pg_result_status(). Successful completion of a command returning data (such as a SELECT or SHOW).
Returned by pg_result_status(). Copy Out (from server) data transfer started.
Returned by pg_result_status(). Copy In (to server) data transfer started.
Returned by pg_result_status(). The server's response was not understood.
Returned by pg_result_status(). A nonfatal error (a notice or warning) occurred.
Returned by pg_result_status(). A fatal error occurred.
Returned by pg_transaction_status(). Connection is currently idle, not in a transaction.
Returned by pg_transaction_status(). A command is in progress on the connection. A query has been sent via the connection and not yet completed.
Returned by pg_transaction_status(). The connection is idle, in a transaction block.
Returned by pg_transaction_status(). The connection is idle, in a failed transaction block.
Returned by pg_transaction_status(). The connection is bad.
Passed to pg_result_error_field(). The severity; the field contents are ERROR, FATAL, or PANIC (in an error message), or WARNING, NOTICE, DEBUG, INFO, or LOG (in a notice message), or a localized translation of one of these. Always present.
Passed to pg_result_error_field(). The SQLSTATE code for the error. The SQLSTATE code identifies the type of error that has occurred; it can be used by front-end applications to perform specific operations (such as error handling) in response to a particular database error. This field is not localizable, and is always present.
Passed to pg_result_error_field(). The primary human-readable error message (typically one line). Always present.
Passed to pg_result_error_field(). Detail: an optional secondary error message carrying more detail about the problem. May run to multiple lines.
Passed to pg_result_error_field(). Hint: an optional suggestion what to do about the problem. This is intended to differ from detail in that it offers advice (potentially inappropriate) rather than hard facts. May run to multiple lines.
Passed to pg_result_error_field(). A string containing a decimal integer indicating an error cursor position as an index into the original statement string. The first character has index 1, and positions are measured in characters not bytes.
Passed to pg_result_error_field(). This is defined the same as the PG_DIAG_STATEMENT_POSITION field, but it is used when the cursor position refers to an internally generated command rather than the one submitted by the client. The PG_DIAG_INTERNAL_QUERY field will always appear when this field appears.
Passed to pg_result_error_field(). The text of a failed internally-generated command. This could be, for example, a SQL query issued by a PL/pgSQL function.
Passed to pg_result_error_field(). An indication of the context in which the error occurred. Presently this includes a call stack traceback of active procedural language functions and internally-generated queries. The trace is one entry per line, most recent first.
Passed to pg_result_error_field(). The file name of the PostgreSQL source-code location where the error was reported.
Passed to pg_result_error_field(). The line number of the PostgreSQL source-code location where the error was reported.
Passed to pg_result_error_field(). The name of the PostgreSQL source-code function reporting the error.
Passed to pg_set_error_verbosity(). Specified that returned messages include severity, primary text, and position only; this will normally fit on a single line.
Passed to pg_set_error_verbosity(). The default mode produces messages that include the above plus any detail, hint, or context fields (these may span multiple lines).
Passed to pg_set_error_verbosity(). The verbose mode includes all available fields.
Passed to pg_result_status(). Indicates that numerical result code is desired.
Passed to pg_result_status(). Indicates that textual result command tag is desired.
Passed to pg_convert(). Ignore default values in the table during conversion.
Passed to pg_convert(). Use SQL NULL in place of an empty string.
Passed to pg_convert(). Ignore conversion of NULL into SQL NOT NULL columns.
A partire da PostgreSQL 7.1.0, il tipo di dato text ha 1GB come dimensione massima. Nelle versioni più vecchie di PostgreSQL il tipo di dato text è limitato dalla dimensione del block. (Default 8KB. Massimo 32KB, specificato al momento della compilazione)
Per usare l'interfaccia large object (lo), è necessario includerla entro un blocco di una transazione. Un blocco di transazione inizia con un comando SQL BEGIN e se la transazione è stata valida, termina con COMMIT o END. Se la transazione fallisce, essa deve venire chiusa con ROLLBACK o ABORT.
Esempio 2. Utilizzare Large Objects
|
(PHP 4 >= 4.2.0, PHP 5)
pg_affected_rows -- Restituisce il numero delle tuple coinvolte dall'ultimo comandopg_affected_rows() restituisce il numero di tuple (istanze/record/righe) coinvolte dalle query INSERT, UPDATE, e DELETE eseguite da pg_query(). Se nessuna tupla è stata modificata da questa funzione, restituisce 0.
Nota: Questa funzione si chiamava pg_cmdtuples().
Vedere anche pg_query() e pg_num_rows().
pg_cancel_query() annulla una query asincrona inviata da pg_send_query(). Non è possibile annullare query eseguite attraverso pg_query().
Vedere anche pg_send_query() e pg_connection_busy()
(PHP 3 CVS only, PHP 4 >= 4.0.3, PHP 5)
pg_client_encoding -- Restituisce la codifica caratteri del clientpg_client_encoding() restituisce la codifica carattere del client sotto forma di stringa. La stringa può essere : SQL_ASCII, EUC_JP, EUC_CN, EUC_KR, EUC_TW, UNICODE, MULE_INTERNAL, LATINX (X=1...9), KOI8, WIN, ALT, SJIS, BIG5, WIN1250.
Nota: Questa funzione richiede PHP-4.0.3 o successivi e PostgreSQL-7.0 o successivi. Se libpq è compilata senza il supporto per la codifica multibyte, pg_set_client_encoding() restituisce sempre "SQL_ASCII". Le codifiche supportate dipendono dalla versione di PostgreSQL. Consultare il manuale di PostgreSQL per i dettagli sull'abilitazione del supporto della codifica multibyte e sulle codifiche riconosciute.
Questa funzione si chiamava pg_clientencoding().
Vedere anche pg_set_client_encoding().
pg_close() chiude la connessione non persistente verso un database PostgreSQL, identificata dalla risorsa connessione. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: iL'uso di pg_close() non è normalmente necessario, dal momento che le connessioni non persistenti vengono chiuse automaticamente alla fine dell'esecuzione dello script.
Se c'è una risorsa large object aperta sulla connessione, non chiudere quest'ultima finché la risorsa non è stata chiusa a sua volta.
pg_connect() restituisce una risorsa di connessione necessaria per l'utilizzo delle altre funzioni PostgreSQL.
pg_connect() stabilisce una connessione a un database PostgreSQL specificato da stringa_connessione. Restituisce una risorsa di connessione in caso di successo. Restituisce FALSE, se la connessione non può essere stabilita. stringa_connessione dovrebbe essere una stringa racchiusa tra apici.
Esempio 1. Uso di pg_connect
|
Se viene eseguita una seconda chiamata a pg_connect() con stessi argomenti nella stringa_connessione, non viene stabilita una nuova connessione, bensì viene restituita la risorsa che punta alla connessione già aperta. Si possono avere connessioni multiple allo stesso database se si usano stringhe di connessione differenti.
La sintassi a parametri multipli: $conn = pg_connect ("host", "port", "options", "tty", "dbname") è deprecata.
Vedere anche pg_pconnect(), pg_close(), pg_host(), pg_port(), pg_tty(), pg_options() e pg_dbname().
pg_connection_busy() restituisce TRUE se la connessione è occupata. In questo caso, la query precedentamente inviata è ancora in esecuzione. Se pg_get_result() viene chiamata, verrà bloccata.
Vedere anche pg_connection_status() e pg_get_result()
pg_connection_reset() ripristina la connessione. È utile per la gestione degli errori. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
See also pg_connect(), pg_pconnect() e pg_connection_status()
pg_connection_status() restituisce lo stato di una connessione. I possibili valori sono PGSQL_CONNECTION_OK e PGSQL_CONNECTION_BAD.
Vedere anche pg_connection_busy().
(PHP 4 >= 4.3.0, PHP 5)
pg_convert -- Converte i valori di un array associativo in una forma compatibile con i comandi SQL.pg_convert() controlla e converte arrayassoc rendendolo compatibile con i comandi SQL.
Nota: Questa funzione è sperimentale.
Vedere anche pg_meta_data()
pg_copy_from() inserisce le tuple in una tabella etraendole dall'array tuple. Utilizza internamente il comando OPY per inserire i record. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Vedere anche pg_copy_to()
pg_copy_to() copia una tabella in un array. Internamente utilizza il comando SQL COPY TO per inserire le tuple. Restituisce l'array risultante. Restituisce FALSE in caso di errore.
Vedere anche pg_copy_from()
pg_dbname() restituisce il nome del database associato alla risorsa connessione Restituisce FALSE, if connessione non è una valida risorsa di connessione PostgreSQL.
pg_delete() cancella le tuple indicate dalle condizioni specificate da arrayassoc composto da campo=>valore. Se opzioni è specificato, pg_convert() viene applicata a arrayassoc con l'opzione data.
Esempio 1. pg_delete
|
Nota: Questa funzione è sperimentale.
Vedere anche pg_convert()
pg_end_copy() sincronizza il frontend PostgreSQL (normalmente un processo del server web) con il server PostgreSQL dopo aver eseguito una operazione di copia attraverso pg_put_line(). pg_end_copy() deve essere invocato, altrimenti il server PostgreSQL può rimanere fuori sincronizzazione con il frontend e restituire un errore. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Per ulteriori dettagli ed esempio, vedere anche pg_put_line().
(PHP 4 >= 4.2.0, PHP 5)
pg_escape_bytea -- Aggiunge le sequenze di escape ai dati binari nel tipo byteapg_escape_bytea() aggiunge le sequenze di escape nei dati di tipo bytea. Restituisce una stringa con le sequenze.
Nota: Quando si esegue una SELECT su un tipo bytea, PostgreSQL restituisce dei byte formattati in ottale e con il prefisso \ (es. \032). Agli utenti è lasciato il compito di convertire questi valori in formato binario.
Questa funzione richiede una versione di PostgreSQL pari o superiore alla 7.2. Con PostgreSQL 7.2.0 e 7.2.1, il tipo bytea richiede un cast quando si abilita il supporto multi-byte. Es. INSERT INTO tabella (immagine) VALUES ('$immagine_con_escape'::bytea); PostgreSQL 7.2.2 e successivi non necessitano del cast. L'eccezione è che quando le codifiche di carattere del client e del backend non corrispondono, ci possono essere errori del flusso multi-byte. L'utente deve effettuare un cast a bytea per evitare questo errore.
Le nuove versioni di PostgreSQL avranno il supporto per la funzione di unescape. Il supporto per la funzione unescape verrà aggiunto non appena disponibile.
See also pg_escape_string()
pg_escape_string() aggiunge le sequenze di escape alle stringhe di tipo text/char. Restituisce la stringa modificata con le sequenze per PostgreSQL. L'uso di questa funzione è raccomandato al posto di addslashes().
Nota: Questa funzione richiede PostgreSQL 7.2 o successivi.
Vedere anche pg_escape_bytea()
(PHP 5 >= 5.1.0RC1)
pg_execute -- Sends a request to execute a prepared statement with given parameters, and waits for the result.Sends a request to execute a prepared statement with given parameters, and waits for the result.
pg_execute() is like pg_query_params(), but the command to be executed is specified by naming a previously-prepared statement, instead of giving a query string. This feature allows commands that will be used repeatedly to be parsed and planned just once, rather than each time they are executed. The statement must have been prepared previously in the current session. pg_execute() is supported only against PostgreSQL 7.4 or higher connections; it will fail when using earlier versions.
The parameters are identical to pg_query_params(), except that the name of a prepared statement is given instead of a query string.
PostgreSQL database connection resource. When connection is not present, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().
The name of the prepared statement to execute. if "" is specified, then the unnamed statement is executed. The name must have been previously prepared using pg_prepare(), pg_send_prepare() or a PREPARE SQL command.
An array of parameter values to substitute for the $1, $2, etc. placeholders in the original prepared query string. The number of elements in the array must match the number of placeholders.
Esempio 1. Using pg_execute()
|
(PHP 5 >= 5.1.0RC1)
pg_fetch_all_columns -- Fetches all rows in a particular result column as an arraypg_fetch_all_columns() returns an array that contains all rows (records) in a particular column of the result resource.
Nota: This function sets NULL fields to PHP NULL value.
PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).
Column number, zero-based, to be retrieved from the result resource. Defaults to the first column if not specified.
An array with all values in the result column.
FALSE is returned if column is larger than the number of columns in the result, or on any other error.
Esempio 1. pg_fetch_all_columns() example
|
pg_fetch_all() restituisce un array che contiene tutte le tuple (righe/record) contenuti nella risorsa risultato. Restituisce FALSE se non ci sono tuple.
Vedere anche pg_fetch_row(), pg_fetch_array(), pg_fetch_object() e pg_fetch_result().
Esempio 1. PostgreSQL fetch array
|
pg_fetch_array() restituisce un array che corrisponde alla riga caricata (tuple/record). Restituisce FALSE se non ci sono più righe.
pg_fetch_array() è una versione estesa di pg_fetch_row(). Oltre a salvare i dati in un array con indici numerici, li salva pure in un array associativo, utilizzando i nomi dei campi come chiave.
tupla è il numero della riga (record) che deve essere caricata. La prima riga è la 0.
tipo_risultato è un parametro opzionale che controlla come il risultato viene restituito. result_type è una costante e può assumere i seguenti valori: PGSQL_ASSOC, PGSQL_NUM, e PGSQL_BOTH. pg_fetch_array() restituisce un array associativo con il nome del campo come chiave con PGSQL_ASSOC, oppure l'indice del campo con PGSQL_NUM o entrambi con PGSQL_BOTH. Il default è PGSQL_BOTH.
Nota: tipo_risultato è stato aggiunto nel PHP 4.0.
pg_fetch_array() NON è più lento di pg_fetch_row(), inoltre è più facile da usare.
Esempio 1. PostgreSQL fetch array
|
Vedere anche pg_fetch_row(), pg_fetch_object() e pg_fetch_result().
Nota: Dalla versione 4.1.0, tupla è opzionale. La chiamata a pg_fetch_array() incrementa di 1 il puntatore alle tuple.
pg_fetch_assoc() returns an associative array that corresponds to the fetched row (tuples/records). It returns FALSE, if there are no more rows.
pg_fetch_assoc() is an extended version of pg_fetch_row(). In addition to storing the data in the numeric indices (field index) to the result array, it also stores the data in associative indices (field name) by default.
row is row (record) number to be retrieved. First row is 0.
pg_fetch_assoc() is NOT significantly slower than using pg_fetch_row(), while it provides a significant ease of use.
See also pg_fetch_row(), pg_fetch_array(), pg_fetch_assoc(), pg_fetch_object() and pg_fetch_result().
Esempio 1. PostgreSQL fetch array
|
pg_fetch_object() restituisce un oggetto avente le proprietà che corrispondono alla tupla scaricata. Restituisce FALSE se non ci sono più tuple o in caso di errore.
pg_fetch_object() è simile a pg_fetch_array(), con una differenza - viene restituito un oggetto invece che un array. Indirettamente, questo significa che si può accedere ai dati solo attraverso i nomi dei campi, e non attraverso i loro indici numerici (i nomi delle proprietà non possono essere numeri).
tupla è il numero della riga (record) da caricare. La prima tupla è la numero 0.
Per quanto riguarda la velocità di esecuzione, questa funzione è identica a pg_fetch_array(), ed è veloce quasi quanto pg_fetch_row() (la differenza è trascurabile).
Nota: Dalla versione 4.1.0, tupla è opzionale.
Dalla versione 4.3.0, tipo_risultato è di default a PGSQL_ASSOC mentre il default delle versioni precedenti era PGSQL_BOTH. La proprietà numerica è inutile, dal momento che un nome di proprietà numerico non è valido in PHP.
tipo_risultato potrebbe essere abbandonato nelle versioni future.
Esempio 1. Postgres fetch object
|
Vedere anche pg_query(), pg_fetch_array(), pg_fetch_row() e pg_fetch_result().
Nota: Dalla versione 4.1.0, row è diventato opzionale. La chiamata alla pg_fetch_object() incrementa di 1 il contatore di riga interno.
pg_fetch_result() restituisce i valori da una risorsa risultato ottenuta mediante pg_query(). tupla è un intero. campo è il nome del campo (stringa) o l'indice del campo (intero). I parametri tupla e campo indicano quale cella nella tabella risultante va restituita. La numerazione delle tuple parte da 0. Invece di indicare il nome del campo, si può usare l'indice del campo sotto forma di numero senza virgolette. Gli indici dei campo partono da 0.
PostgreSQL ha molti tipi di dato e solo quelli più usati sono supportati direttamente da questa funzione. Tutti gli integer, sono restituiti come valori integer. Tutti i float, e i tipi real sono restituiti come valori float. Boolean è restituito come "t" o "f". Tutti gli altri tipi, compresi gli array, sono restituiti come stringhe formattate nello stesso modo di default che si puo vedere nel programma psql.
pg_fetch_row() carica un record dal risultato della query associato alla risorsa identificata da result. La riga (record) è restituia sotto form di array. Ogni campo è identificato da un indice numerico, che inizia da 0.
Restituisce un array che corrisponde alla riga caricata, oppure FALSE se non ci sono altre tuple.
Esempio 1. Postgres fetch row
|
Vedere anche pg_query(), pg_fetch_array(), pg_fetch_object() e pg_fetch_result().
Nota: Dalla versione 4.1.0, row è opzionale. La chiamata a pg_fetch_row() incrementa il puntatore alle tuple di 1.
pg_field_is_null() controlla se un campo è NULL o meno. Restituisce se il campo nella tupla data è NULL. Restituisce 0 se il campo nella tupla NON è NULL. Il campo può essere specificato con un indice di colonna (numero) o come un nome di campo (stringa). La numerazione comincia da 0.
Nota: Questa funzione si chiamava g_fieldisnull().
pg_field_name() restituisce il nome del campo che occupa la posizione indicata da numero_campo, rispetto alla risorsa risultato. La numerazione dei campi parte da 0.
Nota: Questa funzione si chiamava pg_fieldname().
Vedere anche pg_field_num().
pg_field_num() restituisce il numero della colonna che corrisponde al campo nome_campo nella risorsa PostgreSQL risultato spacificata. La numerazione dei campi parte da 0. Questa funzione restituisce -1 in caso di errore.
Nota: Questa funzione si chiamava pg_fieldnum().
Vedere anche pg_field_name().
pg_field_prtlen() restituisce la reale lunghezza (numero di caratteri) di uno specifico valore in un risultato di PostgreSQL. La numerazione delle tuple parte da 0. Questa funzione restituisce -1 in caso di errore.
Nota: Questa funzione si chiamava pg_field_prtlen().
Vedere anche pg_field_size().
pg_field_size() restituisce la dimensione di memorizzazione (in bytes) del campo indicato all'interno di risultato. La numerazione dei campi comincia da 0. Una dimension del campo di -1 indica un campo a lunghezza variabile. Questa funzione restituisce FALSE in caso di errore.
Nota: Questa funzione si chiamava pg_fieldsize().
Vedere anche pg_field_prtlen() e pg_field_type().
(PHP 5 >= 5.1.0RC1)
pg_field_type_oid -- Returns the type ID (OID) for the corresponding field numberpg_field_type_oid() returns an integer containing the OID of the base type of the given field_number in the given PostgreSQL result resource.
You can get more information about the field type by querying PostgreSQL's pg_type system table using the OID obtained with this function. The PostgreSQL format_type() function will convert a type OID into an SQL standard type name.
Nota: If the field uses a PostgreSQL domain (rather than a basic type), it is the OID of the domain's underlying type that is returned, rather than the OID of the domain itself.
PostgreSQL query result resource, returned by pg_query(), pg_query_params() or pg_execute() (among others).
Field number, starting from 0.
Esempio 1. Getting information about fields
Il precedente esempio visualizzerà:
|
pg_field_type() restituisce una stringa contenente il nome del tipo del campo specificato da numero_campo nella risorsa PostgreSQL specificata da risultato. La numerazione dei campi comincia da 0.
Nota: Questa funzione si chiamava pg_fieldtype().
Vedere anche pg_field_prtlen() e pg_field_name().
pg_free_result() deve essere chiamata solo se si è preoccupati di aver usato troppa memoria durante l'esecuzione dello script. Normalmente tutte le aree di memoria allocate per i risultati sono automaticamente deallocate alla fine dell'esecuzione. Se invece si è sicuri di non dover più utilizzare i dati del risultato, è possibile chiamare pg_free_result() con la risorsa result come argomento e la memoria associata verrà liberata. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Nota: Questa funzione si chiamava pg_freeresult().
See also 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()
Esempio 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() estrae la risorsa risultato dalle query asincrone eseguite da pg_send_query(). pg_send_query() può inviare query multiple al server PostgreSQL server e pg_get_result() è utilizzat per recuperare i risultati uno ad uno. Restituisce la risorsa risultato. Se non ci sono più risultati, restituisce FALSE.
pg_host() restituisce il nome dell'host a cui la risorsa PostgreSQL connessione è connessa.
Vedere anche pg_connect() e pg_pconnect().
pg_insert() inserisce array_assoc composto da campo=>valore nella tabella specificata da nome_tabella. Se opzioni è specificato, pg_convert() è eseguita su array_assoc con le opzioni date.
Nota: Questa funzione è sperimentale.
Vedere anche pg_convert()
pg_last_error() restituisce l'ultimo messaggio di errore della connessione specificata.
I messaggi di errore possono essere sovrascritti da chiamate a funzioni interne a PostgreSQL(libpq). Quindi questa funzione potrebbe non restituire il messaggio di errore corretto, se più errori si sono verificati in una funzione interna di PostgreSQL.
Utilizzare pg_result_error(), pg_result_status() e pg_connection_status() per una migliore gestione degli errori.
Nota: Questa funzione si chiamava pg_errormessage().
Vedere anche pg_result_error().
(PHP 4 >= 4.0.6, PHP 5)
pg_last_notice -- Restituisce l'ultimo messaggio di notifica dal server PostgreSQLpg_last_notice() restituisce l'ultimo messaggio di notifica emesso dal server PostgreSQL specificato dal parametro connessione. Il server PostgreSQL invia messaggi di notifica in parecchi case, per esempio se le transazioni non possono essere continuate. Con pg_last_notice() è possibile evitare di eseguire query inutili, controllando se la notifica è relativa alla transazione o meno.
Avvertimento |
Questa funzione è SPERIMENTALE e non è completamente implementata allo stato attuale. pg_last_notice() è stato aggiunta nel PHP 4.0.6. Comunque, il PHP 4.0.6 ha dei problemi con la manipolazione dei messaggi di notifica. L'uso del modulo PostgreSQL con il PHP 4.0.6 non è raccomandato anche se non si fa uso di pg_last_notice(). Questa funzione è completamente implementata in PP 4.3.0. Le versioni di PHP precedenti alla 4.3.0 ignorano il parametro di connessione al database. |
Il tracciamento dei messaggi di notifica può essere reso opzionale impostando a 1 la variabile pgsql.ignore_notice nel file php.ini a partire dal PHP 4.3.0.
Il log dei messaggi di notifica può essere reso opzionale impostando a 0 la variabile pgsql.log_notice nel file php.ini a partire dal PHP 4.3.0. A meno che pgsql.ignore_notice sia impostato a 0, i messaggi di notifica non possono essere registrati.
See also pg_query() e pg_last_error().
pg_last_oid() è utilizzato per recuperare l'oid assegnato ad una tupla inserita (record), se la risorsa risultato deriva dall'ultimo comando inviato attraverso pg_query(), e se quest'ultimo è un SQL INSERT. Restituisce un intero positivo se esiste un oid valido. Restituisce invece FALSE in caso di errore o se l'ultimo comnado inviato da pg_query() non era un INSERT, oppure se l'INSERT ha fallito.
Il campo OID è diventato opzionale dal PostgreSQL 7.2. Quando il campo OID non è definito in una tabella, il programmatore deve utilizzare pg_result_status() per controllare se il record è stato inserito con successo.
Nota: Questa funzione si chiamava pg_getlastoid().
Vedere anche pg_query() e pg_result_status()
pg_lo_close() chiude un Large Object. large_object è una risorsa large object ottenuta attraverso pg_lo_open().
Per utilizzare l'interfaccia large object (lo), è necessario includere la chiamata in un blocco di transazione.
Nota: Questa funzione si chiamava pg_loclose().
Vedere anche pg_lo_open(), pg_lo_create() e pg_lo_import().
pg_lo_create() crea un Large Object e restituisce l'oid dello stesso. connessione specifica una connessione valida al database aperta da pg_connect() o pg_pconnect(). I modi di accesso di PostgreSQL INV_READ, INV_WRITE e INV_ARCHIVE non sono supportati, l'oggetto è sempre creato con accesso sia in lettura che in scrittura. INV_ARCHIVE è stato rimosso da PostgreSQL (versioni 6.3 e successive). La funzione restituisce l'oid del large object, altrimenti restituisce FALSE in caso di errore.
Per utilizzare l'interfaccia large object (lo) è necessario includerla in un blocco di transazione.
Nota: Questa funzione si chiamava pg_locreate().
L'argomento oid specifica l'oid del large object da salvare e l'argomento percorso specifica il percorso del file. Restituisce FALSE in caso di errore, TRUE altrimenti.
Per utilizzare l'interfaccia large object (lo), occorre includere il comando in un blocco di transazione.
Nota: Questa funzione si chiamava pg_loexport().
Vedere anche pg_lo_import().
Nelle versioni precedenti al PHP 4.2.0 la sintassi di questa funzione era differente, come nella seguente definizione:
int pg_lo_import ( string percorso [, resource connessione] )Il parametro percorso specifica il percorso del file che deve essere importato nel large object. Restituisce FALSE in caso di errore, altrimenti l'oid del large object appena creato.
Per utilizzare l'interfaccia large object (lo), occorre includere il comando in un blocco di transazione.
Nota: Quando safe-mode è abilitato, PHP controlla che i file o le directory sulle quali si sta andando a lavorare, abbiano lo stesso UID dello script che è in esecuzione.
Nota: Questa fuinzione si chiamava pg_loimport().
Vedere anche pg_lo_export() e pg_lo_open().
pg_lo_open() apre un Large Object e restituisce una risorsa (riferimento) large object. La risorsa incapsula le informazioni sulla connessione. oid specifica un oid valido di un large object e modo può essere "r", "w", o "rw". Restituisce FALSE se avviene un errore.
Avvertimento |
Non chiudere la connessione al database prima di aver chiuso il large object. |
Per utilizzare l'interfaccia large object (lo), occorre includere il comando in un blocco di transazione.
Nota: Questa funzione si chiamava pg_loopen().
Vedere anche pg_lo_close() e pg_lo_create().
(PHP 4 >= 4.2.0, PHP 5)
pg_lo_read_all -- Legge interamente un large object e lo manda direttamente al browserpg_lo_read_all() legge un large object e lo passa direttamente al browser dopo aver inviato tutti gli header in attesa. È pensata principalmente per inviare dati binari, come immagini o suoni. Restituisce il numero di byte letti. Restituisce FALSE in caso di errore.
Per utilizzare l'interfaccia large object (lo), occorre includere il comando in un blocco di transazione.
Nota: Questa funzione si chiamava pg_loreadall().
Vedere anche pg_lo_read().
pg_lo_read() legge al massimo lung byte da un large object e li restituisce sotto forma di stringa. large_object specifica una risorsa large object valida e lung specifica la lunghezza massima accettabile del segmento del large object. Restituisce FALSE in caso di errore.
Per utilizzare l'interfaccia large object (lo), occorre includere il comando in un blocco di transazione.
Nota: Questa funzione si chiamava pg_loread().
Vedere anche pg_lo_read_all().
pg_lo_seek() ricerca la posizione di un large object. whence è PGSQL_SEEK_SET, PGSQL_SEEK_CUR o PGSQL_SEEK_END.
Vedere anche pg_lo_tell().
pg_lo_tell() restituisce la posizione attuale (offset dall'inizio di un large object).
Vedere anche pg_lo_seek().
pg_lo_unlink() cancella un large object identificato da oid. Restituisce TRUE in caso di successo, FALSE in caso di fallimento.
Per utilizzare l'interfaccia large object (lo), occorre includere il comando in un blocco di transazione.
Nota: Questa funzione si chiamava pg_lo_unlink().
Vedere anche pg_lo_create() e pg_lo_import().